【发布时间】:2015-03-03 01:45:51
【问题描述】:
为了实现* 运算符的完美转发,我构建了以下示例。
#include <string>
#include <iostream>
class A {
public:
std::string name;
A(const A& _other) : name(_other.name) {
std::cout << "Copy-Construct with name: " << name << std::endl;
}
A(A&& _other) : name(std::move(_other.name)) {
std::cout << "Move-Construct with name: " << name << std::endl;
}
A(std::string _name): name(_name) { }
};
A operator*(const A& _lhs, const A& _rhs) {
std::cout << "Start Operator Copy with: " << _lhs.name << " " << _rhs.name << std::endl;
A bla(_lhs.name+" "+_rhs.name);
return bla;
}
A&& operator*(A&& _lhs, const A& _rhs) {
std::cout << "Start Operator Move with: " << _lhs.name << " " << _rhs.name << std::endl;
_lhs.name += " "+_rhs.name;
return std::move(_lhs);
}
int main() {
A a("a");
A b("b");
A c("c");
A d("d");
A x = a*b*A("t1")*c*A("t2")*A("t3")*d;
std::cout << "Final result is: " << x.name << std::endl;
}
结果如我所愿,特别是只调用了一个移动构造函数,没有调用复制构造函数。
Start Operator Copy with: a b
Start Operator Move with: a b t1
Start Operator Move with: a b t1 c
Start Operator Move with: a b t1 c t2
Start Operator Move with: a b t1 c t2 t3
Start Operator Move with: a b t1 c t2 t3 d
Move-Construct with name: a b t1 c t2 t3 d
Final result is: a b t1 c t2 t3 d
现在我的问题是:这是合法的C++11 代码吗?特别是,我可以依赖第一个临时对象(由 a 和 b 构造)在分号处而不是在那之前离开其范围的事实吗?并且将作为移动引用获得的对象返回为移动引用的构造是否合法?
【问题讨论】:
-
你指的是哪个临时对象?
-
第一次重载会泄漏内存——从任何意义上来说,这绝对不是“完美”的。两个重载都应该按值返回。
-
@JonathanWakely:抱歉,这是另一个测试用例。我纠正了它。输出是正确的。