Smart pointer destructor call vector

Why is the Node destructor called only once instead of 5 times in the code below?

#include <iostream> #include <vector> #include <memory> struct Node { ~Node() {std::cout << "Node destructor called.\n";} }; void foo() { std::vector<std::shared_ptr<Node>> nodes(5, std::make_shared<Node>()); } int main() { foo(); std::cout << "foo() ended.\n"; } 
+5
source share
2 answers

Your vector contains five copies of the original common index, all sharing the ownership of one person.

To create five separate objects, each of which belongs to one common index, write it as follows:

 std::vector<std::shared_ptr<Node>> nodes; for (int i = 0; i != 5; ++i) nodes.push_back(std::make_shared<Node>()); 
+12
source

Kerrek SB explained the situation well, but to do what you want to do differently, you can also std::generate_n algorithm:

 std::vector<std::shared_ptr<Node>> nodes; std::generate_n( std::back_inserter(nodes), 5, std::make_shared<Node>); 

It is more like what you thought you were doing initially.

Or similarly:

 std::vector<std::shared_ptr<Node>> nodes(5); std::generate(nodes.begin(), nodes.end(), std::make_shared<Node>); 
+1
source

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


All Articles