开发者

C++ functions taking values, where they should be taking references

I'm just learning c++, and coming from c, some function calls I'm seeing in the book confuse me:

char a;
cin.get(a);

In C, t开发者_高级运维his couldn't possibly work, if you did that, there would be no way to get the output, because you are passing by value, and not by reference, why does this work in c++? Is referencing and dereferncing made implicit (the compiler knows that cin.get needs a pointer, so it is referenced)?


C++

This would work in C++ because the function signature for get() is probably this:

void get(char& a); // pass-by-reference

The & symbol after char denotes to the compiler than when you pass in a char value, it should pass in a reference to the char rather than making a copy of it.

What this essentially means is that any changes made within get() will be reflected in the value of a outside the method.

If the function signature for get() was this:

void get(char a); // pass-by-value

then a would be passed by value, which means a copy of a is made before being passed into the method as a parameter. Any changes to a would then only be local the method, and lost when the method returns.

C

The reason why this wouldn't work in C is because C only has pass-by-value. The only way to emulate pass-by-reference behaviour in C is to pass its pointer by value, and then de-reference the pointer value (thus accessing the same memory location) when modifying the value within the method:

void get(char* a)
{
    *a = 'g';
}

int main(int argc, char* argv[])
{
    char a = 'f';
    get(&a);
    printf("%c\n", a);

    return 0;
}

Running this program will output:

g


Reference types work like that (pass by reference, instead of passing by value). It is similar to passing a pointer (pass by pointer) in C, but with a nicer syntax and more safety (compile-time checks). The implementation passes by pointer internally.


C++ allows pass by reference (note the &, which signifies that a reference is used):

void foo(char& bar) {
    bar = 42;
}

int main() {
    char a;
    foo(a);
    // a == 42 here
}


This is why some C++ programmers don't like to use references like that.
It looks like a function arguement - you have no clue from the syntax whether 'a' is modified or not.

Prefer passing const references (when you have a large object and a copy would be expensive) and returning references or best of all passing pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜