可能重复:
为什么析构函数只被调用一次?
鉴于下面的代码,我无法理解gcc中的输出.我希望创建和销毁两个对象,但只能看到对构造函数和析构函数的一次调用.这里发生了什么事?
#include <string>
#include <iostream>
struct Huge{
Huge() { std::cout << "Constructor" << std::endl; }
Huge(Huge const &r) { std::cout << "Copy Constructor" << std::endl; }
~Huge() { std::cout << "Destructor" << std::endl; }
};
Huge g() {
std::cout << "Entering g" << std::endl;
Huge temp;
std::cout << "Exiting g" << std::endl;
return temp;
}
int main(){
Huge h2(g());
std::cout << "Before leaving main" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
g ++(4.4)中此代码的输出是
输入g
构造函数
退出g
在离开主要之前
析构函数
那么为什么不能在“ 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+=" …Run Code Online (Sandbox Code Playgroud)