C++ 错误:“取临时数组的地址" [英] C++ error: "taking address of temporary array"

查看:53
本文介绍了C++ 错误:“取临时数组的地址"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 if 语句中声明一个数组.我以这种方式编写了代码,以便在 if 块退出后对象保持在范围内,但现在我遇到了一个新问题:获取临时数组的地址".我怎样才能以另一种方式重写它,以便为 maskArray 分配正确的值?

I am trying to declare an array inside an if-statement. I wrote my code this way so that the object stays in scope once the if-block exits, but now I have a new issue: "taking address of temporary array". How can I re-write this in an alternative way so that maskArray is assigned the correct values?

int* maskArray;
if(conditional==true)
   maskArray = (int[9]) {0,1,0,1,-4,1,0,1,0};

推荐答案

虽然原始构造在 C++ 中无效,但标准 C++ 确实具有相当相似的特性:可以使用显式类型创建临时数组名称和列表初始化器

While it is true that the original construct is not valid in C++, standard C++ does have a fairly similar feature: one can create a temporary array using an explicit type name and list-initializer

using I9 = int [9];
I9{ 0, 1, 0, 1, -4, 1, 0, 1, 0 };

以上是临时数组对象的有效 C++ 语法.但是如果你尝试在 GCC 中使用它,你会很快发现 GCC 拒绝将数组到指针的转换应用于这种临时数组,例如

The above is valid C++ syntax for a temporary array object. But if you try using it in GCC, you will quickly discover that GCC refuses to apply array-to-pointer conversion to such temporary arrays, e.g.

using C10 = char [10];
C10 str;
std::strcpy(str, C10{ 'a', 'b', 'c' });
// GCC: error: taking address of temporary array

以上是完全有效的 C++,但是 GCC 中的一个错误阻止了它的编译.Clang 和 MSVC 接受此代码.

The above is perfectly valid C++, but a bug in GCC prevents it from compiling. Clang and MSVC accept this code.

在您的原始代码中,您实际上依赖于 GCC 扩展,它允许您在 C++ 代码中使用 C 风格的复合文字语法,但这个扩展显然碰巧遇到了同样的错误如上所述.

In your original code you are actually relying on a GCC extension, which allows you to use C-style compound literal syntax in C++ code, but this extension apparently happens to suffer from the very same bug as described above.

这篇关于C++ 错误:“取临时数组的地址"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆