从上一个问题中我知道,在~base()
调用派生类时,它首先构造一个临时基对象,然后operator~()
在临时对象上调用临时基,最后销毁临时对象。
但是当基类没有时operator~
,在派生类中调用base::~base()
仍然可以调用基类的析构函数。
为什么当基类有时会发生错误operator~
?
#include <iostream>
using namespace std;
class base
{
public:
base(){cout << "constructor base \n";}
~base(){cout << "destructor base \n";}
void operator~(){cout << "operator ~ \n";}
};
class derived : public base
{
public:
derived(){cout << "constructor derived \n";}
~derived(){base::~base();cout << "destructor derived \n";}
};
编译器版本信息:
g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
错误:
cmd /c chcp 65001>nul && C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g "D:\Valkyrie-text\simple text\text.cpp" -o "D:\Valkyrie-text\simple text\text.exe"
D:\Valkyrie-text\simple text\text.cpp: In destructor 'derived::~derived()':
D:\Valkyrie-text\simple text\text.cpp:15:28: error: no matching function for call to 'derived::~derived()'
~derived(){base::~base();cout << "destructor derived \n";}
^
D:\Valkyrie-text\simple text\text.cpp:7:5: note: candidate: 'base::~base()'
~base(){cout << "destructor base \n";}
^
D:\Valkyrie-text\simple text\text.cpp:7:5: note: candidate expects 1 argument, 0 provided
正如多人在评论中指出的那样,这段代码是“正确的”,也就是说,编译器不应该抱怨:
由于您的旧 gcc 不接受它,您可以使用不同的语法来执行相同的操作:
但是,语言会自动调用基类析构函数,您不应该干涉这一点。
我出于好玩儿的缘故,做了些小修改,发现这个 bug 在 gcc 10 版本(2020 年)中已经修复了。之所以花了这么长时间才发现这个 bug,可能是因为代码完全没用,而且也没人测试过。