Pointer to an element in the force pointer container

I'm just starting to use boost::ptr_vector . I have ptr_vector pctr as a member of one class A and want another class B to refer to an element in pctr . When building an object of class B, I want to save the pointer in pctr .

Since the pointer containers do not allow access to the pointer (but only to the links), I have to take the link address from pctr and then save it in an object of type B. But given the link address, it seems unintuitive. Is there a better alternative?

+4
source share
2 answers

As you have discovered, containers with an acceleration indicator guard their pointers well. Of course, you can defeat it by taking the address of the links that it gives, but keep in mind that you can dilute the power of the container-pointer to authoritarian property by hanging pointers on them (it all depends on the rest of your code actually).

Alternatives are as follows:

  • Ask class B iterators to refer to the pointer container element of interest (of course, the usual rules for canceling an iterator should be considered).

  • Since A owns pointers, and you seem to want B to hold some kind of one that doesn't have a weak reference to it, use the shared_ptr container instead and use B weak_ptr . The disadvantage may depend on performance.

+2
source

I think that addressing the dereferenced iterator address is the right way to achieve what you are trying to do.

 iterator it = ... T *ptr = &*it; 

However, this is dangerous because you can end up with dangling pointers if object A is destroyed before objects B. That's why the release function, which allows the caller to take the address of the object, also remove the pointer from the container.

If you can support overhead, you might consider changing boost::ptr_vector to a smart pointer vector, for example. std::vector<boost::shared_ptr<T> > .

0
source

Source: https://habr.com/ru/post/1286064/


All Articles