I'm trying to return a std::optional
to an object containing a std::unique_ptr
member. However, when I try to change the optional
return type to use a reference, I get errors like this:
error: cannot bind non-const lvalue reference of type std::optional<ObjectWithConnection>& to an rvalue of type std::optional<ObjectWithConnection>
Is this the best way to return _aConnection
without encountering any copying/latency across the stack frames?
I use references very often, but I've never used std::optional
with std::unique_ptr
and I'm concerned what it's doing under the hood.
struct ObjectWithConnection
{
std::unique_ptr<Connection> _aConnection;
};
struct ConnectionsContainer
{
// If I change return type to reference, get compiler error
std::optional<ObjectWithConnection> getConnection(const std::string& key)
{
auto iter = _connections.find(key);
if(iter != _connections.end())
{
return std::optional<ObjectWithConnection>(std::move(iter->second));
}
return std::nullopt;
}
std::unordered_map<std::string, ObjectWithConnection> _connections;
}
struct AnotherClass
{
// If I change return type to reference, get compiler error
std::optional<ObjectWithConnection> getConnection(const std::string& key)
{
return _container.getConnection(key);
}
ConnectionsContainer _container;
};
There are no std::optional references. A program is ill-formed if it instantiates an optional with a reference type. Alternatively, an optional of a std::reference_wrapper of type T may be used to hold a reference.