How to initialise memory with new operator in C++?
I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int
with the new
operator, how can I initialise them all to 0 without looping through them all myself? Should I just use memset
? Is there a “C++” way to do it?
It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for default-initializing an array (well, technically, it's called "value-initialize" in the Standard):
new int[10]();
Note that you must use the empty parentheses - you cannot, for example, use (0)
or any other expression (which is why this is only useful for default initialization).
This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:
A new-expression that creates an object of type T initializes that object as follows:
...
and does not restrict the types for which this is allowed, whereas the (expression-list)
form is explicitly restricted by further rules in the same section such that it does not allow array types.
Assuming that you really do want an array and not a std::vector, the "C++ way" would be this
#include <algorithm>
int* array = new int[n]; // Assuming "n" is a pre-existing variable
std::fill_n(array, n, 0);
But be aware that under the hood this is still actually just a loop that assigns each element to 0 (there's really not another way to do it, barring a special architecture with hardware-level support).
There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...
Manual initialisation of all elements in loop
int* p = new int[10];
for (int i = 0; i < 10; i++)
{
p[i] = 0;
}
Using std::memset
function from <cstring>
int* p = new int[10];
std::memset(p, 0, 10);
Using std::fill_n
algorithm from <algorithm>
int* p = new int[10];
std::fill_n(p, 10, 0);
Using std::vector
container
std::vector<int> v(10); // elements zero'ed
If C++0x available, using initializer list features
int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime
链接地址: http://www.djcxy.com/p/13756.html
上一篇: 马洛克vs新的原始人
下一篇: 如何用C ++中的新运算符初始化内存?