tinycodinglm / cpp /cpp11-002.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
1.97 kB
opencode trace
System 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 c...

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.

User

Explain C++11 move semantics in depth

Assistant

C++11 Move Semantics Deep Dive:

Rvalue References:

cpp
void process(std::string&& s);  // rvalue reference
std::string name = "hello";
process(std::move(name));  // name is now moved-from
// name is in valid but unspecified state

Move Constructor:

cpp
class Buffer {
    size_t size_;
    char* data_;
public:
    Buffer(Buffer&& other) noexcept
        : size_(other.size_), data_(other.data_) {
        other.size_ = 0;
        other.data_ = nullptr;
    }
    ~Buffer() { delete[] data_; }
};

Move Assignment:

cpp
Buffer& operator=(Buffer&& other) noexcept {
    if (this != &other) {
        delete[] data_;
        size_ = other.size_;
        data_ = other.data_;
        other.size_ = 0;
        other.data_ = nullptr;
    }
    return *this;
}

Rule of Five:
If you define any of these, define all five:

  1. Destructor
  2. Copy constructor
  3. Copy assignment
  4. Move constructor
  5. Move assignment

Perfect Forwarding:

cpp
template<typename T>
void wrapper(T&& arg) {
    target(std::forward<T>(arg));
}

std::move vs std::forward:

  • std::move: unconditional cast to rvalue
  • std::forward: conditional cast (preserves value category)