Questions / Quant development, C++ ownership & memory

Express exclusive ownership

Foundation, about 6 minutes. Question D011.

A C++ object has one owning component and must be destroyed automatically when ownership ends. Which standard smart pointer expresses that most directly?

  1. AA raw pointer can do it if the owner deletes it in every exit path.
  2. BUse std::weak_ptr for observed ownership.
  3. CUse std::unique_ptr for exclusive ownership.
  4. DUse std::shared_ptr for shared ownership.

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: C. Use std::unique_ptr for exclusive ownership.

  1. The problem specifies one owner and automatic destruction when that ownership ends.
  2. unique_ptr encodes an exclusive owning handle and releases the managed object when the handle ends or is reset.
  3. Choose shared_ptr when shared ownership is an actual requirement, rather than merely a possible implementation.

Interview shortcut. One owner, automatic cleanup: unique_ptr.

Takeaway. Express the lifetime contract in the ownership type.

Why the other choices fail

  • A raw pointer can do it if the owner deletes it in every exit path. Manual delete is not automatic; an exception or early return can skip it.
  • Use std::weak_ptr for observed ownership. weak_ptr is non-owning. It cannot provide the required owning lifetime on its own.
  • Use std::shared_ptr for shared ownership. shared_ptr represents a potentially shared lifetime. It can manage destruction, but does not express the requested exclusivity as directly.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More c++ ownership & memory questions