是否可以从多态指针容器中返回“准确"对象? [英] Is it possible to return an 'accurate' object from a polymorphic container of pointers?

查看:98
本文介绍了是否可以从多态指针容器中返回“准确"对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,每当我们想要多态时,我们都需要指针或引用,因为将Derived实例存储在Base变量切片"中,而不包含基础"中未定义的任何内容.

I found out that whenever we want polymorphism, we need pointers or references, because storing a Derived instance in a Base variable 'slices' off anything that isn't defined in 'Base'.

(我想那是因为DerivedBase实例不一定占用内存中的相同空间.对吗?)

(I suppose that's because Derived and Base instances don't necessarily occupy the same space in memory. Is that correct?)

因此,当我们想要一个容纳所有对象的容器时,这些对象都是从Base的子类派生的,我们需要一个指针容器而不是一个实际对象容器.

So when we want a container that holds all kinds of objects, all derived from subclasses of Base, we need a container of pointers and not a container of actual objects.

如果我们想要一个函数来从该容器中获取一个对象并按原样"返回(未切片),则可以执行以下操作:

And if we want a function that gets an object from this container and returns it 'as it is' (not sliced), we can do this:

Base* get_pointer(int index) {
   return container[index];
}

但是请说我想做以下事情:

But say I want to do the following:

Base get_object(int index) {
   return *container[index];
}

即:返回一个真实的对象,而不是一个指针.这可能吗?还是当我想要任何一种多态性时,我应该只使用指针进行管理吗?

I.e.: return a real object, not a pointer. Is this possible? Or should I simply always manage with pointers when I want any kind of polymorphism?

推荐答案

我知道,只要我们想要多态,就需要指针或引用[...]正确吗?

I know that whenever we want polymorphism, we need pointers or references [...] Is that correct?

那是完全正确的.但是,您不仅限于该语言中内置的普通"指针.智能指针(例如std::unique_ptr<T>std::shared_ptr<T>)提供了更好的替代方法,可让您保留多态行为.

That is absolutely correct. However, you are not limited to "plain" pointers built into the language. Smart pointers, such as std::unique_ptr<T> and std::shared_ptr<T> present a better alternative that lets you preserve polymorphic behavior.

[我想]返回一个真实的对象,而不是一个指针.这可能吗?

[I want to] return a real object, not a pointer. Is this possible?

您可以执行此操作,但是切片将返回. Base将按值返回,因此结果将不包含派生的功能.当您按值传递或返回时,总是会发生这种情况(传递和返回是同一件事的两个方面,因此两种情况下的基本作用机理都是相同的.)

You can do that, but the slicing would be back. The Base will be returned by value, so the result would be stripped of the derived functionality. This always happens when you pass or return by value (passing and returning are two sides of the same thing, so the basic mechanism in play is the same in both cases).

但是,如果通过引用返回Base&,则在调用方中将获得相同的语法,并且对象将不会被切片:

If you return Base& by reference, however, you would get the same syntax in the caller, and your objects would not get sliced:

Base& get_object(int index) {
   return *container[index];
}

唯一的陷阱是,当您的代码持有对它的引用时,容器中的项目必须保留在原处.

The only catch is that the item in the container must remain in place while your code is holding a reference to it.

这篇关于是否可以从多态指针容器中返回“准确"对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆