Редактировать: редактировать см. Комментарии - Не знаем, как отметить как решено без ответа.
После просмотра канала 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-значения, так и Const & S для его назначения. Создавая новый объект с соответствующим конструктором, а затем заменяйте содержимое с помощью этого. Это кажется мне звук, так как данные не копируются больше, чем нужно. И указатель арифметика дешево.
Однако мой компилятор не согласен. (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>
Я делаю что-то не так? Это плохая практика (я не думаю, что есть способ тестирования, не являетесь ли вы самостоятельно)? Компилятор только не готов еще не готов?
Спасибо