I expect following code to fail (in main
function), but it works:
class Response {
public:
Response() {}
void displayInfo() {
cout << "Hello!" << endl;
}
};
class HttpClient
{
public:
HttpClient(Response& response) : m_response(&response) {
m_response = &response;
}
Response* getResponse() {
return m_response;
}
private:
Response *m_response;
};
HttpClient* createClient()
{
Response response;
HttpClient *clnt = new HttpClient(response);
clnt->getResponse()->displayInfo();
return clnt;
}
int main()
{
HttpClient* client = createClient();
// ------------------------------------------
// I expect getResponse()->displayInfo() to fail, since "response" object
// passed as argument to HttpClient (in createClient function) goes out of the scope and should be deleted.
client->getResponse()->displayInfo();
}
So I've created local variable response
in the createClient
function.
Then this local variable is passed as constructor argument (reference) to HttpClient.
This argument is assigned to the member Response *m_response
.
So as I understand, m_response
holds reference to response
local variable.
But when response
local variable goes out of the scope, I still can access to it via m_response
(call method of m_response
object).
I expect that m_response
should refer to some garbage since response
went out of the scope.
Why does it work?