How do I use move semantics in C++11?

Move semantics in C++11 is a feature that allows developers to optimize resource management and improve performance by enabling the transfer of resources (like memory or file descriptors) from one object to another instead of copying them. This is particularly useful for large objects where copying can be expensive.

Move semantics utilize two main components: rvalue references and move constructors/move assignment operators. An rvalue reference allows you to bind a temporary object (an rvalue) for use. This is indicated by the `&&` syntax. The move constructor and move assignment operator allow the transfer of resources from one object to another without expensive deep copies.

Here is a simple example demonstrating move semantics in C++11:

#include #include // for std::move class MyString { private: char* data; public: MyString(const char* str) { data = new char[strlen(str) + 1]; strcpy(data, str); std::cout << "Constructor called!" << std::endl; } // Move constructor MyString(MyString&& other) { data = other.data; // Transfer ownership other.data = nullptr; // Leave the moved-from object in a valid state std::cout << "Move constructor called!" << std::endl; } // Destructor ~MyString() { delete[] data; // Clean up } void print() { if (data) { std::cout << "Data: " << data << std::endl; } else { std::cout << "Data is null." << std::endl; } } }; int main() { MyString str1("Hello, world!"); str1.print(); MyString str2(std::move(str1)); // Move str1 into str2 str2.print(); // str2 owns the data now str1.print(); // str1 is in a valid but empty state return 0; }

move semantics C++11 rvalue references move constructor performance optimization