lundi 1 février 2016

Difference between returning 'const' or non-const reference [duplicate]

This question already has an answer here:

I have a class with a list as member, and a getter on this list:

class A
{
public:
  const std::list<int*>& get() const {
    return list;
  }

private:
  std::list<int*> list;
}; 

Why the get function has to return a const std::list and not just an std::list ?

Otherwise I get this error :

error: invalid initialization of reference of type 'std::list&' from expression of type 'const std::list'

Aucun commentaire:

Enregistrer un commentaire