gpt4 book ai didi

c++ - 如何在 block 中使用 std::fstream?

转载 作者:行者123 更新时间:2023-11-28 00:48:54 25 4
gpt4 key购买 nike

我在尝试从 block 中使用 ifstream 时遇到问题。 (这是一个更大、更复杂的项目的一部分,所以我快速创建了一个只有相关部分的小源文件。)

// foo.cpp, in its entirety:

#include <iostream>
#include <fstream>
#include <Block.h>

int main() {
__block std::ifstream file("/tmp/bar") ;
// ^ tried this with and without the __block
void (^block)() = ^{
file.rdbuf() ;
file.close() ;
file.open("/tmp/bar") ;
} ;
block() ;
}

如果我用 __block 声明 ifstream,我得到:

foo.cpp:6:24: error: call to implicitly-deleted copy constructor of
'std::ifstream' (aka 'basic_ifstream<char>')
__block std::ifstream file("/tmp/bar") ;
^~~~

如果我在不使用 __block 的情况下声明它,我会得到:

foo.cpp:8:3: error: call to implicitly-deleted copy constructor of
'const std::ifstream' (aka 'const basic_ifstream<char>')
file.rdbuf() ;
^~~~
// rdbuf() and (presumably) other const functions

foo.cpp:9:3: error: member function 'close' not viable: 'this' argument has
type 'const std::ifstream' (aka 'const basic_ifstream<char>'), but
function is not marked const
file.close() ;
^~~~
// open(), close(), and (presumably) other non-const functions

在 block 内使用 fstream 的正确方法是什么?

最佳答案

来自 Block Implementation Specification

It is an error if a stack based C++ object is used within a block if it does not have a copy constructor.

这是第一个错误 - ifstream blocks copy . __block 需要复制。

正如引用所说,一种选择是在堆上声明 ifstream(new/delete).. 但那很麻烦。

其余的错误是简单的 const 正确性错误。不声明 __block 将对象作为 const 拷贝导入,这是两个错误中的第一个,它不能用于调用非 const 函数,如 close

尝试切换到lamda expressions from C++11看看它们是否能缓解这些问题。

关于c++ - 如何在 block 中使用 std::fstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com