Reputation: 62848
I was looking at another SO question, and the top-rated answer said this:
Other answers have already mentioned RAII, and that's a good answer. However, the best advice is this: don't allocate dynamic objects in the first place! Don't write
Foo * x = new Foo();when you could just write
Foo x;instead.
This seems like sound advice to me. Stack-based stuff already has fine and good automatic lifetime management.
My question is this: How to I apply this sound advice to something like
char * buffer = new char[1024];
stream.read(buffer, 1024);
...do stuff...
delete[] buffer;
Appologies if I'm being dumb, but how do you create arrays without using new[]
?
Upvotes: 2
Views: 1438
Reputation: 171167
If the array is fixed-size (e.g. the 1024 in your question), just this:
char buffer[1024];
Or, in C++11, the preferred:
std::array<char, 1024> buffer;
If the arrary size is only known at runtime (or if it's too big to fit comfortably on the stack), this:
std::vector<char> buffer(1024);
Upvotes: 4
Reputation: 114795
char buffer[1024];
stream.read(buffer, 1024 /* or sizeof(buffer) */);
Upvotes: 5