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 
10
  • 6
    remove n = n1; Commented Dec 12, 2015 at 16:14
  • 2
    ABCD(std::unique_ptr<ABC> & n1) : n(n1) - Who is going to own the pointer? Commented Dec 12, 2015 at 16:16
  • 1
    What is worse, you have reference to unique_ptr, not copy Commented Dec 12, 2015 at 16:16
  • 1
    why are people downvoting this question? Commented Dec 12, 2015 at 16:17
  • 1
    It needs to be n(std::move(n1)). Commented Dec 12, 2015 at 16:17

1 Answer 1

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! 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.