【发布时间】:2016-07-14 14:11:39
【问题描述】:
有一个带有构造函数的 Complex 类,它为 RVO 打印一条消息。
我已经在 gtest 中测试了 Complex 的 operator+ 方法。
如果发生 RVO,则打印“Complex!!”留言 3 次。
但是有“复杂!!”消息 5 次。
我认为没有发生 RVO。
我用 c++98 和 c++11 编译了这段代码
为什么不发生RVO?
#include <stdio.h>
class Complex {
friend Complex operator+(const Complex&, const Complex&);
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { printf("\nComplex!!\n");}
Complex(const Complex& c) : real(c.real), imag(c.imag) {}
Complex& operator=(const Complex& c) {
real = c.real;
imag = c.imag;
return *this;
}
~Complex() {}
private:
double real;
double imag;
};
Complex operator+(const Complex& lhs, const Complex& rhs)
{
return Complex(lhs.real + rhs.real, lhs.imag + rhs.imag);
}
int main()
{
Complex a(1.0), b(2.0), c;
for (int i = 0; i < 2; i++) {
c = a + b;
}
}
【问题讨论】:
-
有 5 个构造函数调用:一个用于初始化
a、b和c,每个调用一个用于operator+。为什么你认为会有其他数字?你认为哪些不应该发生? -
RVO 省略了对复制构造函数和移动构造函数的调用,而不是其他调用。所以你的代码没有告诉你任何关于 RVO 的信息。
-
Complex c = a + b;可能会发生这种情况。现在你只有一个作业,这是不适用的。 -
发生RVO时,两个“Complex!!”不应打印调用 operator+ 的消息。但它是打印出来的。
-
@GyeongWonDo:那是错误的。您误解了省略的作用。