给定一个您想要在我的情况下具有递归字段的类:

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/

10-11 22:53
查看更多