return const auto object -- and Qt implicit sharing

379 views Asked by At

So it is known this code is not sensical:

const int foo() 
{
  int n = // do computation...;
  return n;
}

Because what meaning is to return "const int" when it is copied anyway?

But with classes with implicit sharing (COW) like Qt containers, it makes sense again? Consider:

const QList<mytype> get_list()
{
   QList<mytype> lst;
   // do stuff to fill list;
   return lst;
}

Now I can do:

   const QList<mytype> mylst = get_list();

Since Qt has implicit sharing for containers, it should work OK because return lst doesn't really copy the contents of list, just increase refcount, and const make sure I can't modify it (if get_list want to ensure it for some reason, or needs it to be const method itself). Is my thinking correct here?

1

There are 1 answers

3
iammilind On

and const make sure I can't modify it ... Is my thinking correct here?

I couldn't understand the whole question. But, above part is not correct. You are returning just a const value from the function and it doesn't mandate the receiving end also to be a const. So removing const from mylst is allowed and it again becomes modifiable.

/* const */ QList<mytype> mylst = get_list();  // ok! 'mylst' is modifiable