std :: optional和多态 [英] std::optional and polymorphism

查看:123
本文介绍了std :: optional和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在许多文章中都读过Stack Overflow,它说到使用指针(用于参数或返回值)并且允许使用nullptr(使其成为可选)时,通常最好使用std::optional.

I have read on Stack Overflow in many posts that when pointer is used (for argument or return value) and nullptr is allowed (making it optional), it is generally better to use std::optional instead.

但是如果指针指向多态类型怎么办?最好使用std::optional还是指针?

However what if the pointer refers to polymorphic type? Is it best to use std::optional or a pointer?

推荐答案

optional不适用于多态类型.这是一个值类型,多态基类在optional中不起作用.就像将多态基类放入vector或类似容器中一样.

optional doesn't work with polymorphic types. It's a value type, and polymorphic base classes don't work in an optional. Just as putting polymorphic base classes in vector or similar containers doesn't work.

返回一个指针.建议通常被称为一般"是有原因的.

Return a pointer. There's a reason why the advice is usually stated as "generally".

这篇关于std :: optional和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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