与std :: shared_ptr和std :: unique_ptr相比,std :: optional有什么优势? [英] What's the advantage of `std::optional` over `std::shared_ptr` and `std::unique_ptr`?
问题描述
std::optional
的理由是言而明达,它可能或可能不包含值.因此,如果我们不需要它,则可以省去构造一个可能很大的对象的工作.
The reasoning of std::optional
is made by saying that it may or may not contain a value. Hence, it saves us the effort of constructing a, probably, big object, if we don't need it.
例如,这里的工厂,不会在某些情况下构造对象条件不满足:
For example, a factory here, will not construt the object if some condition is not met:
#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
}
但是,这与此有何不同?
But then how is this different from this:
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::shared_ptr
来添加std::optional
,我们能赢得什么?
What is it that we win by adding std::optional
over just using std::shared_ptr
in general?
推荐答案
通过添加std :: optional而不是仅使用std :: shared_ptr来赢得什么呢?
What is it that we win by adding std::optional over just using std::shared_ptr in general?
比方说,您需要从带有标志"not a value"的函数返回符号.如果您将std::shared_ptr
用于此用途,则会产生巨大的开销-char
将分配到动态内存中,而std::shared_ptr
将保留控制块.而另一边 std :: optional :
Let's say you need to return a symbol from a function with flag "not a value". If you would use std::shared_ptr
for that you would have huge overhead - char
would be allocated in dynamic memory, plus std::shared_ptr
would maintain control block. While std::optional on another side:
如果可选包含值,则保证该值为 分配为可选对象足迹的一部分,即无动态 内存分配曾经发生过.因此,可选对象对 对象,而不是指针,即使operator *()和operator->() 被定义.
If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though the operator*() and operator->() are defined.
因此不涉及动态内存分配,即使与原始指针相比,差异也很明显.
so no dynamic memory allocation is involved an difference comparing even to the raw pointer could be significant.
这篇关于与std :: shared_ptr和std :: unique_ptr相比,std :: optional有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!