如何正确实现一个对象列表的创建(和分配)只有在C ++的抽象基础知道? [英] How to properly implement creation (and allocation) of a list of objects known only by abstract base in C++?
问题描述
我应该将堆栈分配优先于堆分配。 最好通过值(,尤其是如果您要创建新的对象,但同时如果返回基类,则对象将被切片),或至少通过引用而不是传递指针 (虽然您无法创建引用向量) 。
I should prefer stack allocation to heap allocation. It's better to pass by value (especially if you're creating new objects — but at the same time, if you return by base class, your object will be sliced), or at least by reference than passing pointers (although you can't create a vector of references).
我仔细阅读所有这些,现在我觉得我知道的不多,我以前知道。我不知道如何写一个代码,IMO,应该是微不足道,同时尊重所有这些精心编写和思考的答案中提到的最佳做法。
I read all of this carefully, and now I feel that I know less that I knew before. I don't have a slightest idea about how to write a code that, IMO, should be trivial, while respecting the best practices mentioned in all of these well-written and thought-through answers.
这里是我想要实现的。 (我不假装它是正确的C ++,但我只是想传达的想法)。
Here's what I want to implement. (I don't pretend that it's correct C++, but I just want to convey the idea).
// This thing is purely virtual!
class BaseStuff { }
// Has important behaviour and data members that shouldn't be sliced
class SomeStuff : public BaseStuff { }
// Don't slice me plz
class OtherStuff : public BaseStuff { }
BaseStuff CreateStuff()
{
// falls a set of rules to create SomeStuff or OtherStuff instance based on phase of the moon
}
std::vector<BaseStuff> CreateListOfStuff()
{
// calls CreateStuff a lot
}
public static void main()
{
List<BaseStuff> allTheStuff = CreateListOfStuff();
// to things with stuff
}
推荐答案
你将存储多态指针到一个实际指向派生类型的基类(注意我在这里使用 std :: unique_ptr
): p>
You're going to store polymorphic pointers to a base class that actually point to a derived type (note I used std::unique_ptr
s here):
#include <iostream>
#include <memory>
#include <vector>
class Base
{
public:
virtual void shout() = 0;
};
class Child : public Base
{
public:
void shout() { std::cout << "Child!\n"; }
};
class Orphan : public Base
{
public:
void shout() { std::cout << "Orphan!\n"; }
};
int main()
{
std::vector<std::unique_ptr<Base>> the_list;
the_list.reserve(3);
the_list.emplace_back(std::make_unique<Child>());
the_list.emplace_back(std::make_unique<Orphan>());
the_list.emplace_back(std::make_unique<Child>());
for(const auto& item : the_list)
{
item->shout(); // remember, items are (smart) pointers!
}
}
实例。
只能在标准C ++容器中存储一种类型,因此必须在此处存储一个(智能)指针到Base。
Live example. You can only store one type in a Standard C++ container, so you must store a (smart) pointer to Base here.
这篇关于如何正确实现一个对象列表的创建(和分配)只有在C ++的抽象基础知道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!