C ++ 11 standard-layout - using the same access control

I thought the whole point of POD (C ++ 11, trivial + standard-layout) is to make sure the type is compatible with C.

Given the following code:

// that one is a standard layout, and trivial which makes it a c++11 POD struct Bar { public: int x; public: int y; }; 

AFAIU, the compiler can reorder x and y. Wouldn't that break compatibility with C?

Why is this replication of the 98/03 POD definition in C ++ 11 considered a good idea?

+4
source share
3 answers

AFAIU, the compiler can reorder x and y. Wouldn't that break compatibility with C?

In C ++ 03, this is possible. In C ++ 11, it cannot. The standard C ++ 11 build rules only require that all members have the same access control. They should not be advertised in the same access control area.

Why is this replication of the 98/03 POD definition in C ++ 11 considered a good idea?

I think you misunderstand things. C ++ 11 rules allow standard layouts (and therefore potentially compatible with layouts with C types) to have more types, not less. Thus, there is no real flaw in loosening the rules.

+4
source

I thought the whole point of POD (C ++ 11, trivial + standard-layout) is to make sure the type is compatible with C.

Not quite the whole point, but yes, this is one of the properties of the POD.

 // that one is a standard layout, and trivial which makes it a c++11 POD 

Right.

AFAIU, the compiler can reorder x and y. Wouldn't that break compatibility with C?

We have already established that this is a POD, which means that the compiler will maintain compatibility with C. Maintaining compatibility with C does not violate compatibility with C.

Why is this replication of the 98/03 POD definition in C ++ 11 considered a good idea?

Because he did not break anything.

+3
source

The point of the POD is not only to make sure that the type is compatible with C - note that a type with an access specifier ( public , private , etc.) is by definition incompatible with C, because C doesn I have access specifiers. The main property of the POD type is that it can be memcpy'ed around.

Having more than one access specifier in a C ++ type allows the compiler to lay out the type in an unspecified way, and this has been true for some time (this is not new with C ++ 11):

From C ++ 03 9.2 / 12

Non-static data members of a (non-single) class declared without an intermediate access specifier are allocated so that subsequent members have higher addresses inside the class object. Distribution order Non-static data elements separated by an access specifier are not defined (11.1).

However, this does not make the type of non-POD - it can still be a POD, just not the one that can be portable in C.

-1
source

Source: https://habr.com/ru/post/1434087/


All Articles