I have the following piece of code:
#include <iostream>
#include <memory>
using namespace std;
int main() {
string* s = new string("foo");
{
unique_ptr<string> ss(s);
}
cout << *s << endl;
}
If I understand unique pointer correctly, ss
should gain ownership of the string object pointed by s
once it's declared and then destroys the object when it exits its local scope.
However, the cout
statement still runs normally, which means the string object is not destroyed at all. Could you explain what's happening here? Thanks.
PS: I tested the code with both g++ and clang on OS X.
Edit: OK, I understand now this is undefined behavior. Thanks for all the useful comments.