[英]Trying to return std::ifstream from a function
當我嘗試使用此功能時,在兩個返回值時出現錯誤。 如果我將其注釋掉,則不會得到錯誤。 有什么原因為什么這不起作用?
std::ifstream bipgetConfigurationPath() {
char bipacfFilename[256], bipacfFullPath[512];
char *bipconfigPath;
char *bipdefaultConfigFile;
const char *bipdefaultConfigFileName;
bipdefaultConfigFile = "./Resources/plugins/Xsaitekpanels/D2B_config.txt";
bipdefaultConfigFileName = "D2B_config.txt";
XPLMGetNthAircraftModel(0, bipacfFilename, bipacfFullPath);
bipconfigPath = strstr(bipacfFullPath, bipacfFilename);
strncpy(bipconfigPath, bipdefaultConfigFileName, sizeof(bipacfFilename));
puts(bipacfFullPath);
// Check if ACF-specific configuration exists
std::ifstream bipcustomStream(bipacfFullPath);
if (bipcustomStream.good()) {
return bipcustomStream;
} else {
std::ifstream bipdefaultStream(bipdefaultConfigFile);
if (bipdefaultStream.good()) {
return bipdefaultStream;
}
}
}
謝謝比爾
通過將其復制構造函數設為private
,可以使C ++中的所有流類均不可復制。 這意味着您不能按值返回流對象。 閱讀這個詳細。 故事的結局。
因此,解決方案是將流對象傳遞給函數作為引用,然后在函數中打開文件,然后從文件中返回,或者使用new
創建流對象,然后從函數返回指向流對象的指針,但是如果為此,您必須在完成操作后delete
該對象。 我個人不會做任何一個。
我可能會在一個類中封裝流以及您希望對該對象進行的行為/工作。
在C ++ 11中,您可以使用std::move
移動流對象,因為流是可移動的。
std :: streams是不可復制的。
正如其他人所說,文件流不可復制。 也許更像這樣:
bool bipgetConfigurationPath(std::ifstream& ifs) {
std::string bipdefaultConfigFileName("D2B_config.txt");
// ...
ifs.open(bipdefaultConfigFileName);
return ifs.good();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.