當我返回一個指向我的內存映射文件的指針,或者我在結構中返回我的文件時,數據在函數作用域之外丟失。我的函數應該返回什麼。內存映射文件返回後數據丟失
#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;
}
按值返回(該類可複製)。當函數返回時,'file'對象被破壞,留給調用者一個懸掛指針和未定義行爲的程序。 – hmjd