考虑以下类:
#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
,对于rvalues只需一次移动,对于lvalues只需一次复制。有没有可能用一个构造函数实现同样的结果?在这种情况下不是大问题,但如果有多个参数呢?我将需要在参数列表中针对每个lvalue和rvalue出现的所有可能性进行组合。
这不仅限于构造函数,也适用于函数参数(例如设置器)。
注意:本问题严格与
class B
有关;class A
仅存在于可视化复制/移动调用的方式。