vendredi 24 avril 2020

How to move object from a function return correctly?

I have an Object that should not be copied, but only moved, and so I've tried to ensure that a function returns the T&& of the object. My problem is that the object is being destroyed before it returns and I don't know how to do this properly.

#include <iostream>

class Foo
{public:
    Foo() { 
        a = new int; 
        std::cout << a << '\n'; 
    }
    Foo(const Foo& other) = delete;
    Foo(Foo&& other) { 
        a = other.a; other.a = nullptr; 
    }
    ~Foo() { 
        std::cout << a << '\n';
        delete a; 
    }
    void operator= (const Foo& other) = delete;
    void operator= (Foo&& other) { 
        a = other.a; 
        other.a = nullptr; 
    }
    int* a;
};

Foo&& createNewFoo()
{
    return std::move(Foo());
}

int main()
{
    Foo foo = createNewFoo(); // The pointer is deleted before this assigns to foo

}

Aucun commentaire:

Enregistrer un commentaire