I have the following Container class
template <typename T>
class Container
{
private:
std::vector<std::shared_ptr<T>> items_;
public:
void addItem(std::shared_ptr<T> item)
{
std::cout << "useCount addItem pre: " << item.use_count() << std::endl;
items_.push_back(std::move(item));
std::cout << "useCount addItem post: " << item.use_count() << std::endl;
}
};
and I'm calling it like this
int main(int argc, char** argv) {
std::unique_ptr<Container<std::string>> container = std::make_unique<Container<std::string>>();
std::shared_ptr<std::string> s = std::make_shared<std::string>("hello");
std::cout << "useCount main pre: " << s.use_count() << std::endl;
container->addItem(s);
std::cout << "useCount main post: " << s.use_count() << std::endl;
return 0;
}
This is the output I get
useCount main pre: 1
useCount addItem pre: 2
useCount addItem post: 0
useCount main post: 2
Line by line...
Makes sense, there's only one reference to
sas soon as its definedMakes sense,
sgets copied intoitemso its reference count is incremented by 1I've given
items_ownership ofitem, so the reference count shouldn't change sinceaddItemhas relinquished ownership and transferred it toitems_. I expect the reference count to be 2, once frommainand once fromitems_. Instead it's 0.Makes sense as long as one reference is from
mainand one reference is fromitems_.
Thanks for any clarification!