0

I'm having trouble trying to use an ifstream from within a block. (This is part of a larger, complex project, so I whipped up a quick little source file with just the relevant parts.)

// 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() ;
}

If I declare the ifstream with __block, I get:

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

If I declare it without __block, I get:

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

What's the proper way to use fstreams inside of blocks?

newacct
  • 119,665
  • 29
  • 163
  • 224
Blacklight Shining
  • 1,468
  • 2
  • 11
  • 28

1 Answers1

3

From 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.

Which is the first error - ifstream blocks copy. __block requires copy.

As the quote says, one option is to declare ifstream on heap(new/delete).. but that is messy.

The rest of the errors are simple const correctness errors. Not declaring __block imports the objects as a const copy, which is the first of the two errors, and it cannot be used to call non const functions like close.

Try to switch to lamda expressions from C++11 and see if they alleviate these issues.

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87