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;
string& t1 = *p1;What have you done here?string *p1 = new string("test1");- it is almost never necessary or desirable to dynamically allocate a string like this.t1is supposed to be a reference type. The value you assign it is not an address but a value type