编辑:已解决,请参见评论。 - 不知道如何在没有答案的情况下标记为已解决。
在观看了 Channel 9 上有关 c++0x 中完美转发 / 移动语义的视频后,我有些倾向于认为这是编写新赋值运算符的好方法。
#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);
}
这应该允许将r-values和const&赋值给它。通过使用适当的构造函数构造一个新对象,然后交换其内容与*this。在我的看来,这似乎是可行的,因为没有多余的数据被复制。而且指针算术是便宜的。
然而,我的编译器不同意。(g++ 4.6) 我得到了以下错误。
copyconsttest.cpp: In function ‘int main()’:
copyconsttest.cpp:40:4: error: ambiguous overload for ‘operator=’ in ‘t = t1’
copyconsttest.cpp:40:4: note: candidates are:
copyconsttest.cpp:18:11: note: my_type& my_type::operator=(my_type)
copyconsttest.cpp:30:11: note: my_type& my_type::operator=(const my_type&) <deleted>
copyconsttest.cpp:31:11: note: my_type& my_type::operator=(my_type&&) <near match>
copyconsttest.cpp:31:11: note: no known conversion for argument 1 from ‘my_type’ to ‘my_type&&’
copyconsttest.cpp:41:16: error: ambiguous overload for ‘operator=’ in ‘t = std::move [with _Tp = my_type&, typename std::remove_reference< <template-parameter-1-1> >::type = my_type]((* & t1))’
copyconsttest.cpp:41:16: note: candidates are:
copyconsttest.cpp:18:11: note: my_type& my_type::operator=(my_type)
copyconsttest.cpp:30:11: note: my_type& my_type::operator=(const my_type&) <deleted>
copyconsttest.cpp:31:11: note: my_type& my_type::operator=(my_type&&) <deleted>
我做错了什么吗?这是不好的实践吗(我认为没有测试自我分配的方法)?还是编译器还没有准备好?
谢谢
swap
еҮҪж•°гҖӮ然еҗҺе®ғеә”иҜҘжҳҜswap(std::move(other));
гҖӮ - Kerrek SB