简体   繁体   中英

double& (not passing by reference) C++

typedef double real8;

typedef real8 Real_t;

Real_t& x(int y);

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

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.

It means x is a function that returns a reference to a Real_t .

An example of returning by reference is for data access in classes. For example, std::vector::at() returns a reference to an element of the vector.

For a free function to safely return a reference, there must be something non-obvious going on inside the function to ensure that a dangling reference isn't returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM