Why is taking the address of a temporary illegal?

前端 未结 7 1849
无人及你
无人及你 2020-12-03 08:24

I know that the code written below is illegal

void doSomething(std::string *s){}
int main()
{
     doSomething(&std::string(\"Hello World\"));
     retur         


        
相关标签:
7条回答
  • 2020-12-03 08:52

    Why is taking the address of a temporary illegal?

    The scope of temporary variables are limited to some particular method or some block, as soon as the method call returns the temporary variables are removed from the memory, so if we return the address of a variable which no longer exists in the memory it does not make sense. Still the address is valid but that address may now contain some garbage value.

    0 讨论(0)
提交回复
热议问题