Skip to content
cppadvanced

Modern C++

Smart pointers, move semantics and lambdas

7 questions

By EZ4Code Team

1. What are the characteristics of std::unique_ptr?

Exclusive ownership, non-copyable, movable only
Shared ownership
Copyable
Does not manage resources
Explanation: unique_ptr exclusively owns the pointed-to object; it cannot be copied but can be moved (std::move), and is released automatically when leaving scope, a zero-overhead abstraction.

2. Is std::shared_ptr's reference count atomic and thread-safe?

Yes, the reference count itself is atomic and thread-safe
Non-atomic
No counting needed
Determined at compile time
Explanation: shared_ptr's reference count uses atomic operations and is thread-safe; however, access to the pointed-to object still requires external synchronization.

3. What is the main purpose of move semantics?

To avoid unnecessary deep copies and transfer resource ownership
To speed up compilation
To replace references
To implement polymorphism
Explanation: Move semantics uses rvalue references (&&) and move constructors/assignment to transfer resources (such as heap pointers) rather than copying, improving performance.

4. What does std::move actually do?

Unconditionally casts an lvalue to an rvalue reference to trigger move semantics
Actually moves data
Destroys the object
Copies the object
Explanation: std::move is a wrapper around static_cast<T&&>; it only performs a type cast and does not move any data; the actual move is done by the move constructor/assignment.

5. What is the purpose of the [] part in a Lambda expression [capture](params){body}?

To specify how external variables are captured (by value or by reference)
To declare parameters
To declare the return type
To declare exceptions
Explanation: [] is the capture list: [=] captures all by value, [&] captures all by reference, [x] captures x by value, [&x] captures x by reference.

6. What does the auto keyword do?

Automatically deduces the variable type at compile time
Dynamic typing
Declares a global variable
Declares a constant
Explanation: auto lets the compiler deduce the variable type from the initializer expression; it is still statically typed and simplifies writing long type names.

7. What is the purpose of the rvalue reference T&&?

To bind to rvalues (temporaries), enabling move semantics and perfect forwarding
To replace lvalue references
To declare constants
To declare pointers
Explanation: T&& is an rvalue reference that can bind to temporary objects; combined with std::forward it enables perfect forwarding and is the foundation of move semantics.

More cpp Quizzes