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

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...