Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move constructor when returning a "chained" object

Tags:

c++

Say I have a class that is move-only, and this class has methods that "chain". example:

struct C {
    C() = default;
    C(C const&) = delete;
    C(C&&) = default;

    C& chained() {
        return *this;
    }

    int a;
};

C foo(C c) {
    return c.chained();
}

int main()
{
  auto o = foo(C{});
}

I get an error at the return statement of foo: "Use of deleted function 'C::C(const C&)'".

Why is trying to call the copy constructor? Shouldn't it be using the move constructor since its a return statement?

like image 415
Baruch Avatar asked Apr 09 '26 20:04

Baruch


1 Answers

Why is trying to call the copy constructor? Shouldn't it be using the move constructor since its a return statement?

No. You are referring to, and misinterpreting, copy elision (as pertaining to NRVO). Only when the returned expression is a an id-expression (just a name) that refers to an object from the function's parameter list or a local, will a move be attempted first.

You don't return an id-expression, your expression is the result of a call to a member function.

like image 131
StoryTeller - Unslander Monica Avatar answered Apr 11 '26 11:04

StoryTeller - Unslander Monica