【发布时间】:2017-08-13 06:40:29
【问题描述】:
std::optional 的推理是made by saying 它可能包含也可能不包含值。因此,如果我们不需要它,它就节省了我们构建一个可能是大对象的工作。
For example,这里的工厂,如果不满足某些条件,将不会构造对象:
#include <string>
#include <iostream>
#include <optional>
std::optional<std::string> create(bool b)
{
if(b)
return "Godzilla"; //string is constructed
else
return {}; //no construction of the string required
}
但是这和这个有什么不同:
std::shared_ptr<std::string> create(bool b)
{
if(b)
return std::make_shared<std::string>("Godzilla"); //string is constructed
else
return nullptr; //no construction of the string required
}
我们通过添加std::optional 而不是通常使用std::shared_ptr 赢得了什么?
【问题讨论】:
-
一方面,它更冗长
-
当您只能使用整数时使用枚举和布尔值,或者当您可以转到时使用结构化循环,您可以获得什么?
-
@molbdnilo 我觉得
std::optional太过分了。那时,当我和我的博士导师进行这些激烈的辩论时,他总是说 C 比 C++ 更好,因为你可以从 300 页的书中学习 C。 -
@TheQuantumPhysicist,请问您的博士在哪个领域?)
-
@TheQuantumPhysicist
std::optional不是一种新的语言结构,它只是一种标准库类型,如std::string或std::size_t。 (顺便说一句,我会推荐 Null References: The Billion Dollar Mistake,由发明它们的人 Tony Hoare。)
标签: c++ optional c++17 stdoptional