string const&和const string&有什么区别吗?
例如
#include <iostream>
using namespace std;
int main()
{
string b = "test";
const string &a = b;
string const &c = b;
return 0;
}
怪我咯2017-04-17 14:01:00
There is no difference.
Let’s start with the variable declaration method in C/C++. The simplest declaration method of
is like int a
, indicating that declares a variable a, and makes a be of type int
Then according to the above statement, the declaration of int *a
indicates that A variable *a is declared, and *a is of type int
We already know that (*a) is of type int, and the asterisk is the dereference operator, (*a) indicates that the variable a points to The data of the memory address. From this sense, we infer that the type of a is the pointer type of int.
The type of a is an int pointer, so how do we express it? Considering that the common declaration method in C is 类型名+变量名
, in the declaration int*a
, since a is 变量名
, so int* is 类型名
, so we use int*
to represent the int pointer type
In the same way, int &a
can be considered as declaring a variable of type int (&a). Through the meaning of the & operator, we know that a is an int reference type, and use int& to represent the int reference type
Back to the topic, string const &a
declares a (&a), (&a) is of string type and is a constant
and const string &a
declares a (&a), (&a) is a constant and of type string
This obviously means the same thing~
Going a little further, let’s look at the analysis questions used to trick children. The former of const char *a
and char * const a
declares that (*a) and (*a) are of const char type. a is modified by a dereference operator, so a is an ordinary pointer and can be modified, but the data pointed to by a (i.e. *a) cannot be modified due to the const modification
The latter declares (*const a), ( *const a) is of type char. a is modified by a dereference operator and a const keyword, so a is an unmodifiable pointer, but the data pointed to by a (i.e. *a) can be modified
char const *a
and const char *a
have the same meaning, and if neither a is allowed to be modified nor the data pointed to by a is allowed to be modified, then it needs to be declared as const char * const a