Compiler Error C2354

Error Message

'reference' : initialization of reference member requires a temporary variable

A constructor initializes a reference to a member instead of initializing the member.

It is invalid to initialize a reference member of a class in the class's constructor with a temporary variable. An attempt to do so generates the C2354 error.

The following sample generates C2354:

// C2354.cpp
int temp() { return 1; }
class Test
    int member;
    int& ref_member;

Test::Test() : ref_member( temp() )
{   // C2354

When this error is encountered, the solution is to change the code so that the reference member is not initialized to a temporary variable. The reference must be initialized to an object that will exist for the lifetime of the reference member.

Community Additions