← Back to Question List
C++ Code Walkthrough #63
Move Assignment Releases What It Held
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <string>3#include <utility>4using namespace std;56class Buffer {7 int* m_data;8 int m_size;9 string m_name;10public:11 Buffer(const string& name, int size) : m_size(size), m_name(name) {12 m_data = new int[size];13 cout << "alloc " << m_name << endl;14 }15 Buffer& operator=(Buffer&& other) noexcept {16 if (this != &other) {17 delete[] m_data;18 cout << "release " << m_name << endl;19 m_data = other.m_data;20 m_size = other.m_size;21 m_name = other.m_name;22 other.m_data = nullptr;23 other.m_size = 0;24 other.m_name = "";25 }26 return *this;27 }28 ~Buffer() {29 delete[] m_data;30 cout << "free " << (m_name.empty() ? "nothing" : m_name) << endl;31 }32 int size() const { return m_size; }33};3435int main() {36 Buffer a("a", 2);37 Buffer b("b", 5);38 b = std::move(a);39 cout << b.size() << " " << a.size() << endl;40 Buffer& r = b;41 b = std::move(r);42 cout << "end" << endl;43 return 0;44}