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;
  • 1
    `string& t1 = *p1;` What have you done here? – smac89 Sep 08 '18 at 21:58
  • 1
    `string *p1 = new string("test1");` - it is almost _never_ necessary or desirable to dynamically allocate a string like this. –  Sep 08 '18 at 21:59
  • Assigning to t1 the value that p1 is pointing to. – Jurgen Padilla Sep 08 '18 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. – Jurgen Padilla Sep 08 '18 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 – smac89 Sep 08 '18 at 22:02
  • Yes I know, and thats the behaviour that I'm expecting on the first example, too. But as I said "t" is still holding a value, that is a reference to something that shouldn't exist – Jurgen Padilla Sep 08 '18 at 22:07
  • Somewhat related (there must be lots of duplicates for this) https://stackoverflow.com/questions/22404296/delete-pointer-does-not-delete-all-the-memory-array And this https://stackoverflow.com/questions/34055639/values-still-accessible-after-i-call-delete-c – Galik Sep 08 '18 at 23:51
  • And https://stackoverflow.com/questions/2896238/dereferencing-deleted-pointers-always-result-in-an-access-violation – Galik Sep 08 '18 at 23:58

1 Answers1

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)
eerorika
  • 232,697
  • 12
  • 197
  • 326