Copy semantics, the Rule of Three/Five. If your class owns a resource and frees it in the destructor, the compiler-generated copy constructor and copy assignment do a shallow copy of the members, so two objects end up owning the same resource and both destructors release it, a double-free or double-release. You have three options: implement the copy constructor and copy assignment to do a deep copy or proper ownership transfer (Rule of Three; add move operations for Rule of Five), delete them (Class(const Class&) = delete;) to forbid copying, or, best, design so you don't manage a raw resource directly: hold it in a member type that already cleans up after itself, so you need no special functions at all (the Rule of Zero). On embedded, deleting copies on a hardware-owning class (you can't have two objects driving the same UART) is often the right, intent-revealing choice.
C++ for Embedded · Interview question
If a class has a destructor that releases a resource, what else must you consider?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Constructors, Destructors & RAII
Tie setup to object creation and cleanup to scope exit, so you can't forget to release a lock, disable a clock, or re-enable interrupts. The defining C++ idiom for embedded.
More Constructors, Destructors & RAII questions
What is RAII and why is it especially valuable in embedded?Write an RAII guard for a critical section. Why is it better than paired enable/disable calls?Why prefer the member initializer list over assigning members in the constructor body?In what order are destructors called, and why does it matter?
Browse all 472 interview questions