c++ - 在具有 'has-a' 关系的 C++ 类中两次调用析构函数的问题

标签 c++ destructor

我有一个类A,其中包含另一个类B的对象。这是一个私有(private)对象。但是,当我尝试使用 A 的对象访问 B 的成员变量时,不知何故调用了 B 的析构函数。 无法理解为什么 B 的析构函数在这里被调用?

以下代码的输出是:

In B ctor
In A ctor
10
In B dtor     <------ Why this ?
In A dtor
In B dtor

代码示例:

#include "stdafx.h"
#include <iostream>
using namespace std;

    //Implementaion of B class
    class B
    {
    public:
        int bVal1;
        B::B(void)
        {
            cout << "In B ctor" << endl;
            bVal1 = 10;
        }
        B::~B(void)
        {
            cout << "In B dtor" << endl;
        }
    };

    //Implementaion of A class having private B's object ( composition )
    class A
    {
    private:
        B b;
    public:
        A::A(void)
        {
            cout << "In A ctor" << endl;
        }
        A::~A(void)
        {
            cout << "In A dtor" << endl;
        }
        B A::func2(void)
        {
            return b;

        }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        A a;                                //ctor calling order : B followed by A
        cout << a.func2().bVal1 << endl;    //Why ADDITIONAL B's destructor is getting called here ???
        return 0;                           //dtor calling order : A followed by B
    }

对于这么长的代码,我深表歉意。

最佳答案

你的功能

B A::func2(void)
{
    return b;

}

返回 B 类型对象的拷贝。所以你在 main() 函数中有一个临时的本地版本。所以 A::b 对象和临时 B 对象都被销毁了,因此你有 2 次调用 B::~B() .

您的 main() 函数等同于此:

int _tmain(int argc, _TCHAR* argv[])
{
    A a;                                //ctor calling order : B followed by A
    B b = a.func2();
    cout << b.bVal1 << endl;    //Why ADDITIONAL B's destructor is getting called here ???
    return 0;                           //dtor calling order : b, followed by A::b followed by followed by a
}

试试这样写:

const B& A::func2(void)
{
    return b;
}

这只会给您调用 1 次 B::~B()

关于c++ - 在具有 'has-a' 关系的 C++ 类中两次调用析构函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641799/

相关文章:

C++ 对象 : When should I use pointer or reference

c++ - 当字符串包含 %2C 时,c++ 中的 std::string 不完整

c++ - 为什么我以前调用析构函数的方式会导致内存问题?

c++ - 如何保证单例不被过早销毁?

c++ - C++中的字符串类赋值运算符重载

C++ 指向函数的指针作为参数。数据类型不兼容

c++ - QImage 使用 OpenCV 损坏

C++虚拟析构函数导致调用基方法

Java,当对象的作用域结束时执行一个方法

c++ - 谁能告诉我我的代码有什么问题?