Std :: vector emplace_back using the copy constructor, although a move constructor is available

I came across an odd case where the vector emplace_back method uses a type constructor when it is available, even if the same code compiles and works fine with the same copy constructor that is deleted (it relies on moves instead).

I was able to come up with a rather brief example:

using namespace std;
struct node {
    vector<node> children;

    node(const node&){
        printf("Copy!\n");
    }

    node(node&&){
        printf("Move!\n");
    } 

    node(){}
    node(int a) {}
};

int main(int argc, const char * argv[]) {
    vector<node> vec;

    node node(1);
    node.children.emplace_back(2);

    vec.emplace_back(move(node));
    vec.emplace_back(3);

    return 0;
} 

For me, this prints:

Move!
Copy!

But just commenting on the copy constructor will lead to the conclusion:

Move!
Move!

Debugging I can say that the copy occurred during the last emplace_back, so it seems that the copy occurred during the resizing of the vector. Actually adding 'vec.reserve (2);' excludes copy (as well as 2nd move without copy constructor)

, node, - , ?

: clang++ -v

Apple LLVM 8.0.0 (clang-800.0.42.1)

: x86_64-apple-darwin16.1.0

- = ++ 11

!

+4

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


All Articles