POD implications for a struct which holds an standard library container

天大地大妈咪最大 提交于 2020-01-14 19:37:59

问题


I came across this question recently. My goal is to understand how the C++ compiler views struct definitions which hold standard library containers such as std::vector.

Ben Voigt's answer to the linked question cites the following from the C++0x standard:

....

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes. — end note ]

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,

....

I'm almost certain that the bolded text implies that the following is undefined behavior

struct A 
{
    std::vector< SomeType > myVec;
    int myC;  
    A( int c ) : myC : (c) {}
};

int main( void )
{
    A one( 1 );
    A two( 2 );

    SomeType k, z;
    one.myVec.push_back( k );
    two.myVec.push_back( z );

    memcpy( &two, &one, sizeof( A ) ); // bad juju
}

And the same would be the case for any type which is from the standard library, including simpler types such as std::string. This would be due to the nature of the library's design, given its large usage of inheritance and template programming.

So, while struct A would resemble that of a POD type, the fact that it contains that standard library type automatically invalidates it from that category, as far as the compiler is concerned.

Are my assumptions correct?


回答1:


No. Your basic assumptions are flawed. "Standard layout" is not related to templates. E.g. std::pair<T1, T2> has standard layout if and only if both T1 and T2 do. Same goes for std::array<T,N>

However, none of the Containers have standard layout. The whole point of their allocators is to have advanced memory management.



来源:https://stackoverflow.com/questions/27165436/pod-implications-for-a-struct-which-holds-an-standard-library-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!