[shared pointer] - question about different types pointing to the same object
I've looked through the shared_ptr documentation and am still puzzled about something. suppose I have class base1 { virtual ~base1; ... }; class derived1 : public base1 { .... }; shared_ptr<derived1> pd1(new derived1) shared_ptr<base1> pb1(pd); ? do pd1 and pb1 refer to the same object? class base2 { virtual ~base2; ... }; class derived3 : public base1, public base2 { ... }; shared_ptr<base2> pb2(pd1); ? do pb1 and pb2 refer to the same object? I'm presuming they do, but it's not really clear to me that this would work. To check this I could downcast everything to derived3. BUT when I have pb1 and pb2, I don't know what to downcast to. since there could be class derived4 : public base1, public base2 { ... }; So how could I verify whether an arbitrary pb1 and pb2 point to the same object or not? Robert Ramey
On Saturday 06 June 2009, Robert Ramey wrote:
class base1 { virtual ~base1; ... }; class derived1 : public base1 { .... };
shared_ptr<derived1> pd1(new derived1) shared_ptr<base1> pb1(pd);
? do pd1 and pb1 refer to the same object?
Yes, shared_ptr behaves pretty much the same as raw pointers.
class base2 { virtual ~base2; ... }; class derived3 : public base1, public base2 { ... };
shared_ptr<base2> pb2(pd1);
? do pb1 and pb2 refer to the same object?
No, that wouldn't compile as base2 is not a base class of derived1.
On Sat, Jun 6, 2009 at 4:12 PM, Robert Ramey <ramey@rrsd.com> wrote:
So how could I verify whether an arbitrary pb1 and pb2 point to the same object or not?
If you want to check whether two shared_ptr objects p and q share ownership (that is, manage the same object), you can use: !(p<q) && !(q<p) However, you're probably asking with serialization in mind. I don't think serialization can support the most general shared_ptr use cases, since it supports aliasing: a shared_ptr<int> might point to an int within a larger object of user-defined type T. Obviously, when such shared_ptr is serialized what you want is to serialize the T, so you need some sort of cast-like operation to get to the T address, knowing the address of the int. Obviously this is not possible in general. (My last blog post might also be helpful in understanding shared_ptr better.) Emil Dotchevski Reverge Studios, Inc. http://www.revergestudios.com/reblog/index.php?n=ReCode
participants (3)
-
Emil Dotchevski
-
Frank Mori Hess
-
Robert Ramey