|
Boost : |
Subject: Re: [boost] Weak pointer to object not managed by a shared_ptr
From: Stewart, Robert (Robert.Stewart_at_[hidden])
Date: 2009-09-03 12:27:51
Mateusz Loskot wrote:
>
> simple testes using GCC 4.3 and Visual C++ 9.0 show that destruction
> occurs in different point than we expect:
Perhaps it is different than you expected.
> 1) I added verbose destructor to X
>
> ~X() { cout << "X dtor\n"; }
>
> 2) Compiled and executed the following use case of X:
>
> shared_ptr<X> spx;
> {
> X x1(7);
> spx = shared_ptr<X>(x1.get_weak_ptr());
> } // *** x1 is being destructed
> cout << spx->get_i() << std::endl;
>
> mloskot_at_dog:~$ g++ -Wall -pedantic weak_ptr_local.cpp
> mloskot_at_dog:~$ ./a.out
> X dtor
> 7
> deleter
> mloskot_at_dog:~$
>
> So, x1 is destructed but its value of 7 is still accessible.
x1 went out of scope. A shared_ptr referencing its address does nothing to extend it's lifetime.
> I assume I'm observing UB here. I understand nature of UB and that
> it can give unexpectedly 'correct' results.
As Overmind showed, the stack has yet to be overwritten by that point, so the bits exist. What is undefined is accessing what used to be an object after its destructor ran. That you can see the value is due to X::~X() not overwriting it and of the data member type not having a destructor that likewise does something destructive.
_____
Rob Stewart robert.stewart_at_[hidden]
Software Engineer, Core Software using std::disclaimer;
Susquehanna International Group, LLP http://www.sig.com
IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk