【发布时间】:2018-10-30 19:08:54
【问题描述】:
我在 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。
【问题讨论】:
-
const T&其中T是U&折叠为U&,而不是const U&。 (decltyle 导致引用类型)