1

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.

lei_z
  • 1,049
  • 2
  • 13
  • 27
  • 9
    Undefined behavior is undefined. – user657267 Nov 10 '15 at 09:16
  • This is indeed undefined behavior. But I'm curious. What did you expect it to print? – selbie Nov 10 '15 at 09:19
  • Deleting the string does not neccessarily mean removing it from memory. It could be still reachable. – Daniel Walter Nov 10 '15 at 09:20
  • @selbie I expect the program to crash, just as when I dereference a pointer whose memory block is already freed. – lei_z Nov 10 '15 at 09:20
  • @lei.april You have an incorrect expectation of **undefined** behavior. – user657267 Nov 10 '15 at 09:21
  • @lei.april - that's not a valid assumption. Memory is memory. While not safe (and technically undefined), you can typically "read" unallocated memory it as long as it's being retained by the runtime's memory manager. As for writing to unallocated memory and/or acting on objects based on that memory - definitely unsafe. Undefined at best. – selbie Nov 10 '15 at 09:23
  • @user657267 Well, IIRC, I always crash my C program whenever accessing freed memory block. Perhaps this behavior does apply everywhere... – lei_z Nov 10 '15 at 09:25
  • @lei.april It might crash, it might not, it might buy you a pizza - all of these are valid outcomes. – user657267 Nov 10 '15 at 09:25

0 Answers0