Which to use - “operator new” or “operator new[]” - to allocate a block of raw memory in C++?

后端 未结 4 1137
情话喂你
情话喂你 2021-01-12 05:54

My C++ program needs a block of uninitialized memory and a void* pointer to that block so that I can give it to a third party library. I want to pass control of

4条回答
  •  再見小時候
    2021-01-12 06:30

    Use new with a single object and new[] with an array of objects. So, for example:

    int* x = new int; // Allocates single int
    int* y = new int[5]; // Allocates an array of integers
    
    *x = 10; // Assignment to single value
    y[0] = 8; // Assignment to element of the array
    

    If all you are doing is allocating a memory buffer, then allocate an array of char as in:

    int bufferlen = /* choose a buffer size somehow */
    char* buffer = new char[bufferlen];
    // now can refer to buffer[0] ... buffer[bufferlen-1]
    

    However, in C++, you should really use std::vector for arbitrary arrays, and you should use std::string for character arrays that are to be interpreted or used as strings.

    There is no reason to invoke ::operator new or ::operator new[] explicitly rather than using the ordinary syntax for these calls. For POD and primitive types (e.g. char) no initialization will take place. If you need to get a void* buffer, then simply use static_cast to convert char* to void*.

提交回复
热议问题