Dar*_*row -1 c++ std c++17 stdoptional
如果我想返回std :: nullopt作为非恒定引用,请形成学术观点。我将如何做同样的事情。
没什么背景,今天当我在处理返回std :: optional>引用的代码时,却忘记了使返回常量,并得到了错误。
Run Code Online (Sandbox Code Playgroud)Error (active) E0434 a reference of type "std::optional<std::vector<std::any, std::allocator<std::any>>> &" (not const-qualified) cannot be initialized with a value of type "const std::nullopt_t" Socket.IO D:\Hardware\Windows\Visual Studio\Socket.IO\Socket.IO\main.cpp 46 Error C2440 'return': cannot convert from 'const std::nullopt_t' to 'std::optional<std::vector<std::any,std::allocator<_Ty>>> &' Socket.IO d:\hardware\windows\visual studio\socket.io\socket.io\main.cpp 46
只是想知道是否有人想使用std :: optional返回一个非常量引用,他将如何做。
使用平台:Windows 10 Pro x64
开发环境:Visual Studios 15.9.9
std::vector<int>> a;
std::optional<std::vector<int>>& test(int b)
{
a.clear();
a.push_back(b);
if(b)
return a;
else
return std::nullopt;
}
Run Code Online (Sandbox Code Playgroud)
std::nullopt不是std::optional<std::vector<int>>(也不是a),而是一个对该类型进行隐式转换的对象。
您不能将非常量引用绑定到临时文件,例如转换结果。
我不确定您是否应该返回对可选的引用,而是“可选的引用”。std::optional<std::vector<int> &>是不是有效的类型,但都std::vector<int> *和std::optional<std::reference_wrapper<std::vector<int>>>都和他们模式“可选参考”。