Igor R.
Igor R.

Reputation: 15075

Reference to a member of temporary

Consider the following code:

#include <vector>

struct temp {
    int& get() { return i; }
    int i = 1;
};

int main() {
    std::vector<int> v;
    v.push_back(temp{}.get());
}

Is the above well-formed code or UB?

My doubts are about the reference returned from get(), which becomes dangling at the last semicolon. But at this point push_back is already evaluated, so it's ok, isn't it?

Upvotes: 2

Views: 51

Answers (1)

NathanOliver
NathanOliver

Reputation: 180500

Temporaries live to the end of the full expression. In this case, that means after push_pack has returned. Since push_back makes a copy of the value get refers to, there is no dangling reference and everything will work as expected.

Upvotes: 3

Related Questions