有智能指针类:
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));
}
如果我通过测试课,一切都还可以:
UniquePtr<Test> ptr(new Test);
function(std::move(ptr));
但是,如果我通过测试类派生,则不会编译代码:
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
此代码有效。
非常喜欢 std::unique_ptr
处理它,您需要为您的课程提供模板构造函数,该构造函数采用不同类型的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;
}