这些情况有什么区别?我怎么知道什么是临时对象?
What is the difference between these cases? And how can I know what is a temporary object?
给定以下错误:
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+b1
是B
类型的对象,那么问题出在哪里呢?怎么说是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;
}
其中+=
实现为成员函数,然后编写一个稍微不对称的friend
operator+
,该根据+=
实现。
+
中的不对称使+
表达式的长链稍微提高了效率,尤其是在实现移动成本低的对象时。
1当然,在某些情况下,这不是最好的。 就像有时真实的表达式模板一样。 但是你应该从这个开始,只有当你证明你需要它时,它才会变得更加复杂。
相关文章:
- 我怎么知道数组包含多少个元素C++?
- 这是系统资源吗?(或者我怎么知道我是否需要删除指针) - 在 C++ 中使用 C
- 这些情况有什么区别?我怎么知道什么是临时对象?
- 我怎么知道我最后的指示
- 我怎么知道从哪里得到我丢失的 h 文件?
- 我怎么知道C++编译器是否制作线程安全的静态对象代码
- 我怎么知道USB设备是否已经在使用
- 我怎么知道哪种上下文处于活动状态
- 我怎么知道“ rehash”是否在插入unordered_map之后发生
- 我怎么知道谁拥有某个指针
- 我怎么知道使用caffe framwork和c ++程序的层中是否存在偏差
- 我怎么知道基类对象的指针数组中元素的类型,它将为派生类分配内存
- 我怎么知道,如果我在 STL 列表中找到了我搜索的号码
- 我怎么知道内存中的变量是否是指针
- 我怎么知道我是否需要在C 中删除某些内容
- 我怎么知道我的服务器是否在一段时间内没有连接
- 扫雷,我怎么知道有多少个 0 彼此相邻?
- 我怎么知道std :: vector的分配记忆大小
- 我怎么知道要发送什么到串口
- 我怎么知道是什么使不完整类型不完整的错误:对指向不完整类型的指针进行算术运算