dimanche 14 octobre 2018

In place construction for class with deleted move and copy constructors

Assume I have a class with deleted copy and move constructors. I'd like to have a factory function that constructs the object in place depending on some bool x, without allocating dynamic memory (no unique_ptr, new, etc).

Two questions:

  1. Why does the below throw a use of deleted function 'Foo::Foo(const Foo&&)'? Where is the move happening?

  2. How can I achieve something to the effect of what I'm trying to do?

Thanks. Code below:

class Foo
{
public:
    Foo(int _x) : x(_x) {}
    Foo(const Foo&) = delete;
    Foo(const Foo&&) = delete;
    int x = 10;
};

class Bar : Foo
{
public:
    Bar(int _y) : Foo(10), y(_y) {}
    int y;
};

Foo make_foo(int a, bool x) {
    if (x) {
        return Foo{a};
    } else {
        return Bar{a};
    }
}

int main() {
    Foo&& x = make_foo(10, true);
}

Link: https://coliru.stacked-crooked.com/a/196d69ec513d536d

Aucun commentaire:

Enregistrer un commentaire