2014-01-06 25 views
0

當我返回一個指向我的內存映射文件的指針,或者我在結構中返回我的文件時,數據在函數作用域之外丟失。我的函數應該返回什麼。內存映射文件返回後數據丟失

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

按值返回(該類可複製)。當函數返回時,'file'對象被破壞,留給調用者一個懸掛指針和未定義行爲的程序。 – hmjd

回答

5

您不能返回指向本地堆棧對象的指針。你的編譯器應該發出警告。一旦函數完成,堆棧中的對象將會失去範圍,被銷燬並且指針無效。

您需要將變量放在堆上,方法是使用new創建它,或者您需要創建一個副本(儘管我不確定該類是否可複製)。

在你的函數 getData()

3

你在棧上分配的變量file

mapped_file_source file; 

這意味着該對象在函數作用域的末尾被自動銷燬。

不過你這條線返回此對象的地址:

return &file; 

你倒是應該在堆中分配file用關鍵字new

mapped_file_source * file = new mapped_file_source() ; 

,並沒有手動忘記當你不再需要該對象時,用main()函數中的關鍵字delete將其刪除。

delete file; 
+0

是的,這是有道理的,謝謝。 – jellyfication