【发布时间】:2012-05-06 16:28:35
【问题描述】:
考虑这些类:
#include <iostream>
#include <string>
class A
{
std::string test;
public:
A (std::string t) : test(std::move(t)) {}
A (const A & other) { *this = other; }
A (A && other) { *this = std::move(other); }
A & operator = (const A & other)
{
std::cerr<<"copying A"<<std::endl;
test = other.test;
return *this;
}
A & operator = (A && other)
{
std::cerr<<"move A"<<std::endl;
test = other.test;
return *this;
}
};
class B
{
A a;
public:
B (A && a) : a(std::move(a)) {}
B (A const & a) : a(a) {}
};
在创建B 时,我总是为A 提供一个最佳的正向路径,一个用于右值的移动或一个用于左值的副本。
是否可以用一个构造函数实现相同的结果?这种情况下问题不大,但是多参数呢?我需要参数列表中每个可能出现的左值和右值的组合。
这不仅限于构造函数,也适用于函数参数(例如setter)。
注意:这个问题完全是关于class B; class A 的存在只是为了可视化复制/移动调用的执行方式。
【问题讨论】:
-
@JamesCuster:我只是想测试一下各自的构造函数/操作符被调用了多少次。
标签: c++ c++11 parameter-passing rvalue-reference