Modern C++ • C++20 baseline
Constructors, Destructors, and Object Lifetimes
Establish a valid object at construction and release owned resources at destruction.
A constructor initializes an object before it can be used. A destructor runs when the object lifetime ends. Prefer member initialization lists because they initialize members directly in declaration order. Destructors should generally not let exceptions escape.
Key points
- Members initialize in declaration order, regardless of initializer-list order.
- A destructor is called for local objects when scope exits, including many exception paths.
Example
#include <string>
#include <utility>
class UserName {
public:
explicit UserName(std::string value)
: value_(std::move(value)) {}
const std::string& value() const noexcept { return value_; }
private:
std::string value_;
};
What to expect
Construction moves the argument into the member; destruction releases the std::string resource automatically.
Practice exercise
Add an invariant that rejects an empty name. Decide how construction communicates invalid input.
Key idea: Tie resource lifetime to object lifetime using standard resource-owning members.