简体   繁体   中英

Return std::nullopt as a non-constant reference

Form academic point of view, if I wanted to return std::nullopt as a non-constant reference. How will I be doing the same.

Little background, today when I was working on a code returning an std::optional> reference but I forgot to make the return constant and I got the error.

 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 

Just wanted to know if someone wanted to return an non-constant reference using std::optional how would he be doing so.

Platform Used : Windows 10 Pro x64

Development Environment : 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;
}

std::nullopt is not a std::optional<std::vector<int>> (nor is a ), it is an object that has an implicit conversion to that type.

You can't bind a non-const reference to a temporary, such as the result of a conversion.

I'm not sure you should be returning a reference to an optional, but rather an "optional reference". std::optional<std::vector<int> &> is not a valid type, but both std::vector<int> * and std::optional<std::reference_wrapper<std::vector<int>>> are, and they model "optional reference".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM