C++ 返回内存映射文件后,数据将丢失

C++ 返回内存映射文件后,数据将丢失,c++,memory-mapped-files,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

当我返回指向内存映射文件的指针或返回结构中的文件时,数据会丢失在函数范围之外。我的函数应该返回什么

#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;
}

不能返回指向本地堆栈对象的指针。编译器应该发出警告。函数完成后,堆栈上的对象将失去作用域、被销毁,并且指针无效

您需要通过使用new创建变量来将其放入堆中,或者您需要创建一个副本,尽管我不确定该类是否可复制。

在函数getData中

在堆栈上分配变量文件

mapped_file_source file;
这意味着该对象在函数范围结束时自动销毁

但是,使用以下行返回此对象的地址:

return &file;
您应该使用关键字new在堆上分配文件:

当您不再需要该对象时,不要忘记在主功能中使用关键字delete手动删除它

delete file;

按值返回,而该类是可复制的。当函数返回时,file对象被销毁,使调用者的指针悬空,程序的行为未定义。
delete file;