c++ - 为什么 std::string 不可轻易破坏?

标签 c++

我是一个 C++ 菜鸟,我一直在阅读关于微不足道的可破坏性的文章。

来自 this关于微不足道的可破坏性的文章,

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.

但显然 std::string 不可轻易破坏。为什么? std::string 不满足以上哪条规则?

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

上面的代码片段返回以下输出:

std::string 是可以轻易破坏的吗?假的

最佳答案

std::string 通常包含指向动态分配的字符数据的指针,因此它需要一个显式析构函数来释放该内存。因此,如果不出意外,它必须满足以下条件:

uses the implicitly defined destructor

或者有一个基类不符合它,在这种情况下它不符合这个标准:

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

关于c++ - 为什么 std::string 不可轻易破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71985523/

相关文章:

C++ Socket 连接自动建立?

c++ - 特化返回 void 且没有参数的成员函数

c++ omp原子捕获-语法?

c++ - 具有静态成员的静态结构

c++ - 无法链接 BEGIN_MESSAGE_MAP 中的 afx_msg

c++ - 用 ASCII 空格初始化模板<size_t N> std::array<char, N>?

c++ - _ITERATOR DEBUG LEVEL 困惑?

c++ - Xcode C++ vector : Implicit instantiation of undefined template

c++ - 有9次破坏怎么解释?

c++ - 定义 HAS_XXX/NO_XXX 支持/不支持一个特性