Reputation: 93264
The following code is taken straight out of one of my projects. The first version causes a crash (segmentation fault). The second version works as intended.
Aren't the two code snippets equivalent?
This one crashes
auto getUserFromPacket = [&](sf::Packet& mP) -> User&
{
return users.getUser(ssvuj::as<std::string>(getDecompressedPacket(mP), 0));
};
pHandler[FromClient::US_Death] = [&](ClientHandler&, sf::Packet& mP)
{
getUserFromPacket(mP).stats.deaths += 1; // segmentation fault here!
};
This one works
pHandler[FromClient::US_Death] = [&](ClientHandler&, sf::Packet& mP)
{
users.getUser(ssvuj::as<std::string>(getDecompressedPacket(mP), 0)).stats.deaths += 1;
// this works fine
};
Compiler used: clang++ 3.4 - it also couldn't deduce the return type of getUserFromPacket
. users
is an instance of an UserDB
. The function signature is User& UserDB::getUser(const std::string&)
- why does the compiler fail to deduce User&
as the return type?
Upvotes: 1
Views: 703
Reputation: 503805
No, they aren't equivalent. The first one will refer to the lambda, which (likely) will not be in scope by the time it is needed. The second has no such dependency. Always be careful capturing by reference. :)
Upvotes: 2