C++ 在按值返回函数中没有返回时的奇怪行为

C++ 在按值返回函数中没有返回时的奇怪行为,c++,C++,我是新来的! 很明显,当我们调用一个返回对象(不是基本类型)的类的getter函数时,将运行对象类的copy构造函数来创建对象的副本&after';'自毁函数 但是我注意到,当我们在这个被调用的getter函数中没有任何返回时,复制构造函数将不会运行,但析构函数不会运行!!! 为什么析构函数在以前没有构造过对象的情况下运行 现在想象一下,当我们有一个特定类的总对象的int计数器时,它在构造函数&复制构造函数中加1,在类的析构函数中减1,以计算幸存对象的数量。因此,我们可能有一个错误的号码,包括上

我是新来的! 很明显,当我们调用一个返回对象(不是基本类型)的类的getter函数时,将运行对象类的copy构造函数来创建对象的副本&after';'自毁函数

但是我注意到,当我们在这个被调用的getter函数中没有任何返回时,复制构造函数将不会运行,但析构函数不会运行!!! 为什么析构函数在以前没有构造过对象的情况下运行

现在想象一下,当我们有一个特定类的总对象的int计数器时,它在构造函数&复制构造函数中加1,在类的析构函数中减1,以计算幸存对象的数量。因此,我们可能有一个错误的号码,包括上述问题

请看下面的示例:

class Test
{
public:
    Test()
    {
        testCounter++;
    }
    ~Test()
    {
        testCounter--;
    }
    Test(const Test &)
    {
        testCounter++;
    }
    static int getTestCounter()
    {
        return testCounter;
    }

private:
    static int testCounter;

};

class Confirm
{
public:
    Confirm()
    {
        counter++;
    }
    ~Confirm()
    {
        counter--;
    }
    Confirm(const Confirm &)
    {
        counter++;
    }
    Test get()
    {
        return f;
    }
    Test result (Test)
    {
        //we don't have a return value
    }
    static int getCounter()
    {
        return counter;
    }

private:
    static int counter;
    Test f;
};


int main()
{   Confirm a;
    /*building an object of confirm class which have
    an object of Test class in it
    (So counter & testcounter, both are 1)*/

    Test b;
    //(counter is 1 & testcounter is 2)

    b = a.get();
    /*copy constructor & destructor, both will
    be run and the numbers will stayed*/

    a.result(b);
    /*only destructor will be run because
    we have no return value
    (So counter is 1 & testcounter is 1)
    which is a wrong statistics!!!*/

    std::cout<<endl<<Confirm::getCounter()<<endl<<Test::getTestCounter();
    //will cout 1 1 instead of 1 2 (wrong statistic)
    getch();
    return 0;
}
类测试
{
公众:
测试()
{
testCounter++;
}
~Test()
{
测试计数器--;
}
测试(常数测试&)
{
testCounter++;
}
静态int getTestCounter()
{
返回测试计数器;
}
私人:
静态int测试计数器;
};
班级确认
{
公众:
确认
{
计数器++;
}
~Confirm()
{
计数器--;
}
确认(const确认&)
{
计数器++;
}
测试get()
{
返回f;
}
测试结果(测试)
{
//我们没有返回值
}
静态int getCounter()
{
返回计数器;
}
私人:
静态整数计数器;
试验f;
};
int main()
{确认一份文件;
/*构建具有
其中的测试类的对象
(所以计数器和测试计数器都是1)*/
试验b;
//(计数器为1,测试计数器为2)
b=a.get();
/*复制构造函数和析构函数,两者都将
运行时,数字将保持不变*/
a、 结果(b);
/*只有析构函数将运行,因为
我们没有返回值
(因此计数器为1,测试计数器为1)
这是一个错误的统计数据*/

std::cout如果你的函数有一个非
void返回类型,并且你没有实际返回一个值(或者抛出一个异常),那么任何事情都可能发生,包括将万有引力常数加倍或者开始一场深思熟虑的国际象棋

就这么简单

您的编译器可能在这里做两件事:

  • 为了快速高效地工作,假设你没有这样做
  • 当你这么做的时候警告你

  • .

    这是未定义的行为,请参阅当您说要返回某个内容时不返回该内容是未定义的行为。仅此而已。如果您搜索,应该会有大约20次重复