那么为什么在“const Integer operator+(const Integer &rv)”函数中没有调用 Copy 构造函数。是因为RVO吗? 如果是,我需要做什么来防止它发生?
#include <iostream>
using namespace std;
class Integer {
int i;
public:
Integer(int ii = 0) : i(ii) {
cout << "Integer()" << endl;
}
Integer(const Integer &I) {
cout << "Integer(const Integer &)" << endl;
}
~Integer() {
cout << "~Integer()" << endl;
}
const Integer operator+(const Integer &rv) const {
cout << "operator+" << endl;
Integer I(i + rv.i);
I.print();
return I;
}
Integer &operator+=(const Integer &rv) {
cout << "operator+=" << endl;
i + rv.i;
return *this;
}
void print() {
cout << "i: " << i << endl;
}
};
int main() {
cout << "built-in tpes:" << endl;
int i = 1, j = 2, k = 3;
k += i + j;
cout << "user-defined types:" << endl;
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
}
如果我注释掉复制构造函数,我确实会收到错误消息。我期待在 operator+ 返回时调用复制构造函数。以下是程序的输出
built-in tpes:
user-defined types:
Integer()
Integer()
Integer()
operator+
Integer()
i: 3 // EXPECTING Copy Constructor to be called after this
operator+=
~Integer()
~Integer()
~Integer()
~Integer()
最佳答案
Is it because of RVO. If Yes what do I need to do to prevent it?
是的。但由于 Return Value Optimization 而没有被调用由编译器。
如果您使用的是 GCC,请使用 -fno-elide-constructors
选项来避免它。
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
关于c++ - 为什么在此代码中未调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779827/