当显式初始化std :: optional时,我应该使用nullopt吗? [英] When explicitly initializing std::optional's, should I use nullopt?

查看:238
本文介绍了当显式初始化std :: optional时,我应该使用nullopt吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以像这样将std::optional<T>初始化为脱离状态:

An std::optional<T> can be initialized to the disengaged state like so:

std::optional<int> oi { nullopt };

但也是如此:

std::optional<int> oi { };

,以及类似的分配(oi = {}oi = nullopt).

and similarly for assignment (oi = {} or oi = nullopt).

除了个人喜好/审美外,这两者之间是否应该有区别?还是根本没有关系?

Other than personal preference / sense of aesthetics, is there a difference between these which should make me prefer one over the other? Or does it not matter at all?

注意:我要问的是我想显式初始化可选而不是默认初始化的情况(例如,为了强调).

Note: I'm asking about cases where I want to explicitly initialize the optional, rather than default-initialize it (e.g. for emphasis).

推荐答案

它们都具有相同的效果-我希望使用最简单的形式(KISS),但它是主观的,选择一个并保持一致.您可能还希望与如何对待代码中的其他对象保持一致,通常是否依赖默认初始化(例如int i{}int i{0})?

They both have the same effect - I would prefer the simplest form (KISS), but it is subjective, pick one and be consistent. You may also wish to be consistent with how you treat other objects in your code, do you normally rely on default initialization (e.g. int i{} vs int i{0})?

就我个人而言,当我看到多余的代码时,例如将对象显式地初始化为其默认值,它确实使我对作者的信心稍有下降-作者真的了解他在做什么,并试图变得更加安全/显式吗? /可读,还是他只是懒得阅读文档?这使我感到奇怪,作者是否理解写std::vector<std::optional> v(n)或更复杂的示例时会发生什么?如果以书面形式做出决定的书面决定,那一切都很好,我可以理解需要提高可读性.

Personally when I see redundant code, like initalizing an object to its default value explicitly, it does reduce my confidence in the author by a slight margin - does the author really understand what he is doing and trying to be extra safe / explicit / readable, or was he simply too lazy to read the documentation? It makes me wonder, does the author understand what happens when he writes std::vector<std::optional> v(n), or more complex examples? If this is a documented decision, in a coding style, then all is fine, I can understand the need to improve readability.

这篇关于当显式初始化std :: optional时,我应该使用nullopt吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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