成员为unique_ptr时删除副本构造函数 [英] Deleted copy constructor when member is an unique_ptr

查看:75
本文介绍了成员为unique_ptr时删除副本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可以正常工作:

class Test
{
    int* ptr = new int(10);
};

int main()
{       
     Test o;
     Test t = o;
}

但是当我们使用unique_ptr而不是raw ptr时,会出现错误:

But when we use unique_ptr instead raw ptr, we get an error:

error: use of deleted function 'Test::Test(const Test&)'

和示例代码:

class Test
{
     std::unique_ptr<int> ptr = std::make_unique<int>(1);
};

int main()
{       
     Test o;
     Test t = o;
}

这是怎么回事?

推荐答案

这是怎么回事?

您不能创建Test的第二个实例,因为这意味着您需要唯一的副本,而不是唯一的.unique_ptr只能移动.尝试实现移动分配运算符,并像这样移动 o :

You cannot create a second instance of Test because this implies you need a copy of the unique_ptr, which is not possbile. A unique_ptr can only be moved. Try implementing a move asignment operator and move o like so:

class Test
{
public:
    Test() = default;

    Test(Test&& other) noexcept
        : ptr(std::move(other.ptr))
    {
    }

private:
    std::unique_ptr<int> ptr = std::make_unique<int>(1);
};

int main()
{
    Test o;
    Test t = std::move(o);
}

如果要复制unique_ptr底层的int,则需要定义一个自定义复制构造函数,如下所示:

If you want to copy the int underlying the unique_ptr, you need to define a custom copy constructor like this:

class Test
{
public:
    Test() = default;

    Test(const Test& other)
        : 
    ptr(new int(*other.ptr))
    {

    }

    Test(Test&& other) noexcept
        : ptr(std::move(other.ptr))
    {
    }

private:
    std::unique_ptr<int> ptr = std::make_unique<int>(1);
};

int main()
{
    Test o;
    Test t = o;
}

但是,注意,指针指向两个 DIFFERENT 整数.如果要共享所有权,则必须(并且应该)使用shared_ptr,如下所示:

However, NOTE, that the pointers point to two DIFFERENT ints. If you want shared ownership, you have to (and should) use shared_ptr like this:

class Test
{
private:
    std::shared_ptr<int> ptr = std::make_shared<int>(1);
};

int main()
{
    Test o;
    Test t = o;
}

这篇关于成员为unique_ptr时删除副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆