如何使用一個文件初始化一個全局常量對象,該對象太大而無法在堆棧中創建?這是迄今爲止我嘗試:初始化一個大的全局常量對象
// 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被corretly初始化,但有一個內存泄漏,因爲bigLut_t * LUT被永遠不會釋放。我嘗試使用智能指針,但導致constLut中的值非常隨機。我對通過嘗試谷歌解決方案所發現的信息缺乏感到困惑。
我很確定我確實嘗試了auto_ptr和shared_ptr,但我猜測它沒有工作,因爲我在initializeConstLut函數中取消了引用智能指針。但是,這似乎是完美的,謝謝。儘管你錯過了get()到lut的右側。 – zeroes00 2010-11-27 08:59:18
我不想冒犯巴黎同胞,但我覺得很可惜,你的解決方案需要建造一個臨時性的巨大物體,然後是複製結構(我認爲這是昂貴的),並且臨時銷燬臨時的 – icecrime 2010-11-27 09:06:08