LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 15

Swapping unique_ptrs Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

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

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

int main() {
    auto a = std::make_unique<std::string>("left");
    auto b = std::make_unique<std::string>("right");
    std::string* before = a.get();
    a.swap(b);
    std::cout << *a << ' ' << *b << ' ' << (b.get() == before) << '\n';
    return 0;
}
  • A right left 1 Correct
  • B left right 1
  • C right left 0
  • D left right 0
Correct Answer: Option A

swap exchanges the owned pointers; the strings themselves never move in memory.

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