1
#include<iostream>

struct Test
{
    int n ;
    ~Test(){}

    Test& operator =(int v)
    {
        n=v;
        return *this;
    }
};

Test * ptr = nullptr;

void g(Test && p)
{
    std::cout << "&&";
}


void g(Test & p)
{
    ptr = &p;
    std::cout << "&";
}

void f(Test&& t)
{
    g(t);
}

void buggy()
{
    *ptr  = 5;
}

int main()
{ 
    f(Test());
    buggy();
    std::cin.ignore(); 
} 

Just to be sure, the above code lead to an undefined behavior as we keep address of a tempory ?

Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145

2 Answers2

2

Declaring pointer to struct Test* ptr; or "keeping address" as you call it doesn't lead to an undefined behaviour. Using pointers to objects whose lifetime has ended does.

Lifetime of the object created by Test() in main ends right after f(Test()); is executed. After that, whatever you do by using ptr is undefined. This object most likely stays in the memory even after its lifetime has ended, but you shouldn't rely on it.

You should also check out: What are all the common undefined behaviours that a C++ programmer should know about?

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
1

Yes, the temporary Test() is allocated on the stack, you take a pointer to it and it's destructor is called after returning. After that, the value of the pointer is still valid, but it points to "undefined" memory so all bets are off on dereferencing the pointer.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294