我有以下模板类,其中成员是const ref
类型。对象的复制被禁用,只需要移动 cntor 和移动赋值运算符。
Q1:如何正确实现移动赋值运算符const ref type
(是否正确,我所做的)?
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()
移动的实例中可以调用 using 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();
}