Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is std::string not trivially destructible?

I’m a c++ noob and I’ve been reading about trivial destructibility.

From this article on trivial destructibility,

Trivially destructible types include scalar types, trivially copy
constructible classes and arrays of such types.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A trivially destructible class is a class (defined with class, struct
or union) that:

  • uses the implicitly defined destructor.
  • the destructor is not virtual.
  • its base class and non-static data members (if any) are themselves also trivially destructible types.

But apparently std::string is not trivially destructible. Why? Which of the above rules does std::string not satisfy?

std::cout << std::boolalpha
              << "std::string is trivially destructible? "
              << std::is_trivially_destructible<std::string>::value << '\n'

The above snippet returns the following output:

std::string is trivially destructible? false

>Solution :

A std::string typically contains a pointer to the actual string data, so it needs an explicit destructor to delete[] that. So, if nothing else, it must either fail this criterion:

uses the implicitly defined destructor

or have a base class that fails it, in which case it fails this criterion:

its base class and non-static data members (if any) are themselves also trivially destructible types.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading