2

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[]?

MathematicalOrchid
  • 61,854
  • 19
  • 123
  • 220

2 Answers2

5
char buffer[1024];
stream.read(buffer, 1024 /* or sizeof(buffer) */); 
Motti
  • 110,860
  • 49
  • 189
  • 262
  • So much simpler... I feel dumb now. – MathematicalOrchid Nov 21 '13 at 14:53
  • 2
    Yes, anytime the buffer size is known at compile time and doesn't escape its scope it's a candidate for moving onto the stack. However, one reason even buffers with fixed size and lifetime might be better not on the stack is that they're so large they risk using up all the stack space. 1024 bytes is relatively small, but if the buffer size were, say, 10 MiB then you wouldn't want it on the stack. In that case you still shouldn't use `new`, you should use something like `std::vector buf(10485760);`. @MathematicalOrchid – bames53 Nov 21 '13 at 14:59
  • @bames53 How big is "big"? What's a typical C++ stack size? – MathematicalOrchid Nov 21 '13 at 15:08
  • 1
    @MathematicalOrchid Stack limits are usually from 1 to a few megabytes, though usually you can set the size you want. How big an object you're willing to store on the stack depends on how much other stuff you want there; how many function frames deep the program goes, the average size used for local variables, etc. You can get an idea of how much stack space you're using by taking the difference of addresses of local variables with the address of a local variable in `main()` (though technically that's undefined behavior). – bames53 Nov 21 '13 at 17:59
4

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);
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455