Automatic Variables Passed to an Asynchronous Function

Hi,

If I have a function that defines a local variable of automatic storage called newPlayer and I pass it to an asynchronous function that executes a callback called handleConnection which takes newPlayer by reference, is handleConnection's reference to newPlayer valid?

Example:

1
2
3
4
5
6
7
8
void Server::pollForConnection()
{
	Player newPlayer; // Automatic storage
	std::cout << "first time " << &newPlayer << std::endl; // outputs 0x7ffeec569f50
	acceptor.async_accept(newConnection->getSocket(), boost::bind(&Server::handleConnection, this, newPlayer, newConnection,
		boost::asio::placeholders::error));
}

1
2
3
4
5
6
7

void Server::handleConnection(Player& suppliedPlayer, Connection::sharedPointer suppliedConnection, const boost::system::error_code& error)
{
        //....code....
        std::cout << &suppliedPlayer << std::endl; // Outputs 0x7ffeec56a3d8
        //...code....
}


My concern is that by the time handleConnection executes, the reference to newPlayer would be destroyed and thus suppliedPlayer points to invalid memory, but preliminary testing (reading and writing to the object in the two different functions) seem to indicate that it's still a valid object...

... But obviously I don't want to build an application on an incorrect assumption...

So I'm here to confirm :)
Last edited on
As you've correctly guessed, there's no guarantee that the Player instance won't have been destructed by the time Server::handleConnection() is called.
....which means you'll have to create it differently and store it elsewhere
Topic archived. No new replies allowed.