c++ - 如何为模板类的 const ref 成员定义 move 赋值运算符

标签 c++ c++11 language-lawyer move-semantics const-reference

我有以下模板类,其中成员是 const ref 类型。对象的复制被禁用,并且只希望有 move cntor 和 move 赋值运算符。

Q1:如何正确实现const ref type的 move 赋值运算符(是否正确,我做的)?

Q2:为什么会这样

MyClass<int> obj2(std::move(obj));   // will work with move ctor
MyClass<int> obj3 = std::move(obj2); // also move ctor called: Why?

发生了什么?

Q3:在 main() 中 move 的实例可以使用 print() 调用。是UB吗?

我正在使用 Visual Studio 2015 (v140)。 这是我的代码:

#include <utility>
#include <iostream>

template<typename Type>
class MyClass
{
    const Type& m_ref;  // const ref type
public:
    explicit MyClass(const Type& arg): m_ref(std::move(arg)){}

    // coping is not allowed
    MyClass(const MyClass&) = delete;
    MyClass& operator=(const MyClass&) = delete;

    // enables move semantics
    MyClass(MyClass &&other) : m_ref(std::move(other.m_ref)) { std::cout << "Move Cotr...\n"; } // works

    // how would I do the move assignment operator, properly: following?
    MyClass& operator=(MyClass &&other)
    {
        // this should have been done in initilizer list(due to const ref member), 
        // but here we cannnot and still it gives no errors, why?

        this->m_ref = std::move(other.m_ref);  
        std::cout << "Move =operator...\n";
        return *this;
    }

    // print the member
    const void print()const noexcept { std::cout << m_ref << std::endl; }
};

//test program
int main() {
    MyClass<int> obj(2);
    MyClass<int> obj2(std::move(obj));   // will work with move ctor
    MyClass<int> obj3 = std::move(obj2); // also move ctor called: Why?

    obj.print();  // why this prints 2? : is it UB?
    obj2.print(); // why this prints 2? : is it UB?
    obj3.print(); // here it makes sence.

    std::cin.get();
}

最佳答案

第一个:

MyClass<int> obj2(std::move(obj));   // will work with move ctor

direct initialization .

第二个:

MyClass<int> obj3 = std::move(obj2); // also move ctor called: Why?

copy initialization .

两者都在构造对象(分别是obj2obj3)并初始化它们。 = 在此上下文中并不表示赋值。

关于c++ - 如何为模板类的 const ref 成员定义 move 赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839782/

相关文章:

c++ - 当在某些非 C++ 程序中使用 C++ 代码时,C++ 运行时调用 terminate() 是否为 "legal"?

c++ - if 语句中有 float 的奇怪错误

c++ - 如何使用 std::chrono 库设置特定时间?

c++ - 字节真的是最小可寻址单位吗?

c++ - Clang 中不明确的运算符重载

c++ - C++ 中 lhs 和 rhs 区别的引用

c++ - 在 iOS 和 Mac OS X 应用程序中使用 C++

c++ - 在基于范围的 for 循环中查找具有连续内存的序列中元素的位置

c++ - shared_ptr 尚未拥有的实例的 shared_from_this() 总是返回 null?

返回 void 的函数 g 可以返回 f() 吗? f 何时返回 void?