kalc
kalc

Reputation: 56

Is it legal to pass the address of a temporary to a function with a pointer argument

Is it legal to pass the address of a temporary object to a function that takes a pointer. If not, where in the standard does it say this is UB. Specifically, I would like confirmation that the following code is legal and doesn't contain undefined behavior:

#include <memory>
template <class T>
inline const T* unsafe_addressof(const T&& x) {
    return std::addressof(x);
}

struct S {};

// NOTE: p only used until f returns.
void f(const S* p);

int main() {
    f(unsafe_addressof(S{}));
    return 0;
}

Upvotes: 0

Views: 174

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

Yes, and you don't even have to make it const.

template <class T>
inline std::remove_reference_t<T>* unsafe_addressof(T&& x) {
    return std::addressof(x);
}

struct S {};

// NOTE: p only used until f returns.
void f(const S* p);

int main() {
    f(unsafe_addressof(S{}));
    return 0;
}

Now unsafe_addressof will return a pointer-to-array, pointer-to-temporary, pointer-to-lvalue, or whatever else you try to get it to return a pointer to.

The lifetime of that pointer's validity is the lifetime of the thing pointed to, be it a temporary instantiated out of a prvalue, an xvalue, or an lvalue.

Upvotes: 2

Related Questions