0

I tried fiddling around with the unique_ptr.

Why does the line marked with MK1 (comment) not crash my program?

Foo destructor is called. By using unique_ptr I thought both the destructor for the object was called and deleted the memory allocated for the object itself.

I'm guessing its unique, so I shouldnt let others point to the same Foo?

void ExMemory() {
  Foo *simplePtr;
  {
    std::unique_ptr<Foo> p1(new Foo);
    simplePtr = &*p1; // Does unique_ptr increment a reference counter?
    p1->bar();
    simplePtr->bar();
  }
  simplePtr->bar(); // MK1: Why can I do this? Foo destructor is called.
  delete simplePtr;
  simplePtr->bar(); // Causes the error I expected earlier.
}

int main() {
  cout << "Hello main" << endl;
  ExMemory();
  int x;
  cin >> x;
  return 0;
}
Peheje
  • 12,542
  • 1
  • 21
  • 30
  • The preferred way of getting the address of an object stored in an `std::unique_ptr` is using `get()` rather than `&*` – François Andrieux Jan 06 '17 at 18:26
  • Without the definitions of the `Foo` class and its `bar` method, I'm not sure you're accessing uninitialized memory. (If the method is non-virtual and doesn't use any instance data...) Even if you are, addressing unallocated memory is *undefined*, not guaranteed to crash. Since you're doing it right after deallocation, the data form the object may still be there just by dumb luck. – Mark Adelsberger Jan 06 '17 at 18:29
  • The code is also deleting the same memory address twice (once in the `unique_ptr` destructor, and again in the `delete simplePtr` statement). That is also not guaranteed to crash, but it can also trash memory, which might explain why the `bar()` call on the MK1 line before the `delete` does not crash but the `bar()` call after the `delete` does. – Remy Lebeau Jan 06 '17 at 18:36
  • Thanks everyone! Sorry for the duplicate :-) – Peheje Jan 07 '17 at 19:50

0 Answers0