Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::string not trivially destructible?

Tags:

c++

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.

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

like image 730
Venkata Narayana Avatar asked Sep 17 '25 15:09

Venkata Narayana


1 Answers

A std::string typically contains a pointer to dynamically allocated character data, so it needs an explicit destructor to deallocate that memory. 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.

like image 128
ruakh Avatar answered Sep 19 '25 04:09

ruakh