c++ - 如何返回带大小的 POD 数组引用?

标签 c++ arrays

我有一个 C++ 03 类,它只有一个头文件实现。该类使用在所有类之间共享的静态空 vector :

static const byte nullVector[64];

当我在类外初始化时,链接因重复符号而失败。所以我把它移到一个函数中,并根据 How to have static data members in a header-only library? 使它成为一个静态局部变量。

现在我试图从访问器返回那个字节数组:

static const byte[64]& GetNullVector {
    static const byte s_NullVector[64] = {
        0,0,0,0,0,0,0,0, ... 0,0,0,0,0,0,0,0
    };
    return s_NullVector;
}

虽然尝试返​​回 byte[]& 可能看起来很奇怪,但我需要它,因为编译时断言:

COMPILE_ASSERT(DIGEST_SIZE <= COUNTOF(GetNullVector()));

COUNTOF 宏需要一个真正的数组,它在指针上失败。当字节数组是静态类成员时它工作正常。

在 C++03 下,如何返回对字节数组的引用及其大小,以便诊断继续按预期工作?

提前致谢。


这是编译错误的样子。 static const byte[64]static const byte[] 的返回类型都会产生错误。

c++ -DNDEBUG -g2 -O3 -fPIC -march=native -pipe -c validat3.cpp
In file included from validat3.cpp:16:
./hkdf.h:33:19: error: expected member name or ';' after declaration specifiers
        static const byte[]& GetNullVector {
        ~~~~~~~~~~~~~~~~~^
./hkdf.h:58:49: error: use of undeclared identifier 'GetNullVector'
        COMPILE_ASSERT(DIGEST_SIZE <= COUNTOF(GetNullVector()));

最佳答案

C 数组的语法有点环绕它所附加的标识符(例如 int array[64])。 当您将引用引入其中时,它会变得有点丑陋:

int (&array_ref)[64]

现在如果你想从函数返回这样的引用:

int (& GetNullVector())[64] { ... }

然而,使用一些 typedef,您可以避免在下一次代码审查中解释这个丑陋的声明;)

typedef byte null_vec_t[64];

static const null_vec_t& GetNullVector()
{
    static const null_vec_t s_NullVector = {0};
    return s_NullVector;
}

关于c++ - 如何返回带大小的 POD 数组引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809371/

相关文章:

C++ libcurl 不发布数据

C错误: size of array is too large

c++ - 根据封闭类模板参数有条件地定义嵌套类

java - 如何修复我的子类循环,使其在主类中调用时仅循环一次?

arrays - 使用node、express将对象数组保存到mongo数据库

Javascript:在数组中的对象中查找数组中对象属性的最大值:D

C++ 如何将用户输入与严格排序的字符串列表进行比较?

c++ - 使用 CDT for C++ 在 Eclipse 中重命名类的更舒适方式?

c++ - 为什么会出现 bad_alloc 错误?

c++ - 在 C++11 中,原始字符串文字可以有多行吗?