我有一些基本问题来理解将派生对象存储到 C++ 中基类型容器中的行为。
谁能解释以下代码的输出?我认为这两个函数的行为应该是相同的。
// Output
test_func1
UseCount: 1
UseCount: 2
test_func2
UseCount: 1
UseCount: 1 // Why???
class base_class
{
public:
base_class() { }
virtual ~base_class() { }
};
class derived_class : public base_class
{
public:
derived_class(const std::shared_ptr<int>& i)
: base_class(),
i_(i)
{ }
~derived_class() { }
private:
std::shared_ptr<int> i_;
};
void test_func1()
{
std::cout << "test_func1" << std::endl;
std::vector<derived_class> v;
std::shared_ptr<int> i(new int(100));
std::cout << "UseCount: " << i.use_count() << std::endl;
v.push_back(derived_class(i));
std::cout << "UseCount: " << i.use_count() << std::endl;
}
void test_func2()
{
std::cout << "test_func2" << std::endl;
std::vector<base_class> v;
std::shared_ptr<int> i(new int(100));
std::cout << "UseCount: " << i.use_count() << std::endl;
v.push_back(derived_class(i));
std::cout << "UseCount: " << i.use_count() << std::endl;
}
int main(int argc, char *argv[])
{
test_func1();
test_func2();
return 0;
}