我是一个 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/