在向量中存储对象

发布于 2024-09-17 18:11:10 字数 234 浏览 6 评论 0原文

是否可以拥有一个向量而不对其进行专门化?

我的问题是:我有一个抽象类 N4GestureRecognizer 以及它的几个子类。 因此,在 Controller 类中,我想要一个 vector。 recognizers_ 但由于它是抽象的,我不能。 如何将此识别器存储在向量、集合、列表或标准 C++ 中可循环的任何内容中?

Is it possible to have a vector without specializing it?

My problem is: I have an abstract class N4GestureRecognizer
and a couple of subclasses of it.
So in a Controller class I want to have a vector<N4GestureRecognizer> recognizers_ but since it is abstract I cannot.
How can I store this recognizers in a vector or collection or list or whatever is loop-able in standard c++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梅窗月明清似水 2024-09-24 18:11:10

将它们存储为指针。纯指针或一些智能指针类。

额外
实际上,即使该类不是抽象类,而是子类并且子类旨在在向量中使用,指针也是唯一的方法。原因:std::vector 为每个元素分配 sizeof(T) 字节,但 sizeof(drivenFromT) 可能大于 sizeof(T)。您将能够将子对象推入向量中,但这可能会在运行时导致不可预测的问题。

当然,管理指针向量是一件痛苦的事,但据我所知,boost 包含一些智能指针来简化任务。

Store them as pointers. Either pure pointers or some smart pointer class.

EXTRA
Actually, pointers are the only way even if the class is not abstracts, but is subclassed and child classes are intended to be used in the vector. Why: std::vector allocates sizeof(T) bytes for each element, but sizeof(derivedFromT) could be bigger than sizeof(T). You will be able to push a child object into the vector, but it can cause unpredictable issues at run time.

Managing vectors of pointers is a pain, of course, but as far as I remember, boost contains some smart pointers to simplify the task.

魂牵梦绕锁你心扉 2024-09-24 18:11:10

你需要的是一个 std::vector< std::shared_ptr>

如果您的 std lib 没有附带 std::shared_ptr (它是下一个 C++ 标准的一部分,预计明年发布),它可能会附带 std::tr1::shared_ptr code>,这是相同的(作为官方技术报告 1 对当前 C++ 标准的补充)。如果这也失败了,总是有 boost,它有 boost:shared_ptr (这是std::tr1::shared_ptrstd::shared_ptr 的前身)。

注意:不要使用裸指针 (std::vector)。几乎没有办法保证它不泄漏。

What you need is a std::vector< std::shared_ptr<N4GestureRecognizer> >.

If your std lib comes without std::shared_ptr (it's part of the next C++ standard, expected to be published next year), it might come with std::tr1::shared_ptr, which is the same (as a addition to the current C++ standard by the official Technical Report 1). If that also fails, there's always boost, which has boost:shared_ptr (which is the predecessor of std::tr1::shared_ptr and std::shared_ptr).

Note: Don't use naked pointers (std::vector<N4GestureRecognizer*>). There's almost no way to make this safe so that it doesn't leak.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文