Home > Back-end >  How does std::unique_ptr handle raw pointers/references in a class?
How does std::unique_ptr handle raw pointers/references in a class?

Time:12-14

Let's say I have a class A with the following definition:

class A {
  A(std::string& s) : text_(s) {}

 private:
  std::string& text;
}

Note that A contains a reference to a string object. This can be because we don't want to copy or move the object.

Now, if I have the following code

std::string text = "......";
std::unique_ptr<A>(new A(text));
// now I destroy text in some way, either explicitly call the deconstructor or it goes out of scope somehow

The question is what happens now to the unique_ptr's object A? The A contained a reference to the object text which is deleted. Does unique_ptr's A have now a dangling pointer? Or does unique_ptr handle this case and extend the lifetime of the object for which it contains a raw pointer?

CodePudding user response:

C is not a safe language. If you have a pointer or reference to an object that is destroyed, using that pointer or reference is a bug.

Assuming you actually construct an A that outlives text, it will still reference the destroyed object, and any use of that member is undefined behaviour.

  • Related