Move Construction in C++

So, in this example program, I demonstrate the move operators. Their purpose is to do a shallow copy of an object: copy all pointers rather than pointer contents. The ephemeral source object is now considered to have an invalid state and is probably going out of scope soon.

In this program, I create an object, A, and it allocates dynamic memory. I then move construct an object, B, which now has all of A’s data, no deep copies involved. The addresses of each variable, demonstrating they were not reallocated, are printed.

class A {
public:
	std::vector<int> v;
	std::string str;
	std::mutex m;

	A() {
		v.resize(100);
		str.resize(100);
	}
	A( A&& a) noexcept {
		v = std::move(a.v);
		str = std::move(a.str);
	}

	void printAddresses() {

		std::cout << std::hex;

		auto print = [&](const auto& c, auto pointer) {
			std::cout << c << ": 0x" << std::size_t(pointer)
				<< std::endl;
		};

		print("v", v.data());
		print("str", str.data());
		print("m", &m);
	}
};

int main() {

	A a;
	std::cout << "before move\n";
	a.printAddresses();

	A b(std::move(a));
	std::cout << "after move\n";
	std::cout << "a:";
	a.printAddresses();
	std::cout << "\nb:";
	b.printAddresses();

	return 0;
}

Leave a comment