0

I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

1
  • out is susceptible to a memory leak. Remember to call delete[] on out. Commented Apr 12, 2011 at 20:05

4 Answers 4

5

Get rid of the fileName variable and use out[i].open(str.c_str()); - and remember to delete[] out;

Sign up to request clarification or add additional context in comments.

3 Comments

does delete[] also calls close() on each stream in my array?
@iuliux: delete[] will ensure the destructor of each stream is called - which closes it.
Cool. Then let your answer be the chosen one, though @Chris Kaminski also answered fine
5

Here's the simplest solution to your problem.

out[i].open(fileName); 

Comments

2

You could optimize this, with removing str and fileName:
out[ i ].open( ss.str().c_str() );

Also, I'd recommend you yo use std::vector not to carry about memory allocation and deallocation.
std::vector< std::ofstream >

3 Comments

Well, I kind of read earlier why ss.str().c_str() doesn't work. The guys were saying that ss.str generates a temporary object.
Huh? It's strange O.o I don't see anything wrong with this - yes, .str() returns temp object, but what? It's still "live" when opening the file(stream).
I just ran this on Visual Studio 2010 and there are no even warnings, it works just fine :?
2

If you really need to call the constructor by the time you insert the element (maybe because your class doesn't have a default constructor), try placement new as described here http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.