vendredi 1 décembre 2017

Invalid initialization of non-const reference in custom class

I have declared a C++ class. The constructor looks something like this:

template <class T>
class myclass
{
    public:
    mysclass(int a, int b);
    //More stuff
}

template <class T>
myclass<T>::myclass(int a, int b)
{
    //init stuff
    return;
}

And now I am using the class. I realized that I need to erase the information contained in the class and start from a fresh one, so I did something like this:

myclass<int> obj(1,1);
//Make fun stuff with obj
obj1 = myclass<int>(1,1); //Back to the beginning

These lines give me the following error:

invalid initialization of non-const reference of type ‘myclass<int>&’ from an rvalue of type ‘myclass<int>’

I have been reading some questions in SE, like this one or this one. I understand the answer given in that questions: we have a temporary value, which is going to be destroyed, so you cannot reference to it.

But I don't see where and why I am doing the same thing here. I guess that the temporary rvalue here is myclass<int>(1,1), and that for some reason the assignment is trying to assign it to a reference -and of course this is not possible.

So, why I am getting this error, and what can I do to solve it?

Thank you!

Aucun commentaire:

Enregistrer un commentaire