Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

c++ - What does `invalid initialization of non-const reference` mean?

When compiling this code I get the following error:

In function 'int main()': Line 11: error: invalid initialization of non-const reference of type 'Main&' from a temporary of type 'Main'

Here's my code:

template <class T>
struct Main
{
    static Main tempFunction(){
       return Main();
    }
};

int main()
{
   Main<int> &mainReference = Main<int>::tempFunction(); // <- line 11
}

I don't understand why? Can anyone explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C++ temporaries cannot be bound to non-constant references.

Main<int> &mainReference = Main<int>::tempFunction();

Here you are trying to assign the result of an rvalue expression to a non-constant reference mainReference which is invalid.

Try making it const


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...