本文介绍了存储基础和派生对象混合的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的事情?我知道如果容器是基类值类型,那么存储的派生对象是'sliced'。如果container是派生类类型,则无法存储基类对象。对吗?

What is the right thing to do? I know that if the container is of base class value type, then derived object stored is 'sliced'. If container is of derived class type, then base class object can not be stored. Right?

如果使用指针,auto_ptr不能使用,因为它有复制语义问题。 is shared_ptr是唯一的解决方案来处理这个问题吗?

If to go with pointers, auto_ptr can not be used because it's have copy semantic problem. Is shared_ptr the only solutions to handle this problem?

任何人都可以提供更多的细节,示例代码或在线文章解决这个问题?这应该是一个很常见的问题,但我没有在教科书或在线上找到很多信息。

Could anyone provide more details, sample code or online articles that address this issue? It should be quite a common question however i did not find much information on it in textbook or online.

提前感谢。

btw,我只搜索unique_ptr。它似乎不支持复制语义。所以,它不是只有auto_ptr在STL中使用的安全,但也许是由于缺乏复制语义,许多STL操作或算法不能用于容器的unique_ptr?

btw, i just search on unique_ptr. It does not seem to support copy semantics. So isn't it only safe than auto_ptr to be used in STL, but maybe due to lack to copy semantics, many STL operation or algorithm can not be used on container of unique_ptr?

推荐答案

最明显的解决方案是使用:

The most obvious solution would be to use std::unique_ptr:

class IBase {};
class Derived : virtual public IBase {};
std::vector<std::unique_ptr<IBase>> v;
v.push_back(std::unique_ptr<IBase>(new Derived()));

您可以使用,但它的所有权语义显着改变程序的行为,保持动态分配的对象活着,直到没有人持有对它们的引用。

You could use std::shared_ptr, but it's ownership semantics significantly change the program's behaviour, keeping the dynamically allocated objects alive alive until nobody holds references to them.

这篇关于存储基础和派生对象混合的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:08