Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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!)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading