2

标题可能不是很清楚,我解释一下:我只是想在一个字符串被销毁的时候显示一条消息,所以我这样做了:

std::string::~std::string(void)
{
  std::cout << "Destroyed string" << std::endl;
}

它没有编译,然后我尝试了这个:

namespace std
{
  string::~string(void)
  {
    cout << "Destroyed string" << endl;
  }
}

而且它也没有用,所以有没有办法做我想做的事?谢谢你的帮助。

4

2 回答 2

7

无法向已经定义了析构函数的现有类添加自定义析构函数行为。而且; 您不能(也不应该!)修改std::string使用继承的行为。

如果你想要一个具有自定义行为的析构函数,你必须滚动你自己的类来做到这一点。您也许可以std::string通过创建一个仅将字符串作为其唯一成员的类来“包装” a:

struct StringWrapper
{
    std::string value;

    StringWrapper() {}
    ~StringWrapper()
    {
        // Do something here when StringWrapper is destroyed
    }
};
于 2021-01-08T22:09:21.530 回答
4

我知道这通常是一个不受欢迎的答案,但我真的,真的认为你不想覆盖标准的字符串析构函数。它必须做其他事情,比如释放为字符串字符分配的内存,如果你覆盖它,这将无法完成。

相反,我只使用一个包装类:

class MyString {
private:
    std::string actualString;

public:
    MyString(std::string s) : actualString(s) {}
    ~MyString() {
        //your code here
    }
    
    inline std::string getString() {
        return actualString;
    }
};
于 2021-01-08T22:09:56.543 回答