当我们在返回值函数内没有返回时的奇怪行为

时间:2017-04-25 01:24:22

标签: c++

我是新来的人! 很明显,当我们调用返回对象(非基本类型)的类的getter函数时,将运行对象类的复制构造函数来制作对象&的副本。之后';'析构函数要破坏。

但我注意到,当我们在这个被称为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;
}

顺便说一句,我可以通过其他方式解决错误的数字问题购买我只是想知道这种奇怪行为的工程分析&amp;如何解决该算法中的错误数问题。

1 个答案:

答案 0 :(得分:3)

如果你的函数有一个非void返回类型,并且你实际上没有返回一个值(或抛出异常),那么your program has undefined behaviour就会发生任何事情,包括加倍通用引力常数或用Deep Thought开始下棋。

就这么简单!

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

  1. 假设为了快速有效地工作,你没有这样做;
  2. 当你做的时候警告你。
  3. It physically can't error out in every such case, so the C++ language doesn't require it to