存储基础对象和派生对象的混合物的容器
Container that stores a mixture of base and derived objects?
什么是正确的做法?我知道,如果容器是基类值类型,那么存储的派生对象是"切片"的。若容器是派生类类型,则不能存储基类对象。正确的
如果使用指针,则不能使用auto_ptr,因为它存在复制语义问题。shared_ptr是处理这个问题的唯一解决方案吗?
有人能提供更多的细节、示例代码或在线文章来解决这个问题吗?这应该是一个很常见的问题,但我并没有在课本或网上找到太多关于它的信息。
提前谢谢。
顺便说一句,我只是在unique_ptr上搜索。它似乎不支持复制语义。那么,在STL中使用auto_ptr不是唯一安全的吗?但可能由于缺乏复制语义,许多STL操作或算法无法在unique_ptr的容器上使用?
如果您想要多态行为(并且确实想要),则必须使用指针或引用。这在许多地方都有很好的记录。
由于不能使用引用的容器,所以必须使用指针的容器。
现在,您可以使用您认为合适的任何类型的指针:unique_ptr
、shared_ptr
或原始指针。
最明显的解决方案是使用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()));
您可以使用std::shared_ptr,但它的所有权语义会显著改变程序的行为,使动态分配的对象保持活动状态,直到没有人拥有对它们的引用。
有一个std::vector和std::shared_ptr的例子。我想这就是你想要的。
#include <iostream>
#include <memory>
#include <vector>
class Base {
public:
virtual void foo() {
std::cout << "base" << std::endl;
}
};
class Derived : public Base {
void foo() {
std::cout << "derived" << std::endl;
}
};
int main()
{
std::vector<std::shared_ptr<Base> > v;
v.push_back(std::shared_ptr<Base>(new Base));
v.push_back(std::shared_ptr<Base>(new Derived));
for (auto it : v) {
it->foo();
}
}
[http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_container.html](Boost指针容器库)正是为此而设计的。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 存储基础对象和派生对象的混合物的容器