2

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.

Fayeure
  • 1,181
  • 9
  • 21
  • 2
    You *might* be able to do something funky with `std::basic_string`'s *allocator*. The behaviour of modifying `std::string` directly is undefined. – Bathsheba Jan 08 '21 at 22:12
  • 1
    This feels like an [X-Y Problem](https://meta.stackexchange.com/q/66377/476201). What are you actually trying to accomplish by doing this? –  Jan 08 '21 at 23:06
  • it's mostly for debug purpose – Fayeure Jan 09 '21 at 15:49
  • @Fayeure most `std` classes don't need debugging. So what exactly are you trying to debug? –  Jan 11 '21 at 21:14
  • @Chipster It was to debug my code, to check if all the strings were deleted – Fayeure Jan 12 '21 at 00:51

2 Answers2

7

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
    }
};
BTownTKD
  • 7,911
  • 2
  • 31
  • 47
  • Okay, I didn't mean to modify the destructor, I just wanted to add operations to the existing destructor. – Fayeure Jan 08 '21 at 22:14
  • 3
    @Fayeure How exactly does adding to the destructor not count as modiftying it? – JaMiT Jan 08 '21 at 22:16
4

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;
    }
};
dranjohn
  • 673
  • 7
  • 22
  • 2
    Wouldn't inheriting from it work better if you just want to inject some destructor behavior? – xaxxon Jan 08 '21 at 22:12
  • 2
    Related: [https://stackoverflow.com/questions/6006860/why-should-one-not-derive-from-c-std-string-class](https://stackoverflow.com/questions/6006860/why-should-one-not-derive-from-c-std-string-class) – drescherjm Jan 08 '21 at 22:17