如何将自己的智能指针传递给函数?

时间:2017-06-28 15:33:22

标签: c++ c++11 smart-pointers

有智能指针类:

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()
    {
        delete obj;
    }

private:
    T* obj;
};

测试课程:

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;
    }
};

和功能:

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

如果我通过Test类,一切正常:

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

但是,如果我从Test类传递派生,则代码不会被编译:

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)); ~~~~~~~~~^~~~~

如何将UniquePtr<TestChild>转换为UniquePtr<Test>&& 使用std::unique_ptr此代码可以正常运行。

1 个答案:

答案 0 :(得分:2)

就像std::unique_ptr handles it一样,你需要为你的类提供一个模板化的构造函数,它采用不同类型的UniquePtr(允许SFINAE处理继承检查),然后将其用于初始化您的UniquePtr州。

template<typename U>
UniquePtr(UniquePtr<U> && other) {
    obj = other.obj;//Won't compile if U is not a subclass of T.
    other.obj = nullptr;
}