Can I have polymorphic containers with value semantics in C++?(我可以在 C++ 中拥有具有值语义的多态容器吗?)
问题描述
作为一般规则,我更喜欢在 C++ 中使用值而不是指针语义(即使用 vector
而不是 vector
).通常性能上的轻微损失可以通过不必记住删除动态分配的对象来弥补.
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector<Class>
instead of vector<Class*>
). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.
不幸的是,当您想要存储从公共基础派生的各种对象类型时,值集合不起作用.请参阅下面的示例.
Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
我的问题是:我可以拥有我的蛋糕(价值语义)并吃掉它(多态容器)吗?还是我必须使用指针?
My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
推荐答案
由于不同类的对象会有不同的大小,如果将它们存储为值,最终会遇到切片问题.
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values.
一种合理的解决方案是存储容器安全的智能指针.我通常使用 boost::shared_ptr ,它可以安全地存储在容器中.请注意 std::auto_ptr 不是.
One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not.
vector<shared_ptr<Parent>> vec;
vec.push_back(shared_ptr<Parent>(new Child()));
shared_ptr 使用引用计数,因此在删除所有引用之前它不会删除底层实例.
shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
这篇关于我可以在 C++ 中拥有具有值语义的多态容器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 C++ 中拥有具有值语义的多态容器吗?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01