Boost :: shared_ptr and assignment of derived classes

Suppose DerivedClass derived from BaseClass
Will there be a next job?

 boost::shared_ptr<BaseClass> a(new BaseClass()); boost::shared_ptr<DerivedClass> b(new DerivedClass()); a=b; 

After this question, I understand that now a points to the derivative and b points to the base (right?)

Also, now if I call a function via a , will it call a derived implementation?

+7
source share
3 answers
 ... a=b; 

You reassign to a , and so a and b will now point to a DerivedClass object. The BaseClass object will be destroyed, because at that moment its reference count will be zero (by virtue of a , which will be reassigned to point to another object).

Since a now points to a DerivedClass object, calls to virtual functions (defined in BaseClass and override in DerivedClass ) through a will call the corresponding member functions in DerivedClass .

When both a and b disappear from scope, the DerivedClass object will be destroyed.

If you need to access functions related to a derived class through a (for example, non-virtual functions in DerivedClass ), you can use:

 boost::dynamic_pointer_cast<DerivedClass>(a)->SomeFunctionOnlyInDerivedClass(); 

Of course, this is just a brief example showing usage. In production code, you will almost certainly experience a successful click on DerivedClass before dereferencing a pointer.

+13
source

Suppose DerivedClass derived from BaseClass . Will there be a next job?

Yes. Just as there is nothing wrong with

 boost::shared_ptr<BaseClass> pbase(new DerivedClass()); 

(Assuming in both cases that BaseClass has a virtual destructor.) The smart pointer is designed for maximum possible behavior as a simple pointer and provides the same behavior as BaseClass* pbase = new DerivedClass(); as well as everything you need to manage your life cycle.

Following this question, I understand that now a points to the derivative and b points to the base (right?)

No, a and b both point to an instance of DerivedClass. The paging referenced by the linked article occurs on a temporary object inside the = operator. When this temporary object goes out of scope, the BaseClass instance will be deleted.

Also, now if I call a function via a , will it call a derived implementation?

Yes. If you look at the implementation of operator->, all it does is return a pointer to which the main operator-> should be called:

 T * operator-> () const // never throws { BOOST_ASSERT(px != 0); return px; } 

so that the behavior is the same as a regular pointer.

+4
source

When doing a = b, you point to point to the object b also points to. Thus, all the methods that you call, you call in the BaseClass part of the object b, points to.

So, if it contains a virtual method that is overwritten in the DerviedClass, the overwritten version is called.

+3
source

All Articles