3

Taking the example from here: trivial vs. standard layout vs. POD

The following code passes:

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

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

Yet the following does not:

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

So if all it takes for a type not to be a standard layout, then how could std::string possible be one?

Community
  • 1
  • 1
Sam Kellett
  • 1,277
  • 12
  • 33
  • 1
    "So if all it takes for a type not to be a standard layout" .. if it takes what? to not be standard layout? – 463035818_is_not_an_ai May 11 '17 at 09:55
  • 1
    I don't think the standard guarantees this? – M.M May 11 '17 at 09:59
  • 1
    This is kind of an odd question, with a weak premise. First you don't identify what you find evidently "simple" about `T` ("all it takes") and then you don't explain why you think it should be so outlandish that `std::string` have some property that `T` doesn't. – Lightness Races in Orbit May 11 '17 at 10:02

2 Answers2

9

Let's look at the actual rules for standard layout:

[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 probably has no public data members (what would they be?), which is where you tripped up with your T (since now you have both private and public data members; see emboldened passage).

But as far as I can tell there is no actual requirement for std::string to be standard layout. That's just how your implementation has done it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    By the way, a little treat for "struct vs class" wrong'uns: _"9/7: A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class."_ i.e. literally exactly the same dang thing – Lightness Races in Orbit May 11 '17 at 09:59
  • Gotta love the standard for the clarity it provides for struct and class – Passer By May 11 '17 at 10:06
2

According to the requirement of StandardLayoutType:

Requirements

  • All non-static data members have the same access control
  • ...

That's why T failed to be standard layout type. std::string is just satisfying the requirements.

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405