在命名空间或 header 中调用 std::vector::insert 函数失败

calling std::vector::insert function in namespace or in header fails

我正在尝试将向量插入到 header 文件中,但由于某种原因无法编译。

#include <vector>
#include <inttypes.h>
#include <stdio.h>
    
namespace test
{
    std::vector<uint8_t> HEADERDATA{0x65, 0x73, 0x68, 0x00, 0x00, 0x00};
    std::vector<uint8_t> ADDITIONALDATA{0x00, 0x02, 0x00, 0x00};
    std::vector<uint8_t> DATA(HEADERDATA);
    DATA.insert(std::end(DATA), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
}

int main() {return 0;}

编译器抛出错误为:

<source>:15:1: error: 'DATA' does not name a type
   15 | DATA.insert(std::end(DATA),

但是,如果我将 insert 移动到 main 函数中,它就可以工作。

int main() 
{
    using namespace test;
    DATA.insert(std::end(DATA), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
}

这里是link到godbolt

有人可以解释这种行为吗?

不能在函数体之外编写语句。代码只能 运行 来自初始化器,这就是三个变量的定义有效的原因。

您可以使用内联 lambda 来创建和return集合:

namespace test
{
    std::vector<uint8_t> HEADERDATA{0x65, 0x73, 0x68, 0x00, 0x00, 0x00};
    std::vector<uint8_t> ADDITIONALDATA{0x00, 0x02, 0x00, 0x00};
    std::vector<uint8_t> DATA([](){
        std::vector<uint8_t> data(HEADERDATA);
        data.insert(std::end(data), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
        return data;
    }());
}