kiki kiki - 1 year ago 54
C++ Question

double& (not passing by reference) C++

typedef double real8;

typedef real8 Real_t;

Real_t& x(int y);

What is
?? I've only seen a datatype followed by "&" to indicate pass by reference.
But this is in declaration line. What does this mean ?

Answer Source

This means that the function returns a reference to a Real_t which is actually a double. The Real_t is a real8 which is a double if you resolve all the typedefs.

You should be careful here. If the result being passed by reference isn't retrieved from a scope that exists pasts the end of the function, then you'll have a dangling reference.

For example:

int& foo() {
    int x = 8;
    return x;

int main() {
    int y = foo();

The variable, y, in main ends up referring to a variable which has been destroyed as it went out of scope when foo() returned, so using it is undefined behavior. If x had been retrieved from a singleton or something that lives outside the scope of the function foo(), then it would still exist though and this would be fine.

People sometimes return references to initialize static globals in a deterministic way between compilation units, so you might see this used with statics like:

MyClass& MyStaticVar() {
    static MyClass instance;
    return instance;

Which is also okay, because the static lives for the duration of the program after initialized.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download