除了在源代码中指定其元素的详尽列表(膨胀源代码和二进制文件)之外,我如何在启动时填充静态数组?
这是我能想到的用 0 到 99 之间的值动态填充 array
的最佳方法:
int array[100];
struct FillArray {
FillArray() {
std::iota(std::begin(array), std::end(array), 0);
}
};
FillArray dummy;
是否有更惯用的模式?
数组的定义不能改变:它必须看起来像调用代码的静态数组(例如,不建议使用 std::array
)。
请注意,我并不是要解决静态初始化顺序问题。也就是说,您可以假设除了初始化之外,直到 main()
开始之后才再次访问数组。
最佳答案
您正在寻找的是 Schwarz Counter 的某个版本(更广为人知的名称是 Nifty Counter)。
Nifty Counter 用于在程序中首次使用前初始化非本地静态对象,并在最后一次使用后销毁它。
标准库中 Nifty Counter 的一个例子是 std::cout。
这是您的用例示例:
// GlobalArray.hpp
#pragma once
#include <array>
struct GlobalArray // This the the struct containing the 'static' object we want
{
GlobalArray();
~GlobalArray();
std::array<int, 100> array;
};
extern GlobalArray& global_array; // This is the variable containing the reference to the constructed 'static' object.
static struct GlobalArrayInit
{
GlobalArrayInit();
~GlobalArrayInit();
} global_array_init;
现在……
// GlobalArray.cpp
#include "GlobalArray.hpp"
static int nifty_counter; // zero initialised at load time
static typename std::aligned_storage<sizeof (GlobalArray), alignof (GlobalArray)>::type
global_array_buf; // memory for the global_array object
GlobalArray& global_array = reinterpret_cast<GlobalArray&> (global_array_buffer);
GlobalArray::GlobalArray ()
{
// initialize things
}
GlobalArray::~GlobalArray ()
{
// clean-up
}
GlobalArrayInit::GlobalArrayInit ()
{
if (nifty_counter++ == 0) new (&global_array) GlobalArray (); // placement new
}
GlobalArrayInit::~GlobalArrayInit ()
{
if (--nifty_counter == 0) (&global_array)->~GlobalArray ();
}
请注意,您必须在使用“global_array”对象之前包含 header ,以确保它已正确构建。
如果您想进一步了解它是如何工作的,以及我从哪里得到源代码的想法,请阅读:https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter
关于c++ - 在启动时填充全局静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721454/