Dipak
Dipak

Reputation: 143

Creating objects runtime

i want to create std::ifstream object at runtime as i create new thread ,

ifstream& 
getMultiDataReaderStream()
{
      ifstream ifs;
        ifs.open(m_dataReaderFileName.c_str(), ios::in | ios::binary);
    return ifs;
}

void
runThread(void *lpData)
{
      ifstream& ifs1 = storeManager.getMultiDataReaderStream();
      // code for reading while EOF
      ifs1.close();
}

But , I am getting segmentation Fault is something wrong in above code....

Upvotes: 0

Views: 172

Answers (3)

quetzalcoatl
quetzalcoatl

Reputation: 33536

According to this: Is std::ofstream movable?

both ifstream and ofstream should be movable, so you should be able to simply "just return it". But, many compilers does not have their stdlibs adapted to C'11 properly. For instance, I've just tried it at http://coliru.stacked-crooked.com/ which seems to have g++ 4.8 and I still cannot move/return any fstream - compiler still insists on using nonexistent copy-constructor instead of move ctor.

This was a known issue that GCC hadn't implemented movability in the streams part. Sorry, I don't know anything more. You'll need to stick with the workarounds until c'11 support gets better.

Upvotes: 1

thang
thang

Reputation: 3466

See my comment.

There are many ways to fix this. One is this:

void getMultiDataReaderStream(ifstream& ifs)
{
    ifs.open(m_dataReaderFileName.c_str(), ios::in | ios::binary);
}

void
runThread(void *lpData)
{
      ifstream ifs1;
      getMultiDataReaderStream(ifs1);
      // code for reading while EOF
      ifs1.close();
}

Another is this: (don't use this, this works, but it's sloppy)

ifstream* getMultiDataReaderStream()
{
    ifstream* ifs = new ifstream(m_dataReaderFileName.c_str(), ios::in | ios::binary);
    return ifs;
}

void
runThread(void *lpData)
{
      ifstream* ifs1 = getMultiDataReaderStream();
      // code for reading while EOF
      ifs1->close();
      delete ifs1;
}

And then with smart ptr:

shared_ptr<ifstream> getMultiDataReaderStream()
{
    shared_ptr<ifstream> ifs = shared_ptr<ifstream>(new ifstream(m_dataReaderFileName.c_str(), ios::in | ios::binary));
    return ifs;
}

void
runThread(void *lpData)
{
      shared_ptr<ifstream> ifs1 = getMultiDataReaderStream();
      // code for reading while EOF
      ifs1->close();
}

I am sure there are other ways...

Upvotes: 1

Gorpik
Gorpik

Reputation: 11028

You should never return a reference (or a pointer) to a local object from a function. In this case, getMultiDataReaderStream() is returning a reference to an object (ifs) that is destroyed as soon as you leave the function. So using it is invalid and leads to undefined behaviour. For instance, a segmentation fault.

Upvotes: 0

Related Questions