C++ MOVE

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

int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;

    // uses the push_back(const T&) overload, which means
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";

    // uses the rvalue reference push_back(T&&) overload,
    // which means no strings will copied; instead, the contents
    // of str will be moved into the vector.  This is less
    // expensive, but also means str might now be empty.
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";

    std::cout << "The contents of the vector are \"" << v[0] << "\", \"" << v[1] << "\"\n";
}

### 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、付费专栏及课程。

余额充值