mercredi 6 juillet 2016

How to enforce copy elision, why it won't work with deleted copy constructor?

I have an uncopiable class. Copying this would be problematic. I want to guarantee that it won't be ever copyied, so I made its copy constructor deleted:

class A {
  public:
    A();
    A(const A&) = delete;
};

A fun() {
  return A();
};

int main() {
  A a = fun();
};

Unfortunately, g++ won't compile this on the reason:

t.cc: In function ‘A fun()’:
t.cc:8:12: error: use of deleted function ‘A::A(const A&)’
   return A();
            ^
t.cc:4:5: note: declared here
     A(const A&) = delete;
     ^
t.cc: In function ‘int main()’:
t.cc:12:13: error: use of deleted function ‘A::A(const A&)’
   A a = fun();
             ^
t.cc:4:5: note: declared here
     A(const A&) = delete;
     ^

But this is a very clear situation where copy elision should be used, so the copy constructor shouldn't be ever called. Why is it so?

Aucun commentaire:

Enregistrer un commentaire