将派生对象存储到基本类型的容器中 [英] Storing derived object into container of base type

查看:51
本文介绍了将派生对象存储到基本类型的容器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在理解C ++中将派生对象存储到基本类型的容器中的行为方面,我有一些基本问题.

I have some fundamental problems to understand the behavior of storing derived objects into container of base type in C++.

任何人都可以解释以下代码的输出吗?我认为两个函数的行为应该相同.

Can anyone explain the output of the below code? I thought the behavior should be the same in both functions.

// 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;
}

推荐答案

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

Because in the second case your base class was copy-constructed from the derived class passed to push_back method. And your base class does not store shared_ptr<int>. You derived class instance was destroyed after push_back returned.

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;
}

这篇关于将派生对象存储到基本类型的容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆