4

Here I have tried to use unique_ptr in constructor. It gives the following error:

function "std::unique_ptr<_Ty, _Dx>::operator=(const std::unique_ptr<_Ty, _Dx>::_Myt &) [with _Ty=ABC, _Dx=std::default_delete]" (declared at line 1487 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\memory") cannot be referenced -- it is a deleted function

How can I achieve it?

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
Veena
  • 249
  • 5
  • 15

1 Answers1

7

A unique pointer represents at most one owner of its pointee. Therefore, a unique pointer cannot be copied. It can however be moved, which transfers the (potential) ownership to the target of the move and leaves the source of the move null (i.e. not owning anything).

Given classes Xp, Xl and Xx, each with a member std::unique_ptr<T> p_;, the following constructors all work:

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); }

Only Xp and Xx have sensible constructors, though. They can be used as follows:

{
    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));
}

On the other hand, the constructor of Xl is weird and surprising:

// 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!
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084