LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 8

Self-move assignment with a guard Answer, explanation & discussion

  • Output
  • Hard
  • 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 <utility>

class Holder {
    int* p_;
public:
    explicit Holder(int v) : p_(new int(v)) {}
    ~Holder() { delete p_; }
    Holder(const Holder&) = delete;
    Holder& operator=(Holder&& o) noexcept {
        if (this == &o) { std::cout << "[self] "; return *this; }
        delete p_;
        p_ = std::exchange(o.p_, nullptr);
        return *this;
    }
    int value() const { return p_ ? *p_ : -1; }
};

int main() {
    Holder a(7), b(9);
    a = std::move(a);
    b = std::move(a);
    std::cout << a.value() << ' ' << b.value() << '\n';
    return 0;
}
  • A [self] -1 7 Correct
  • B [self] 7 7
  • C -1 7
  • D [self] -1 9
Correct Answer: Option A

Without the guard, a = std::move(a) would delete p_ and then read the freed pointer. The second move frees 9, takes 7 and empties a.

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