Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does std::unique_ptr handle raw pointers/references in a class?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading