c++中move constructor and assignment

本文介绍了一个C++示例程序,展示了如何使用移动构造函数和移动赋值操作符来高效地处理字符串对象的创建与复制过程。通过具体的代码实现,文章解释了资源管理类的设计方法,并演示了如何通过移动语义提高程序性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
using namespace std;

class Example6 {
    string* ptr;
public:
    Example6 (const string& str) : ptr(new string(str)) {}
    ~Example6 ()  {delete ptr;}
    //move constructor
    Example6 (Example6&& x) : ptr(x.ptr) {x.ptr = nullptr;}
    //move assignment
    Example6& operator= (Example6&& x) {
        delete ptr;
        ptr = x.ptr;
        x.ptr = nullptr;
        return *this;
    }
    //access content:
    const string& content () const {return *ptr;}
    //addtion:
    Example6 operator+(const Example6& rhs) {
        return Example6(content()+rhs.content() );
    }
};

int main(int argc, char const *argv[])
{
    Example6 foo ("Exam");
    Example6 bar = Example6("ple");
    foo = foo + bar;
    cout << "foo's content: " << foo.content() << "\n";
    return 0;
}
### C++ Move Semantics Tutorial and Examples In modern C++, move semantics provide a mechanism to transfer resources between objects without copying them. This feature significantly improves performance by avoiding unnecessary deep copies of data structures such as strings, vectors, or custom containers. #### Introduction to Rvalue References Move operations are implemented using rvalue references (`T&&`). An rvalue reference binds only to temporary (rvalues), allowing functions to distinguish whether an object is being used as a source that can be moved from: ```cpp class MyClass { public: // Copy constructor MyClass(const MyClass& other); // Move constructor MyClass(MyClass&& temp) noexcept; }; ``` The `noexcept` specifier indicates the function will not throw exceptions, which helps optimize standard library algorithms assuming safety during moves[^1]. #### Implementing Move Constructor and Assignment Operator To enable moving for user-defined types, one must define both a move constructor and a move assignment operator. These special member functions take advantage of resource transfers efficiently: ```cpp #include <utility> // For std::swap MyClass::MyClass(MyClass&& rhs) noexcept : ptr(rhs.ptr) { rhs.ptr = nullptr; // Transfer ownership safely } MyClass& MyClass::operator=(MyClass&& rhs) noexcept { if(this != &rhs){ delete ptr; // Clean up existing resource first ptr = rhs.ptr; // Steal pointer value rhs.ptr = nullptr; // Alternatively swap could also work here. // std::swap(ptr, rhs.ptr); } return *this; } ``` By setting the original owner's internal state to null after transferring its managed resource, subsequent destruction remains safe while preventing double-free errors[^2]. #### Usage Example with Standard Library Containers Standard libraries like `<vector>` already support efficient element relocation through their own implementations of move constructors/operators. When inserting elements into dynamic arrays or performing reallocations internally, they preferentially apply move rather than copy whenever possible: ```cpp std::vector<std::unique_ptr<int>> vec; vec.push_back(std::make_unique<int>(42)); // Emplace back directly constructs in place auto anotherVec = std::move(vec); // Transfers entire container contents at once // After this point 'vec' becomes empty but valid ``` This example demonstrates how unique pointers benefit greatly from move semantics since direct assignments would otherwise fail due to non-copyable nature constraints imposed upon smart pointers[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值