gpt4 book ai didi

c++ - 为什么 std::string 是标准布局类型?

转载 作者:太空狗 更新时间:2023-10-29 19:47:46 25 4
gpt4 key购买 nike

以此处为例:trivial vs. standard layout vs. POD

以下代码通过:

struct T {
public:
int i;
private:
int j;
};

static_assert(! std::is_standard_layout<T>::value, "");

但以下不是:

static_assert(! std::is_standard_layout<std::string>::value, "");

所以如果一个类型不是标准布局,那么 std::string 怎么可能是一个呢?

最佳答案

让我们看看标准布局的实际规则:

[C++14: 9/7]: A standard-layout class is a class that:

  • has no non-static data members of type non-standard-layout class (or array of such types) or reference,
  • has no virtual functions (10.3) and no virtual base classes (10.1),
  • has the same access control (Clause 11) for all non-static data members,
  • has no non-standard-layout base classes,
  • either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
  • has no base classes of the same type as the first non-static data member.

std::string 可能没有 public 数据成员(它们会是什么?),这是您用 T 绊倒的地方> (因为现在您同时拥有 privatepublic 数据成员;请参阅大胆的段落)。

但据我所知,没有实际要求 std::string 成为标准布局。这就是您的实现方式。

关于c++ - 为什么 std::string 是标准布局类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43912071/

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