Is Reference type in C++ a POD type too?
Is int&
is a POD type? and what about
struct Q { int& i; }
Anyone can help me?
A POD type is any intrinsic type or aggregate of intrinsic types (basically, anything that does not have a custom constructor, destructor, copy-constructor, copy-assignment operator, nor non-static pointer-to-member types (more details here)
Since a member that references something must be set via a custom constructor, it would violate the first requirement. In short, a struct that declares a reference type as a member is not a POD type.
There is a standard way (using C++11) to determine that at compile time.
#include <iostream>
#include <type_traits>
struct Q
{
int& i;
};
int main()
{
std::cout << std::is_pod<int>::value << "\t";
std::cout << std::is_pod<int&>::value << "\t";
std::cout << std::is_pod<Q>::value << "\n";
}
Demo: http://ideone.com/PECzfT
The output will be 1 0 0, so no a reference to int is not POD.
No.
The only way to set a member that references something is via a user-declared constructor, so therefore, your structure is non-POD.
Update:
The answer is still no.
The C++03 standard specifies that "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and ..." (C++03 standard sect. 9 para 5).
In C++11, a POD-struct "is a class that is both a trivial class and a standard-layout class, and ..." and a standard-layout class "has no non-static data members of type non-standard-layout class (or array of such types) or reference" (C++11 standard sect. 9 para. 6-9).
I parse those phrases that end with "or reference" to immediately mean that a POD class cannot contain non-static data members that are of any reference type. The lack of a comma before the "or reference" does give way to other interpretations (e.g., it's a reference to a non-POD class that makes the reference bad, not a reference per se), but I'm sticking with my interpretation.