How do we catch a std class at destruction?

Viewed 96

The title may not be very clear, let me explain: I just want to display a message when a string is destroyed, so I did that:

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

It didn't compile, then I tried this:

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

And it also didn't work, so is there a way to do what I want to do? Thanks for any help.

2 Answers

It's not possible to add custom destructor behavior to an existing class which already has a destructor defined. Moreover; you cannot (and should not!) modify the behavior of std::string using inheritance.

If you want a destructor with custom behavior, you'll have to roll your own class to do it. You could perhaps 'wrap' a std::string by creating a class which simply has a string as its only member:

struct StringWrapper
{
    std::string value;

    StringWrapper() {}
    ~StringWrapper()
    {
        // Do something here when StringWrapper is destroyed
    }
};

I know this is often an unliked answer, but I really, really think you don't want to overwrite the standard string destructor. It has to do other things, like free the memory allocated for the characters of the string, which won't get done if you overwrite it.

Instead, I'd just use a wrapper class:

class MyString {
private:
    std::string actualString;

public:
    MyString(std::string s) : actualString(s) {}
    ~MyString() {
        //your code here
    }
    
    inline std::string getString() {
        return actualString;
    }
};
Related