例如,此代码:
struct President
{
std::string name;
std::string country;
int year;
President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "--constructedn";
}
/*
President(const President& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
*/
President(const President& other)
: name(other.name), country(other.country), year(other.year)
{
std::cout << "--copy constructedn";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "--movedn";
}
~President()
{
cout << "n"<< &name << " " << country << endl;
std::cout << "--destructn";
}
President& operator=(const President& other);
};
无论是移动构造函数还是复制构造函数,它们都会导致三个数据成员的值存储在新内存中,而旧内存将被释放。
我的意思是对的?
我的意思是对的?
对不起,没有。您的move构造函数将按照您的描述工作,因为它将从other
"窃取"name
和country
成员变量的内容,但copy构造函数不会。std::move
对const
对象不执行任何操作,您应该将其从复制构造函数中删除。毕竟,关键词是copy
,对吧?
值得注意的是,您根本不需要在这里编写自己的副本或移动构造函数("规则为零"(。编译器合成的默认构造函数将正常工作。哦,像int
这样的基元类型上的std::move
也不起任何作用——无论是否包含变量,都只会复制它。