因此,在观看了关于右值引用的精彩演讲之后,我认为每个类都会受益于这样的"移动构造函数",template<class T> MyClass(T&& other) 编辑,当然还有"移动赋值运算符",template<class T> MyClass& operator=(T&& other)正如Philipp在他的回答中指出的,如果它已经动态分配成员,或通常存储指针.就像你应该有一个copy-ctor,赋值运算符和析构函数,如果之前提到的点适用.思考?
编辑:解决看到评论 - 不知道如何标记解决与答案.
在c ++ 0x中观看有关完美转发/移动语义的第9频道视频之后,我认为这是编写新分配运算符的好方法.
#include <string>
#include <vector>
#include <iostream>
struct my_type
{
my_type(std::string name_)
: name(name_)
{}
my_type(const my_type&)=default;
my_type(my_type&& other)
{
this->swap(other);
}
my_type &operator=(my_type other)
{
swap(other);
return *this;
}
void swap(my_type &other)
{
name.swap(other.name);
}
private:
std::string name;
void operator=(const my_type&)=delete;
void operator=(my_type&&)=delete;
};
int main()
{
my_type t("hello world");
my_type t1("foo bar");
t=t1;
t=std::move(t1);
}
Run Code Online (Sandbox Code Playgroud)
这应该允许将r值和const分配给它.通过使用适当的构造函数构造一个新对象,然后使用*this交换内容.这对我来说听起来很合理,因为没有数据被复制超过它需要的数量.指针算术很便宜.
但是我的编译器不同意.(g ++ 4.6)我得到了这些错误.
copyconsttest.cpp: In function ‘int main()’:
copyconsttest.cpp:40:4: error: ambiguous overload for ‘operator=’ in ‘t = …Run Code Online (Sandbox Code Playgroud)