Why does the Node destructor get 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";
}
Your vector contains five copies of the original shared pointer, all sharing ownership of the one single pointee .
To create five separate objects, each owned by one shared pointer, write it like this:
std::vector<std::shared_ptr<Node>> nodes;
for (int i = 0; i != 5; ++i) nodes.push_back(std::make_shared<Node>());
Kerrek SB explained the situation well, but to do what you want to do in a different way, you could also the std::generate_n
algorithm:
std::vector<std::shared_ptr<Node>> nodes;
std::generate_n(
std::back_inserter(nodes),
5,
std::make_shared<Node>);
This is more along the lines of what you thought you were doing originally.
Or, similarly:
std::vector<std::shared_ptr<Node>> nodes(5);
std::generate(nodes.begin(), nodes.end(), std::make_shared<Node>);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.