Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Reference type in C++ a POD type?

Tags:

c++

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?

like image 790
Minh Tuấn Avatar asked Oct 02 '13 18:10

Minh Tuấn


3 Answers

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.

like image 65
David Hammen Avatar answered Oct 23 '22 06:10

David Hammen


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.

like image 31
stefan Avatar answered Oct 23 '22 08:10

stefan


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.

like image 4
Zac Howland Avatar answered Oct 23 '22 08:10

Zac Howland