jel*_*ion 0 c++ memory-mapped-files
当我返回指向我的内存映射文件的指针或我在结构中返回我的文件时,数据在函数范围之外丢失.我的功能应该返回什么
#include <iostream>
#include <fstream>
#include <boost/iostreams/device/mapped_file.hpp>
using namespace std;
using namespace boost::iostreams;
struct data
{
public:
long long timestamp;
double number1;
double number2;
};
int fileSize(ifstream &stream){
stream.seekg(0, ios_base::end);
return stream.tellg();
}
mapped_file_source * getData(const string& fin){
ifstream ifs(fin, ios::binary);
mapped_file_source file;
int numberOfBytes = fileSize(ifs);
file.open(fin, numberOfBytes);
// Check if file was successfully opened
if (file.is_open()) {
return &file;
}
else {
throw - 1;
}
}
int main()
{
mapped_file_source * file = getData("data/bin/2013/6/2/AUD_USD.bin");
struct data* raw = (struct data*) file->data();
cout << raw->timestamp;
}
Run Code Online (Sandbox Code Playgroud)
您不能返回指向本地堆栈对象的指针.您的编译器应该发出警告.函数完成后,堆栈上的对象将丢失范围,被销毁并且指针无效.
您需要通过创建它来将变量放在堆上,new或者您需要复制(尽管我不确定该类是否可以复制).