对象是否支持移动构造对std::move(移动语义)的影响

1.std::move 的作用:

std::move 本身只是一个类型转换操作。它将一个左值表达式转换为一个右值引用表达式。 重要的是要理解 std::move 不执行任何实际的移动操作。 它只是使对象能够被移动。

2.移动语义依赖于移动构造函数/移动赋值运算符:

移动语义的真正实现依赖于类是否定义了移动构造函数和移动赋值运算符。 当你将一个对象“移动”时,你通常是希望:

    • 资源(例如动态分配的内存)的所有权从源对象转移到目标对象。
    • 源对象处于一个有效的、但未定义的状态(通常,它的资源指针会被置空)。

3.如果类没有移动构造函数,并且你对该类的对象使用 std::move,那么将会调用拷贝构造函数。 这是因为右值引用可以绑定到 const 左值引用,拷贝构造函数通常接受 const 左值引用作为参数。 在这种情况下,不会发生真正的移动,而是执行拷贝操作。 性能上不如移动构造函数好,但代码仍然是正确的。

 

注意:C++ 的基础类型(例如 intfloatdoublebool 等)天生就支持移动语义,或者更准确地说,它们在赋值或复制时的行为类似于移动操作。 这是因为基础类型的复制成本很低,直接复制内存即可,没有资源所有权转移的问题。

例子:

#include <iostream>  
#include <string>  
#include <utility>  

class MyString {  
public:  
    std::string data;  

    // 构造函数  
    MyString(const std::string& str) : data(str) {  
        std::cout << "Constructor called\n";  
    }  

    // 拷贝构造函数  
    MyString(const MyString& other) : data(other.data) {  
        std::cout << "Copy constructor called\n";  
    }  

    // 移动构造函数  
    MyString(MyString&& other) : data(std::move(other.data)) {  
        std::cout << "Move constructor called\n";  
    }  

    // 赋值运算符  
    MyString& operator=(const MyString& other) {  
        data = other.data;  
        std::cout << "Assignment operator called\n";  
        return *this;  
    }  

    // 移动赋值运算符  
    MyString& operator=(MyString&& other) {  
        data = std::move(other.data);  
        std::cout << "Move assignment operator called\n";  
        return *this;  
    }  
};  

int main() {  
    MyString str1("Hello"); // 构造函数  
    MyString str2 = std::move(str1); // 移动构造函数  

    MyString str3("World"); // 构造函数  
    str3 = std::move(str2); // 移动赋值运算符  

    return 0;  
}

 

posted @ 2025-02-08 11:38  BlackSnow  阅读(63)  评论(0)    收藏  举报