我们如何在销毁时捕获std类?
标题可能不是很清楚,我解释一下:我只是想在一个字符串被销毁时显示一条消息,所以我这样做了:
std::string::~std::string(void)
{
std::cout << "Destroyed string" << std::endl;
}
它没有编译,然后我尝试了这个:
namespace std
{
string::~string(void)
{
cout << "Destroyed string" << endl;
}
}
而且它也不起作用,所以有没有办法做我想做的事?谢谢你的帮助。
回答
无法向已定义析构函数的现有类添加自定义析构函数行为。而且; 您不能(也不应该!)修改std::string使用继承的行为。
如果你想要一个具有自定义行为的析构函数,你必须滚动你自己的类来做到这一点。您也许可以std::string通过创建一个仅将字符串作为其唯一成员的类来“包装” a :
struct StringWrapper
{
std::string value;
StringWrapper() {}
~StringWrapper()
{
// Do something here when StringWrapper is destroyed
}
};
- @Fayeure How exactly does adding to the destructor not count as modiftying it?