Search code examples
c++assignment-operator

assignment operator template and copy constructor in c++


so basically i m trying to use the assignment operator in way to allocate 2 vars :

S solutionCourante, bestSolution; //(S is a template class)
bestSolution = solutionCourante = solutionInitiale;

Here is the operator i'm dealing with :

template <class S, class T>
const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
{

this->lSommets = graphe.lSommets->copieListe(graphe.lSommets);
this->lAretes = graphe.lAretes->copieListe(graphe.lAretes);

return *this;
}

Here is my copy constructor :

template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
{
 *this = graphe;
}

(I know the constructor copy is a bit bad coded but works)

So at any time, i can see that "bestSolution" and "solutionCourante" are not NULL but empty, and i don't understand why because in my operator "monGraphe" is filled. So it seems like i m doing something wrong when returning the value, first time i m trying to do this operator.

According to :

const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)

graphe is the item i want to copy and we got *this = graphe?


Solution

  • An assignment operator is supposed to assign a value to "this", not allocate a new one.

    template <class S, class T>
    Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
    {
        lSommets = graphe.lSommets ? new PElement<Sommet<T>>(*graphe.lSommets) : nullptr;
        lAretes = graphe.lAretes ? new PElement<Arete<S,T>>(*graphe.lAretes) : nullptr;
        prochaineClef = graphe.prochaineClef;
        return *this;
    }
    template <class S, class T>
    Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
    {
        *this = graphe;
    }
    

    Generally speaking, you should not return something allocated on the heap with new, because any ownership information is lost. You should probably try to use smart pointers such as std::unique_ptr.