8

为什么以下代码在使用 gcc 4.7.2 和 MSVC-11.0 编译时会给出不同的输出?

#include <iostream>

class Base
{
public:
    Base()
    {
        std::cout << "Base::Base() \n";
    }

    ~Base()
    {
        std::cout << "Base::~Base() \n";
    }
};

class Derived : public Base
{
public:
    Derived()
    {
        std::cout << "Derived::Derived() \n";
    }

    ~Derived()
    {
        std::cout << "Derived::~Derived() \n";
    }
};

void foo(Base) {}

int main()
{
    Derived instance;
    foo(instance);
}

GCC 4.7.2

基数::基数()

派生::派生()

基数::~基数()

派生的::~派生的()

基数::~基数()

MSVC-11.0

基数::基数()

派生::派生()

基数::~基数()

基数::~基数()

为什么 MSVC-11.0 不打印第二个Derived::~Derived()

https://ideone.com/NF9FQf

4

1 回答 1

1

我正在使用 MS Visual Studio 11.0.60315.01,cl 版本 17.0.60315.1。

使用它作为main

int _tmain()
{
    Derived instance;
    foo(instance);

    return 0;
}

并在行上放一个断点return 0我得到这个输出:

Base::Base()
Derived::Derived()
Base::~Base()
Base::~Base()

这是问题中报告的那个。

退出main并进入 crt 会产生以下输出:

Base::Base()
Derived::Derived()
Base::~Base()
Base::~Base()
Derived::~Derived()
Base::~Base()

将此添加到Base类中:

Base( const Base& b )
{
    std::cout << "Base::Base( const Base& b ) \n";
}

导致这个输出在return 0;

Base::Base()
Derived::Derived()
Base::Base( const Base& b )
Base::~Base()

并在执行所有析构函数后输出:

Base::Base()
Derived::Derived()
Base::Base( const Base& b )
Base::~Base()
Derived::~Derived()
Base::~Base()

添加虚拟析构函数不会导致任何更改(如预期的那样):

Base::Base()
Derived::Derived()
Base::Base( const Base& b )
Base::~Base()
Derived::~Derived()
Base::~Base()

我的猜测是海报错误地记录了 MSVC 的输出。

编辑:

完整的输出(没有复制构造函数)包含 3 个Base析构函数。添加复制构造函数将其减少到 2 个Base析构函数。

没有复制构造函数的行为等效于以下输出:

void foo(Base) {}

int _tmain()
{
    {
        Derived instance;
        Base b(instance);
        foo(b);
    }

    return 0;
}
于 2013-05-31T16:49:43.813 回答