使用 [] 运算符时"binding reference of type discards qualifiers"
"binding reference of type discards qualifiers" when using [] operator
我在C++应用程序中使用C样式数组(需要与C代码接口(,但在数组上使用[]运算符时,我会得到"类型丢弃限定符的绑定引用"。这里有一个小例子:
#include <iostream>
struct outer_struct {
struct {
int i;
} array[1];
} temp_struct;
typedef decltype( static_cast<outer_struct*>(nullptr)->array[0] ) typed;
void do_something_2(const typed &thing)
{
std::cout << thing.i << std::endl;
}
void do_something_1(const outer_struct &thing)
{
// error: binding reference of type ‘outer_struct::<unnamed struct>&’ to
// ‘const outer_struct::<unnamed struct>’ discards qualifiers
do_something_2(thing.array[0]);
}
int main()
{
temp_struct.array[0].i = 2;
do_something_1(temp_struct);
return 0;
}
我本以为在const引用上使用[]运算符会返回const引用,但从编译器输出来看,情况似乎并非如此。将do_something_1的签名更改为
void do_something_1(outer_struct &thing)
解决了错误。我通常对const正确性没有问题,但老实说,我不明白我在这里做错了什么。感谢您的帮助。
我使用g++7.3.0。我也尝试过GCC的旧版本。
您需要删除decltype返回的额外引用(因为内置下标运算符的结果是引用(:
using
inner_struct = ::std::remove_reference_t<decltype(::std::declval<outer_struct &>().array[0])>;
在线编译器
相关文章:
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 模板类和'invalid use of incomplete type'错误
- 如何修复" State Error (active) E0513 a value of type "const wchar_t *" cannot be assigned to an entity o
- "invalid use of incomplete type" .解决循环依赖关系
- 我用C++做了一个计算器,但我对"type of calculator"的要求循环了两次。有人可以帮助指出我的错误吗?
- 如何修复此"argument of type incompatible with parameter"错误?
- 在 c++ 中,如果包含标头,为什么我会收到'does not a name of type'错误?
- 让编译器告诉哪些方法不具体,而不是错误'invalid new-expression of abstract class type'
- "base operand of ‘->’ has non-pointer type" 但它是指针
- "a value of type " void (exeCallback::*)(int) " cannot be assigned to an entity of type " void (*)(
- "Allocating an object of abstract class type"错误,尽管所有函数都有实现
- C++错误:" 'class' does not name a type"和"invalid use of incomplete type ‘struct ...' "
- 另一个"invalid initialization of reference of type"错误
- "invalid initialization of non-const reference of type..." 克隆() 函数错误
- 禁用杂散"warning: left shift count >= width of type"
- C++:"invalid initialization of non-const reference of type ‘List&’ from a temporary of type ‘List*’"
- prvalue of type std::nullptr_t
- 获取"terminating with uncaught exception of type std::length_error: vector"错误C++
- 如何调试提升元组错误"no operator found which takes a left-hand operand of type"