Is the return value of a function a temporary object?

Bernard 1 Reputation point
2021-05-15T21:54:23.93+00:00

Why does the code below compile and run w/o error? Isn't the return value of goobar() a temporary object? Why would the compiler C++20 permit a reference to it?

#include <iostream>

using namespace std;

struct cfoobar
{
    const int& x;
    cfoobar(const int&y) : x(y) { }
};

int goobar(int x)
{
    int y = x;
    return y;
}

int main()
{
    cfoobar a(goobar(159));
    cout << a.x<< endl;
}

The output is 159 just as I would not expect. Thank you kindly - cheerio

Developer technologies | C++
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Igor Tandetnik 1,116 Reputation points
    2021-05-15T23:39:22.317+00:00

    This program exhibits undefined behavior, by way of accessing an object after its lifetime has ended. "Seems to work" is one possible manifestation of undefined behavior.

    Yes, goobar returns a temporary. A const reference can bind to a temporary; there's nothing wrong in passing a temporary int to a function taking const int&. The problem starts when you take that temporary and store it in a data member - at that point, you make an assumption that the referred-to object will outlive the cfoobar instance. In the example, this assumption doesn't hold - the referred-to int object is destroyed soon after the constructor returns, a.x becomes a dangling reference, and an attempt to use it exhibits undefined behavior.


  2. Code Wanderer 396 Reputation points
    2021-05-16T13:29:03.697+00:00

    The another explanation can be, that 159 is exist while it is holded by some reference. Explanation: 159 is created and added into reference and you copy reference to another. In your scenario, the reference is temporary, not a 159 itself. But I am not sure if I am right.

    0 comments No comments

  3. Sam of Simple Samples 5,546 Reputation points
    2021-05-16T23:08:19.147+00:00

    Originating in the days of mathematical functions before use of functions for computers the purpose of a function is to make a calculation and then provide the result of that calculation for use in further calculations. goobar returns an int; if calling cfoobar a(goobar(159)) was not the same as cfoobar a(159) then functions would be useless. Returning class objects deviates from mathematical functions but for an int it seems impossible that the standard would not require that the function return value be usable as an expression.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.