gpt4 book ai didi

c++ - 当作为参数传递的对象超出范围时,析构函数会调用自身吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:36:51 25 4
gpt4 key购买 nike

我正在使用一个静态变量来跟踪一个对象的实例数。我使用以下代码得到了一些不可预知的行为:

#include <iostream>
using namespace std;

class comp{
private:
int a;
int b;

public:
friend comp &operator+(comp, comp);
static int c;
comp(int, int);
comp();
~comp();
int getA();
int getB();
void print() const;
};

int comp::c = 0;

comp::~comp() {

c--;
cout << "destroying comp of " << a << ", " << b << ", count after decrement is " << c << endl;
}


comp &operator+(comp A, comp B){
comp C = comp(A.a + B.a, A.b + B.b);
cout << "in +, count is " << comp::c << endl;
return C;
}

comp::comp(int A, int B){
a = A;
b = B;
c++;
}

comp::comp(){
a = 0; b = 0; c++;
}

int comp::getA(){
return a;
}

int comp::getB(){
return b;
}

void comp::print() const{
cout << a << ", " << b << endl;
}

int main()
{
cout << comp::c << endl;
comp A = comp(3,4);
cout << comp::c << endl;
comp B = comp(4,5);
cout << comp::c << endl;
A + B;
A.print();
B.print();
cout << "About to exit main, c is: " << comp::c << endl;
return 0;
}

输出是这样的:

0
1
2
in +, count is 3
destroying comp of 7, 9, count after decrement is 2
destroying comp of 3, 4, count after decrement is 1
destroying comp of 4, 5, count after decrement is 0
3, 4
4, 5
About to exit main, c is: 0
destroying comp of 4, 5, count after decrement is -1
destroying comp of 3, 4, count after decrement is -2

此行为是由线路引起的

 A + B;

我对正在发生的事情的最佳猜测是,当对象作为参数传递给函数时,构造函数没有被调用(因此 c 没有递增),但是当函数超出范围时,析构函数被调用。这导致计数的净损失。

但是,重载的 operator+ 通过引用传递变量。这不会阻止参数超出范围和调用析构函数吗?

无论是否将重载的 + 运算符声明为:

,输出都是相同的
friend comp &operator+(comp, comp);

friend comp operator+(comp, comp);

这让我对为什么以及如何调用析构函数感到困惑。

最后一个问题:使用重载运算符时,按引用传递而不是按值传递是好的做法吗?如果是这样,为什么?

谢谢!

编辑:看起来好像我有点混淆了语法。我以为

friend comp &operator+(comp, comp);

通过引用而不是

传递参数
friend comp operator+(comp&, comp&);

请原谅我的问题,有人能解释一下函数名前的“&”运算符是做什么的吗?如果我理解正确的话,“&”是引用运算符,并给出给定变量的地址。但是,如果想要返回一个引用,“*”运算符将是合适的。例如:

int *a()

上面的函数签名返回一个指向 int 的内存地址。

int &a()

函数签名会返回什么?

最佳答案

您没有考虑默认创建的对象,编译器生成的复制构造函数。定义一个,计算在那里创建的对象,数学就会计算出来。

关于c++ - 当作为参数传递的对象超出范围时,析构函数会调用自身吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20828946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com