LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 3

When reset destroys the object Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

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

struct T {
    char c;
    explicit T(char x) : c(x) { std::cout << '+' << c; }
    ~T() { std::cout << '-' << c; }
};

int main() {
    auto p = std::make_unique<T>('a');
    p.reset(new T('b'));
    p = std::make_unique<T>('c');
    std::cout << '|';
    p.reset();
    std::cout << '|' << '\n';
    return 0;
}
  • A +a+b-a+c-b|-c| Correct
  • B +a-a+b-b+c|-c|
  • C +a+b+c|-c-b-a|
  • D +a+b-a+c-b|-c
Correct Answer: Option A

The new object is created first, then the old one is deleted when ownership switches. reset() with no argument deletes c.

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