File size: 1,967 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cpp11-002", "name": "C++11 move semantics deep dive"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "Explain C++11 move semantics in depth"}}
{"type": "message", "message": {"role": "assistant", "content": "**C++11 Move Semantics Deep Dive:**\n\n**Rvalue References:**\n```cpp\nvoid process(std::string&& s);  // rvalue reference\nstd::string name = \"hello\";\nprocess(std::move(name));  // name is now moved-from\n// name is in valid but unspecified state\n```\n\n**Move Constructor:**\n```cpp\nclass Buffer {\n    size_t size_;\n    char* data_;\npublic:\n    Buffer(Buffer&& other) noexcept\n        : size_(other.size_), data_(other.data_) {\n        other.size_ = 0;\n        other.data_ = nullptr;\n    }\n    ~Buffer() { delete[] data_; }\n};\n```\n\n**Move Assignment:**\n```cpp\nBuffer& operator=(Buffer&& other) noexcept {\n    if (this != &other) {\n        delete[] data_;\n        size_ = other.size_;\n        data_ = other.data_;\n        other.size_ = 0;\n        other.data_ = nullptr;\n    }\n    return *this;\n}\n```\n\n**Rule of Five:**\nIf you define any of these, define all five:\n1. Destructor\n2. Copy constructor\n3. Copy assignment\n4. Move constructor\n5. Move assignment\n\n**Perfect Forwarding:**\n```cpp\ntemplate<typename T>\nvoid wrapper(T&& arg) {\n    target(std::forward<T>(arg));\n}\n```\n\n**std::move vs std::forward:**\n- std::move: unconditional cast to rvalue\n- std::forward: conditional cast (preserves value category)"}}