作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在尝试从 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/
我是一名优秀的程序员,十分优秀!