我在看另一个 SO 问题,评分最高的答案是这样说的:
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.
这对我来说似乎是个不错的建议。基于堆栈的东西已经具有很好的自动生命周期管理。
我的问题是:如何将这个合理的建议应用到类似的事情上
char * buffer = new char[1024];
stream.read(buffer, 1024);
...do stuff...
delete[] buffer;
对不起,如果我是愚蠢的,但是你如何在不使用 new[]
的情况下创建数组?
最佳答案
char buffer[1024];
stream.read(buffer, 1024 /* or sizeof(buffer) */);
关于C++ 处理数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20124085/