Forcing the copy constructor

I have a function like this:

Object Class::function() {
    Object o;
    return o;
}

Now that I call it this way:

Object o = Class::function();

he wants to use a move constructor. However, I want it to use the copy constructor. How to make it not use the move constructor? I removed the move constructor, but then it will not compile.

EDIT: my constructors look like this:

Object(const Object & other) { ... }
Object(Object & other) { ... }
Object(Object && other)=delete;
+4
source share
1 answer

If you have a user-declared (manual declaration) copy of ctor, the ctor will not be declared implicitly. Just leave the ctor move, and it will not take part in overload resolution (i.e. it will not indicate it as deleted, just leave the whole announcement).

CWG DR 1402 : ctor , ctor, . , ctor . . ctor, " , ". , ctor ( ), , ctor ( , ).

#include <iostream>

struct loud
{
    loud() { std::cout << "default ctor\n"; }
    loud(loud const&) { std::cout << "copy ctor\n"; }
    loud(loud&&) { std::cout << "move ctor\n"; }
    ~loud() { std::cout << "dtor\n"; }
};

struct foo
{
    loud l;
    foo() = default;
    foo(foo const& p) : l(p.l) { /*..*/ }; // or `= default;`
    // don't add a move ctor, not even deleted!
};

foo make_foo()
{
    return {{}};
}

int main()
{
    auto x = make_foo();
}

(, -fno-elide-constructors). :

default ctor
copy ctor
dtor
dtor

+4

Source: https://habr.com/ru/post/1530976/


All Articles