Reputation: 401
I declared a class template as follows:
template<typename T>
class C{
public:
C(T&,
shared_ptr<C<T>>&
);
// rest of the public interface
private:
T& rData;
shared_ptr<C<T>>& rP;
};
Subsequently, I defined the template constructor as:
template<typename T> C<T>::C(T& rDataArg,
shared_ptr<C<T>>& rPArg
):rData(rDataArg),
rP(rPArg)
{}
For the above definition I got the following -Wreorder
warning from the g++ compiler:
warning: field 'rData' will be initialized after field 'rP' [- Wreorder]
I reversed the order of initialization in my constructor definition and the warning disappeared.
Since both the members of the template class are references, I am curious about why the initialization in the constructor should adhere to the order specified by the compiler.
Please share your thoughts.
Upvotes: 1
Views: 1296
Reputation: 170045
Since both the members of the template class are references, I am curious about why the initialization in the constructor should adhere to the order specified by the compiler.
It's not specified by the compiler, it's specified by you. You specify it right here:
template<typename T>
class C{
private:
T& rData; // first
shared_ptr<C<T>>& rP; // second
};
Members will always be initialized by declaration order. It's a common source of bugs, when one ends up depending on another one that is yet of an indeterminate value. The warning is trying to help you prevent that. Though it's not a problem in your particular case, because the members don't depend on each other's initialization order.
Upvotes: 2