What is the main purpose of smart pointers?
They apply RAII to heap memory.
Smart Pointers · Exercise 1 of 4
Twenty multiple-choice questions on C++ smart pointers: unique_ptr, shared_ptr, weak_ptr, make_unique and make_shared, reference counting, cycles, custom deleters and passing conventions. Pick an option to check your answer instantly.
What is the main purpose of smart pointers?
They apply RAII to heap memory.
What happens with auto b = a; when a is a std::unique_ptr?
Moving transfers ownership and leaves a empty.
After auto q = std::move(p); with unique_ptrs, what is p?
unique_ptr guarantees the moved-from pointer is null.
When is the object managed by shared_ptrs deleted?
The strong reference count reaches zero.
Does creating a std::weak_ptr from a shared_ptr increase use_count()?
lock() returns a temporary shared_ptr, which does increase the count while it exists.
What does w.lock() return when the object has already been destroyed?
Constructing shared_ptr from an expired weak_ptr (instead of lock) throws std::bad_weak_ptr.
A parent holds shared_ptr to its child and the child holds shared_ptr to its parent. How do you avoid the leak?
The owning direction stays shared; the back-link only observes.
What is an advantage of std::make_shared<T>() over std::shared_ptr<T>(new T)?
One drawback: the memory of the object cannot be freed while weak_ptrs keep the combined block alive.
What is the difference between p.release() and p.reset() for a unique_ptr?
Calling release() and ignoring the result is a leak.
What happens if you delete p.get(); for a unique_ptr p?
get() returns a non-owning pointer; never delete it.
Timed online tests with instant scores and explanations.