Home > Mobile >  Is it an UB when I try to pass the address of temporary as argument?
Is it an UB when I try to pass the address of temporary as argument?

Time:09-28

For the following C codes:

#include <iostream>
using namespace std;

class A {
public:
  A() { cout << "A()\n"; }
  ~A() { cout << "~A()\n"; }
  A* get() { return this; }  // <------
};

void f(const A * const &a, const A * const &b) {
  cout << "f()\n";
}

int main() {
  // f(&A(), &A()); // error: taking address of temporary
  f(A().get(), A().get());   // <------
  cout << "end\n";
  return 0;
}

And it returns:

A() 
A() 
f() 
~A()
~A()
end 

Of course I can't use &A() here because this leads to an error: error: taking address of temporary.

But it works when I wrapped it in A* get() { return this; }.

So my question is, is it an Undefined Behaviour to use get()?

CodePudding user response:

So my question is, is it an Undefined Behaviour to use get()?

No, it's not undefined behavior. It's valid because the temporary object is first constructed, then the function is called, and then (only after the function returns) is the temporary object destroyed again. So during the lifetime of the function call, you're allowed to do anything you could normally do with the passed-in temporary object, including dereferencing a pointer to it or its contents. (your function shouldn't store the passed-in pointer for later use, though, since it will become a dangling-pointer as soon as the function returns!)

  • Related