0

I'm trying to experience with smart_ptrs and so I was trying to return a unique_ptr from a function :

unique_ptr<int> foo()
{
    int x = 100;
    unique_ptr<int> up(new int);
    cout << "value stored in up : " << *up << endl;
    cout << "get : " << up.get() << endl;
    up.reset(&x);
    cout << "value stored in up : " << *up << endl;
    cout << "get : " << up.get() << endl;
    return up;
}

int main()
{
    auto up = foo();
    cout << "value stored in up : " << *up << endl;
    cout << "get : " << up.get() << endl;
    return 0;
}

As I expected up in main is pointing to the same address up in foo was last pointing at, and just before the print statement in main up holds 100 as I expected it too, the problem is right before I print the value stored in up, it gets reset and so I print something else followed up by a failed debug assertion and I'm clueless to why it happens..

enter image description here

dikson231
  • 201
  • 5
  • 10
  • @πάντα ῥεῖ I know memory of local variable can be accessed outside of it's function, but in my example the memory get overwritten and I don't understand why. Another example - http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions work just fine for me but when I use up.reset(&x) and return it then and only then the value inside this memory address get reset and I get the debug assertion failed and I don't see why – dikson231 Feb 14 '15 at 13:46
  • _"I know memory of local variable can be accessed outside of it's function"_ No, it can't be accessed without calling for undefined behavior. Also `std::unique_ptr`, will try to `delete` an adress, that was allocated on the stack, as soon going out of scope in `main()`. – πάντα ῥεῖ Feb 14 '15 at 13:49
  • @πάνταῥεῖ I didn't know about the second part you mentioned, thanks – dikson231 Feb 14 '15 at 13:52

0 Answers0