Why is push_back succeeding in a structure containing unique_ptr, unless that structure has a custom destructor?

The following code compiles if and only if I delete the custom destructor Foo.

struct Foo {
    std::unique_ptr <int> bar;
    ~Foo (void) {} // This Line
};
std::vector <Foo> foos;
foos.push_back (Foo ());

Here is what I think of the situation:

It does not work because it unique_ptrscannot be copied, but std::vector::push_back (thing)calls the thing'scopy constructor . If I write Foomy own copy constructor that explicitly moves bar, then everything will be fine.

However, disabling This Linewill compile the code.

I thought that this should not compile even without This Line, because I'm still trying push_backa unique_ptr.

, ?

: gcc -std=gnu++11 64- Debian Linux

+4
3

, , , , :

, .

++ 11 , , , , . ( , Visual Studio , Mac Xcode .)

, , , . /, , . (. .)

+6

"12.8.9 [class.copy]"

X , , :

  • X ,
  • X ,
  • X ,
  • X
  • .

, , move-constructor. "12.8.15" , move-constructor unique_ptr:

/ X / .

, move :

struct Foo {
         std::unique_ptr <int> bar;

         Foo() = default;
         Foo(Foo&&) = default;

         ~Foo (void) {} // This Line
 };
+5

, _ptr . , :

Foo(){}
Foo &operator=(Foo &&o) {
    if (this != &o)
        bar = std::move(o.bar);
    return *this;
}
Foo(Foo &&o) : bar(std::move(o.bar)) {}

Foo , :

Foo(Foo const &) = delete;
Foo &operator=(Foo const &) = delete;  

[]

, , google, :

destructor
copy constructor
move constructor
copy assignment operator
move assignment operator

you should consider implementing (or deleting) them, and this is especially true when using unique_ptr, which uses move semantics.

When you comment on the destructor, you enter rule 0.

+1
source

Source: https://habr.com/ru/post/1529527/


All Articles