0

我有一些基本问题来理解将派生对象存储到 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;
}
4

2 回答 2

1

You can not store derived objects in std::vector of base class. Try to remember that.

That vector stores the base class, nothing else. On push_back the derived parts are sliced off.

If you want have a polymorphic collection, look up how to do that, 'polymorphic STL collection' is good query either on SO or in general.

于 2013-06-25T10:35:43.647 回答
0

push_back因为在第二种情况下,您的基类是从传递给方法的派生类复制构造的。而且您的基类不存储shared_ptr<int>. push_back您的派生类实例在返回后被销毁。

void test_func2()
{
    std::cout << "test_func2" << std::endl;
    std::vector<base_class> v;
    std::shared_ptr<int> i(new int(100)); //use count is 1
    std::cout << "UseCount: " << i.use_count() << std::endl;
    v.push_back(derived_class(i)); //base_class is copy constructed here and store in v
    //derived_class() is destroyed ans use count is still 1
    std::cout << "UseCount: " << i.use_count() << std::endl;
}
于 2013-06-25T10:30:22.437 回答