Question

struct A
{
  int i;
};

struct B
{
 B(){} 
 int i;
}

Hi,all

I know "POD means Plain Old Data type which by definition cannot have user-defined constructor". But I can't understand why this rule is effective when "definition have an user-defined default-con".

There is no difference of their memory layout.Why type A is POD,but not B?

Was it helpful?

Solution

The reason is simple. Once you define a constructor (any constructor), the language assumes that the class needs some sort of initialization; that just copying the bits in its image won't be sufficient to create a new instance. And one of the important characteristics of PODs is that they can be memcpy'ed.

In sum, the compiler does not look at the contents of a class to determine whether it is POD or not (except to see if any of the members are PODS). It looks at whether you've defined anything special which might affect the initialization, assignment or destruction of those members.

OTHER TIPS

The concept of POD has been split into trivial and standardy-layout concepts. You can query those properties through the standard type traits.

Class B is not POD because it is not trivial. It is not trivial because it has a user-provided default constructor. Either omit that or use the new C++11 =default syntax.

#include <type_traits>
#include <iostream>
#include <ios>

struct A
{
  int i;
};

struct B
{
 B(){} 
 int i;
};

struct C
{
 C() = default;
 int i;
};

int main()
{
    std::cout << std::boolalpha << std::is_pod<A>::value << " ";
    std::cout << std::boolalpha << std::is_trivial<A>::value << " ";
    std::cout << std::boolalpha << std::is_standard_layout<A>::value << "\n";

    std::cout << std::boolalpha << std::is_pod<B>::value << " ";
    std::cout << std::boolalpha << std::is_trivial<B>::value << " ";
    std::cout << std::boolalpha << std::is_standard_layout<B>::value << "\n";

    std::cout << std::boolalpha << std::is_pod<C>::value << " ";
    std::cout << std::boolalpha << std::is_trivial<C>::value << " ";
    std::cout << std::boolalpha << std::is_standard_layout<C>::value << "\n";
}

Online output:

true true true
false false true
true true true

PODs allow the compiler to do certain optimizations. As a rule of thumb, a type is POD if the compiler is allowed to treat the struct the same way as a C-compiler would.

In particular, when initializing a POD struct, the compiler just needs to reserve memory of the appropriate size, it does not need to worry about initialization. Initialization can be requested explicitly by the programmer, but it never happens implicitly as could be the case with a user-defined constructor.

For example, a user-defined default constructor might require the data to get initialized to 0. In general, the default constructor might even have arbitrary side effects that the compiler needs to consider.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top