【问题标题】:How to use unique_ptr in constructor? [duplicate]如何在构造函数中使用 unique_ptr? [复制]
【发布时间】:2016-03-18 10:58:20
【问题描述】:

这里我尝试在构造函数中使用 unique_ptr。它给出了以下错误:

函数“std::unique_ptr<_ty _dx>::operator=(const std::unique_ptr<_ty _dx>::_Myt &) [with _Ty=ABC, _Dx=std::default_delete]”(声明在“C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\memory”的第 1487 行)不能被引用——它是一个被删除的函数

我怎样才能实现它?

StructCol.h

#include "stdafx.h"
#ifndef StructCol_H
#define StructCol_H

#include<string>
#include<memory>
using namespace std;

class ABCD
{
    public:
    std::unique_ptr<ABC> & n;

    ABCD(std::unique_ptr<ABC> & n1) : n(n1)
    {
        n = n1;
    }

    void print()
    {
        cout << n->no << endl;
        cout << n->text_c << endl;
        cout << n->no_c << endl;
    }
};

class ABC
{
public:
    string test;
    int no;
    string text_c;
    int no_c;

    ABC()
    {

    }

    ABC(string text_c1, int no_c1)
    {
        text_c = text_c1;
        no_c = no_c1;
    }

    void print()
    {
        cout << test << endl;
        cout << no << endl;
        cout << text_c << endl;
        cout << no_c << endl;
    }
};

#endif

【问题讨论】:

  • 删除n = n1;
  • ABCD(std::unique_ptr&lt;ABC&gt; &amp; n1) : n(n1) - 谁将拥有指针?
  • 更糟糕的是,您引用的是 unique_ptr,而不是复制
  • 为什么人们不赞成这个问题?
  • 必须是n(std::move(n1))

标签: c++


【解决方案1】:

唯一的指针最多代表其指针对象的 一个 所有者。因此,无法复制唯一指针。然而,它可以被移动,这会将(潜在的)所有权转移给移动的目标,并使移动的源为空(即不拥有任何东西)。

给定类 XpXlXx,每个类都有一个成员 std::unique_ptr&lt;T&gt; p_;,以下构造函数都可以工作:

Xp(std::unique_ptr<T> p) : p_(std::move(p)) {}
Xp(std::unique_ptr<T> p) { p_ = std::move(p); }

Xl(std::unique_ptr<T> & p) : p_(std::move(p)) {}
Xl(std::unique_ptr<T> & p) { p_ = std::move(p); }

Xx(std::unique_ptr<T> && p) : p_(std::move(p)) {}
Xx(std::unique_ptr<T> && p) { p_ = std::move(p); }

不过,只有 XpXx 有合理的构造函数。它们可以按如下方式使用:

{
    Xp xp(std::make_unique<T>(a, b ,c));
    Xx xx(std::make_unique<T>(a, b ,c));
}
{
    auto p = std::make_unique<T>(a, b ,c);
    // Xp xp(p);  // Error, cannot duplicate p!
    Xp xp(std::move(p));
}
{
    auto p = std::make_unique<T>(a, b ,c);
    // Xx xx(p);  // Error, cannot duplicate p!
    Xx xx(std::move(p));
}

另一方面,Xl 的构造函数又奇怪又令人惊讶:

// Xl xl(std::make_unique<T>(a, b ,c));  // Error, cannot bind to temporary
auto p = std::make_unique<T>(a, b ,c);
Xl xp(p);              // OK?!?
assert(p == nullptr);  // grand theft autoptr!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 2013-03-27
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    相关资源
    最近更新 更多