考虑这些类:C++ 11的最佳参数传递
#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
,为右值的左值一招或一个副本。
是否有可能实现与一个构造函数相同的结果?在这种情况下这不是一个大问题,但是多个参数呢?我需要在参数列表中组合每个可能出现的左值和右值。
这不限于构造函数,也适用于函数参数(例如setters)。
注意:这个问题是严格约class B
; class A
仅用于可视化复制/移动调用的执行方式。
你应该阅读这些:http://stackoverflow.com/questions/8472208/under-what-conditions-should-i-be-thinking-about-implementing-a-move-constructor和http:// stackoverflow。 com/questions/4782757/rule-of-three-become-rule-of-five-with-c11 –
@JamesCuster:我只是想测试各个构造函数/操作符被调用的次数。 – fscan