Iulius Curt
Iulius Curt

Reputation: 5114

C++ alloc array of objects

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)

Upvotes: 0

Views: 472

Answers (4)

Konstantin Weitz
Konstantin Weitz

Reputation: 6432

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

Upvotes: 2

Kiril Kirov
Kiril Kirov

Reputation: 38173

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 >

Upvotes: 2

Chris K
Chris K

Reputation: 12359

Here's the simplest solution to your problem.

out[i].open(fileName); 

Upvotes: 5

Erik
Erik

Reputation: 91300

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

Upvotes: 5

Related Questions