这些情况有什么区别?我怎么知道什么是临时对象?

What is the difference between these cases? And how can I know what is a temporary object?

本文关键字:什么 我怎么知道 临时对象 区别 情况      更新时间:2023-10-16

给定以下错误:

class B {
private:
int n;
public:
B(int x) :
n(x) {
}
B operator+(B& b) {
return B(n + b.n);
}
friend ostream& operator<<(ostream &out, const B& b) {
out << "B: " << b.n;
return out;
}
bool operator<(const B& rhs) const {
return n < rhs.n;
}
};
int main() {
B b1(2);
B b2(3);
B res121 = b1 + (b2 + b1); // ----error
B res21 = b2 + b1;
B res1_21 = b1 + res21; // ---- No error
cout << res1_21;
return 0;
}

为什么我在尝试定义res121时遇到错误,但在尝试定义res1_21时没有收到错误?
毕竟,b2+b1B类型的对象,那么问题出在哪里呢?怎么说是a temporary object,我怎么知道什么是temporary object,什么不是。

C++术语中的临时对象是没有名称或标识的对象,通常作为函数的返回值出现。 它们的工作方式在 c++11 和 c++17 之间完全变化。

它们的存在在当前完整表达式(通常是;(的末尾结束,并且它们不能绑定到非const左值引用,因此B&不能绑定到临时引用。

这:

B operator+(B& b) {
return B(n + b.n);
}

是一个可怜的operator+. 编写operator+的最佳1种方法是:

B& operator+=(B const& b)& {
n += b.n;
return *this;
}
friend B operator+(B lhs, B const& rhs) {
lhs += rhs;
return lhs;
}

其中+=实现为成员函数,然后编写一个稍微不对称的friendoperator+,该根据+=实现。

+中的不对称使+表达式的长链稍微提高了效率,尤其是在实现移动成本低的对象时。


1当然,在某些情况下,这不是最好的。 就像有时真实的表达式模板一样。 但是你应该从这个开始,只有当你证明你需要它时,它才会变得更加复杂。