LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 8

unique_ptr::release hands back the raw pointer Answer, explanation & discussion

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

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

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

struct R { ~R() { std::cout << "~R "; } };

int main() {
    auto p = std::make_unique<R>();
    R* raw = p.release();            // p no longer owns it
    std::cout << (p == nullptr) << ' ';
    {
        std::unique_ptr<R> q(raw);  // a new owner takes over
    }
    std::cout << "end\n";
    return 0;
}
  • A 1 ~R end Correct
  • B 0 ~R end
  • C 1 end
  • D 1 end ~R
Correct Answer: Option A

release() gives up ownership without deleting; q adopts the pointer and deletes it at the end of its scope.

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