LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Find the Error · Question 8

Error: copying a class that holds a unique_ptr Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>
#include <memory>

class Session {
    std::unique_ptr<int> token_ = std::make_unique<int>(42);
public:
    int token() const { return *token_; }
};

int main() {
    Session a;
    Session b = a;
    std::cout << b.token() << '\n';
    return 0;
}
  • A make_unique cannot be used in a member
  • B std::unique_ptr is move-only, so Session's implicit copy constructor is deleted; move it (Session b = std::move(a);) or use shared_ptr / a custom deep copy Correct
  • C token must be static
  • D Session needs a destructor
Correct Answer: Option B

A class is copyable only if all its members are. The compiler deletes the copy operations automatically, which is usually exactly right for unique ownership.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links