从学术角度来看,如果我想将 std::nullopt 作为非常量引用返回。我将如何做同样的事情。
一点背景知识,今天当我在处理返回 std::optional> 引用的代码时,但我忘记将返回值设为常量,我得到了错误。
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;
}