What's the semantically accurate position for the ampersand in C++ references

两盒软妹~` 提交于 2020-04-08 09:05:08

问题


It's pretty common knowledge that the semantically accurate way to declare pointers is

int *x;

instead of

int* x;

This is because C sees *x as an int, not x as an int pointer.

This can be easily demonstrated by

int* a, b;

where a is an int pointer, while b is an int.

There are at least 5 duplicate questions on stackoverflow.com that discuss this issue for pointers. But what about references?


回答1:


Bjarne Stroustrup says:

A typical C programmer writes int *p; and explains it *p is what is the int emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A typical C++ programmer writes int* p; and explains it p is a pointer to an int emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

When declaring a pointer variable or argument, you may place the asterisk (or ampersand) adjacent to either the type or to the variable name.

The most important thing is to do this consistently within a single file.

// These are fine, space preceding.
char *c;
const int &i;

// These are fine, space following.
char* c;
const int& i;



回答2:


While researching for this question, I already found the answer:

The & needs to be written just like the *.

The demonstration code is similar to the pointer demonstration code:

int main() {
    int a = 0;
    int b = 1;

    int& ar = a, br = b;

    br = 2;

    return b;
}

This returns 1, which means that ar is an int reference, while br is just an integer.




回答3:


Thanks to "template typedefs", you can declare multiple references in an (arguably) nicer way:

template<typename T> using ref = T&;
int a, b;
ref<int> ar = a, br = b;


来源:https://stackoverflow.com/questions/22766907/whats-the-semantically-accurate-position-for-the-ampersand-in-c-references

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!