C++11 C++;11-在构造函数中移动基本数据类型?

C++11 C++;11-在构造函数中移动基本数据类型?,c++11,move-semantics,C++11,Move Semantics,我正在研究C++11中的移动语义,我很好奇如何在构造函数中移动基本类型,如布尔、整数浮点等。还有复合类型,如std::string 以下面的类为例: class Test { public: // Default. Test() : m_Name("default"), m_Tested(true), m_Times(1), m_Grade('B') { // Starting up... } Test(const Test

我正在研究C++11中的移动语义,我很好奇如何在构造函数中移动基本类型,如布尔、整数浮点等。还有复合类型,如std::string

以下面的类为例:

class Test
{
public:
    // Default.
    Test()
        : m_Name("default"), m_Tested(true), m_Times(1), m_Grade('B')
    {
        // Starting up...
    }
    Test(const Test& other)
        : m_Name(other.m_Name), m_Times(other.m_Times)
        , m_Grade(other.m_Grade), m_Tested(other.m_Tested)
    {
        // Duplicating...
    }
    Test(Test&& other)
        : m_Name(std::move(other.m_Name)) // Is this correct?
    {
        // Moving...
        m_Tested = other.m_Tested; // I want to move not copy.
        m_Times = other.m_Times; // I want to move not copy.
        m_Grade = other.m_Grade; // I want to move not copy.
    }

    ~Test()
    {
        // Shutting down....
    }

private:
    std::string     m_Name;
    bool            m_Tested;
    int             m_Times;
    char            m_Grade;
};

如何移动(而不是复制)m_测试、m_次数、m_等级。m_的名字移动正确吗?感谢您的时间。

从prvalue或xvalue原语初始化和赋值与从左值原语初始化或赋值的效果完全相同;将复制该值,且源对象不受影响

换句话说,您可以使用
std::move
,但这没有任何区别


如果您想更改源对象的值(例如更改为
0
),您必须自己更改。

看起来正确。除了像bool、int、char这样的简单数据类型之外,其他数据类型都只被复制。“移动”字符串的意义在于,它有一个缓冲区,通常在构造新对象时必须复制该缓冲区,但在使用移动旧缓冲区时(复制指针而不是缓冲区的内容)

Test(Test&& other)
    : m_Name(std::move(other.m_Name)), m_Times(other.m_Times)
    , m_Grade(other.m_Grade), m_Tested(other.m_Tested)
{}