編集:解決済みコメントを参照-回答なしで解決済みとしてマークする方法がわからない。
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);
}
これにより、r値と定数の両方を割り当てることができます。適切なコンストラクターを使用して新しいオブジェクトを作成し、その内容を*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>
私は何か間違ったことをしていますか?これは悪い習慣ですか(自分で割り当てているかどうかをテストする方法はないと思います)?コンパイラはまだ準備ができていませんか?
ありがとう