gpt4 book ai didi

c++ - 管理生命周期但也复制内存的智能指针

转载 作者:行者123 更新时间:2023-11-30 01:50:11 24 4
gpt4 key购买 nike

在我的案例中,给定一个你想要递归字段的类:

class SemiVariant {

union {
std::pair<SemiVariant, SemiVariant> pair_value_;
int something_else_;
}
};

基本上这不可能,因为显然我们有一个不完整的类型。使用 unique_ptr 管理内存并允许不完整类型也不起作用。我不知道是否已经有一个现有的类将用作 optional 但可以使用动态内存。unique_ptr 不适合我的情况,因为它们禁用了默认的复制构造函数。我想存在。

最佳答案

您可以为 std::unique_ptr 编写自己的可复制扩展。

template <class T>
class opaque_pointer : public std::unique_ptr < T >
{
public:
// Simple construction by moving a uniqe_ptr into it.
opaque_pointer(std::unique_ptr<T>&& rhs)
:
std::unique_ptr<T>(std::move(rhs))
{
// Print something for observation. Remember to remove it.
std::cout << "opaque_pointer(std::unique_ptr<T>&& rhs)" << endl;
}

// The copy constructor you want!
opaque_pointer(const opaque_pointer& rhs)
:
std::unique_ptr<T>(std::make_unique<T>(*rhs))
{
// Print something for observation. Remember to remove it.
std::cout << "opaque_pointer(const opaque_pointer& rhs)" << endl;
}

// It needs a move constructor too.
opaque_pointer(opaque_pointer&& rhs)
:
std::unique_ptr<T>(std::move(rhs))
{
// Print something for observation. Remember to remove it.
std::cout << "opaque_pointer(opaque_pointer&& rhs)" << endl;
}
};

那么,我们可以试试看。

struct Widget
{
int i;
Widget(int i) : i(i) {}
~Widget()
{
std::cout << "~Widget()" << " " << i << endl;
}

Widget& operator += (int rhs) { i += rhs; return *this; }

friend std::ostream& operator<<(std::ostream& out, const Widget& w)
{
return out << w.i;
}
};

int main()
{
std::cout << "+++ Let's try the simple constructor and copy constructor! +++" << endl;

opaque_pointer<Widget> op = make_unique<Widget>(100);
opaque_pointer<Widget> op2 = op;

*op2 += 2;

cout << "Value: " << *op << " " << *op2 << endl;
cout << "Owning: " << !!op << " " << !!op2 << endl;

std::cout << endl << "+++ Let's move it! +++" << endl;

opaque_pointer<Widget> op3 = std::move(op);

*op3 += 30;

cout << "Value: " << *op3 << endl;
cout << "Owning: " << !!op << " " << !!op3 << endl;

std::cout << endl << "+++ By the way, does it really manage life time? +++" << endl;
}

结果是这样的

+++ Let's try the simple constructor and copy constructor! +++
opaque_pointer(std::unique_ptr<T>&& rhs)
opaque_pointer(const opaque_pointer& rhs)
Value: 100 102
Owning: 1 1

+++ Let's move it! +++
opaque_pointer(opaque_pointer&& rhs)
Value: 130
Owning: 0 1

+++ By the way, does it really manage life time? +++
~Widget() 130
~Widget() 102

关于c++ - 管理生命周期但也复制内存的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com