CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #62

What the Source Owns After a Move

mediumPointers

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <utility>
3using namespace std;
4 
5class Buffer {
6 int* m_data;
7 int m_size;
8public:
9 Buffer(int size) : m_size(size) {
10 m_data = new int[size];
11 for (int i = 0; i < size; i++) {
12 m_data[i] = i * 10;
13 }
14 }
15 Buffer(Buffer&& other) noexcept {
16 m_data = other.m_data;
17 m_size = other.m_size;
18 other.m_data = nullptr;
19 other.m_size = 0;
20 }
21 ~Buffer() { delete[] m_data; }
22 int size() const { return m_size; }
23 bool empty() const { return m_data == nullptr; }
24 int at(int i) const { return m_data[i]; }
25};
26 
27int main() {
28 Buffer a(3);
29 cout << a.size() << " " << a.empty() << endl;
30 Buffer b(std::move(a));
31 cout << b.size() << " " << b.at(2) << endl;
32 cout << a.size() << " " << a.empty() << endl;
33 return 0;
34}

🎯 Your Answer