我有以下模板类,其中成员是 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
第二个:
MyClass<int> obj3 = std::move(obj2); // also move ctor called: Why?
两者都在构造对象(分别是obj2
和obj3
)并初始化它们。 =
在此上下文中并不表示赋值。
关于c++ - 如何为模板类的 const ref 成员定义 move 赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839782/