gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:02:05 24 4
gpt4 key购买 nike

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

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

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

A trivially destructible class is a class (defined with class, structor 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com