【发布时间】:2010-11-27 08:21:35
【问题描述】:
如何使用文件来初始化一个太大而无法在堆栈中创建的全局 const 对象?这是我迄今为止的尝试:
// test.h
#pragma once
#include <boost/array.hpp>
typedef boost::array<int,100000> bigLut_t;
extern const bigLut_t constLut;
// test.cpp
#include <fstream>
#include <boost/filesystem.hpp>
#include "test.h"
bigLut_t& initializeConstLut()
{
if( boost::filesystem::exists("my_binary_file") == false ) {
std::ofstream outStream( "my_binary_file", ios::out | ios::binary );
bigLut_t* tempLut = new bigLut_t;
for(int i = 0; i < 100000; ++i) {
// Imagine this taking a long time,
// which is why we're using a file in the first place
tempLut->at(i) = i;
}
outStream.write( reinterpret_cast<char*>(tempLut), sizeof(bigLut_t) );
outStream.close();
delete tempLut;
}
// We can't write "bigLut_t lut;" because that would cause a stack overflow
bigLut_t* lut = new bigLut_t; // lut gets never deallocated
std::ifstream inStream( "my_binary_file", ios::in | ios::binary );
inStream.read( reinterpret_cast<char*>(lut), sizeof(bigLut_t) );
inStream.close();
return *lut;
}
const bigLut_t constLut = initializeConstLut();
AFAIK 这在某种意义上是有效的,即 constLut 被正确初始化,但由于 bigLut_t* lut 永远不会被释放,因此存在内存泄漏。我尝试使用智能指针,但这导致 constLut 中的值非常随机。通过尝试谷歌解决方案,我发现缺乏信息,这让我感到困惑。
【问题讨论】:
标签: c++ initialization constants global