-
August 12th, 2013, 12:41 AM
#1
shared pointer and up-casting
Hi,
I trying to learn about the boost::shared_ptr and I have a problem.
Let's say that I have a base class A and a derived class B.
Using smart pointers, I would like to be as efficient as possible, meaning that I don't want in increase the counter of a variable if it is not necessary.
Let's say that i have 1 variables:
shared_ptr<B> b(new B);
Now, if i write this:
const shared_ptr<B> &c = b;
then the b counter was not increment, perfect.
but if I write this:
const shared_ptr<A> &c = b;
or const shared_ptr<A> &c = static_pointer_cast<A>(b);
then the b counter was increased.
This is a problem when passing b as an argument of a function from the base class A.
I don't want to debate if I should mind or not because it probably won't cause any performance issue, but I would like to know if there is a way to cast from B to A without incrementing the counter.
So far, the only way I found working (I am not sure if this is safe) is:
const shared_ptr<A> &c = *(const shared_ptr<A> *)&b;
Does someone have a clean solution to up cast an object without incrementing the reference counter?
I am a bit lost here.
Thank you for reading my post,
madric
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|