mercredi 28 juin 2017

How to pass my own smart pointer to function?

There is smart pointer class:

template <typename T>
class UniquePtr {
public:
    UniquePtr(T* obj)
        : obj(obj)
    {
    }
    UniquePtr(const UniquePtr& ptr) = delete;
    UniquePtr(UniquePtr&& ptr)
    {
        std::cout << "!! use of move !!" << std::endl;
        obj = std::move(ptr.obj);
        ptr.obj = nullptr;
    }

    UniquePtr& operator=(const UniquePtr& ptr) = delete;
    UniquePtr& operator=(const UniquePtr&& ptr) = delete;

    ~UniquePtr()
    {
        if (obj)
            delete obj;
    }

private:
    T* obj;
};

class for test:

class Test {
public:
    Test()
    {
        std::cout << "Test is created" << std::endl;
    }
    Test(const Test& obj) = delete;
    Test(const Test&& obj) = delete;
    Test& operator=(const Test& obj) = delete;
    Test& operator=(const Test&& obj) = delete;
    virtual ~Test()
    {
        std::cout << "Test is destructed" << std::endl;
    }
};

and function:

void function(UniquePtr<Test>&& ptr)
{
    std::vector<UniquePtr<Test>> v;
    v.push_back(std::move(ptr));
}

If I pass Test class, everything is OK:

UniquePtr<Test> ptr(new Test);
function(std::move(ptr));

But if I pass derived from Test class, code isn't compiled:

class TestChild : public Test {
public:
    TestChild()
    {
        std::cout << "Test child is created" << std::endl;
    }
    TestChild(const TestChild& obj) = delete;
    TestChild(const TestChild&& obj) = delete;
    TestChild& operator=(const TestChild& obj) = delete;
    TestChild& operator=(const TestChild&& obj) = delete;
    virtual ~TestChild()
    {
        std::cout << "Test child is destructed" << std::endl;
    }
};
UniquePtr<TestChild> ptr(new TestChild);
function(std::move(ptr));

error: invalid initialization of reference of type ‘UniquePtr&&’ from
expression of type ‘std::remove_reference&>::type {aka UniquePtr}’
function(std::move(ptr)); ~~~~~~~~~^~~~~

How can I make UniquePtr<TestChild> convertible to UniquePtr<Test>&& With std::unique_ptr this code works.

Aucun commentaire:

Enregistrer un commentaire