我对这两者感到困惑。我知道C++的引用本质上是不变的,一旦设置,它们就不能被改变来引用别的东西。“const int&jj”和“int&const jj”有什么区别?
6
A
回答
9
const int&
表示参考常量int
。 (类似地,int&
意味着参照非const int
。)
int& const
字面意思const引用(到非const int
),这是在C++中无效,因为参考本身不能是常量限定。
$8.3.2/1 References [dcl.ref]是形成不良的,当cv修饰符 通过使用一个typedef名的介绍除了
CV-合格的引用([dcl.typedef], [temp.param])或decltype-specifier([dcl.type.simple]),在这种情况下,cv-qualifiers将被忽略。
正如你所说,引用本质上是恒定的,一旦设置,它们就不能被改变来引用别的东西。 (我们不能在初始化后重新引用引用。)这意味着引用总是“const”,那么const限定的引用或者const-unqualified引用实际上可能没有意义。
3
const
将限定符应用于引用意味着您无法更改引用的值。例如:
void foo(int& arg) {
arg = 1; // OK. The value passed by a caller will be changed in-place.
}
void foo(const int& arg) {
arg = 1; // Compilation error.
}
int& const jj
是一个编译错误。
3
差异:
const int& jj// means a reference to const int.
int& const jj // ill formed code that should trigger a compiler error
相关问题
- 1. 为什么const int比const int&更快?
- 2. int const函数(参数),int函数(const参数)和int函数(参数)const之间的区别是什么?
- 3. const int&x = 4和const int x = 4之间的区别
- 4. const int&value = 12和const int value = 12之间的区别;
- 5. static const和const有什么区别?
- 6. 关于“int const * p”和“const int * p”
- 7. C++中的“const int”和“int”是否有区别?
- 8. “int * const const * b”是什么意思?
- 9. “Int”和“const int的”在C++
- 10. static const char * const和static const char []之间有什么区别?
- 11. 传递(int x)和(const int x)之间的区别
- 12. 函数参数的区别在C++中为(const int&)和(int&a)
- 13. 返回值之间的区别int&和const int&
- 14. int [] x;有什么区别?和int x [];?
- 15. 使用int [] []和int [,]有什么区别?
- 16. int(1)和int(8)有什么区别?
- 17. void(int)和void(*)(int)有什么区别?
- 18. 第二个const在“const int const&someval”中做什么?
- 19. 不允许在类型“const int ** const”和“int **”之间初始化,为什么?
- 20. var和const有什么区别?
- 21. T&和T * const有什么区别?
- 22. const int *&vs typedef int * IntPtr
- 23. 返回const int的*和回访const int的*参考
- 24. 为什么{typedef int * PTR; const PTR p = #}不等于“const int * p = num”而是等于“int * const p = num”?
- 25. “int * a = new int”和“int * a = new int()”有什么区别?
- 26. swap(int&a,int&b)和swap(int * a,int * b)。有什么区别?
- 27. int * const a = int const * b,对于obj(obj * const a = obj const * b)是否为true?
- 28. (const char * str),(char const * str)和(char * const str)之间有什么区别?
- 29. 转换** const int的**
- 30. 分配const int的*
请问你的编译器接受第二个变种? – juanchopanza
请指定哪个编译器接受第二个变体。 – Angew
@HumamHelfawi这根本不是重复的。这个问题涉及'const int&'和'int const&',它们都是有效的(和等价的)形式。这个处理'const int&'和语法错误'int&const'。 – Angew