1

This the first question I'm doing. I've searched a lot but couldn't find the answer. I'm learning the use of smart pointers on c++14 and the compiler is g++ 5.4. I want to know why is the variable "t" still prints a value when the reassignment of the shared_ptr should destroy that object. As it does in the second example. Thanks in advance!

shared_ptr<string> p = make_shared<string>("test1"); string& t = *p.get(); cout<<t<<endl; p = make_shared<string>("test2"); cout<<t<<endl; cout<<"Second Example\n"; string *p1 = new string("test1"); string& t1 = *p1; cout<<t1<<endl; delete p1; cout<<t1<<endl; 
8
  • 1
    string& t1 = *p1; What have you done here? Commented Sep 8, 2018 at 21:58
  • 1
    string *p1 = new string("test1"); - it is almost never necessary or desirable to dynamically allocate a string like this. Commented Sep 8, 2018 at 21:59
  • Assigning to t1 the value that p1 is pointing to. Commented Sep 8, 2018 at 22:00
  • Is just an example, i want to know the reason why "t" is still holding a value when the pointer is gone. Commented Sep 8, 2018 at 22:01
  • Assigning to t1 the value... but t1 is supposed to be a reference type. The value you assign it is not an address but a value type Commented Sep 8, 2018 at 22:02

1 Answer 1

4

I want to know why is the variable "t" still prints a value when the reassignment of the shared_ptr should destroy that object.

Because the behaviour of accessing destroyed objects is undefined. Possible behaviours include, none of which are guaranteed:

 - working - not working - random output - non-random output - the expected output - unexpected output - no output - any output - crashing at random - crashing always - not crashing at all - corruption of data - different behaviour, when executed on another system - , when compiled with another compiler - , on tuesday - , only when you are not looking - same behaviour in any or all of the above cases - anything else within the power of the computer (hopefully limited by the OS) 
Sign up to request clarification or add additional context in comments.

5 Comments

You forgot, - working when you use a debugger, - not working when you don't
Sir, I am stealing your UB list
you forgot - ordering pizza
Oh now I see, it shouldn't work but it does. Thanks a lot! Since I did a lot of tests and in all of them the undifined behaviour was "working". It was strange that with shared_ptr always worked. Thanks again!
@JurgenPadilla There is no such requirement that "it shouldn't work". Nothing can be expected of the behaviour of the program as far as the standard is concerned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.