Search code examples
c++arraysshared-ptrsmart-pointers

Wrap dynamic array with shared_ptr by make_shared


I want to write some bytes to an array. To make use of modern C++ I have decided to use a smart pointer.

#include <memory>
#include <cstdint>

using namespace std;

void writeUint32_t(uint32_t value, unsigned char* p){
    *p     = static_cast<unsigned char>((value >> 24) & 0xFF);
    *(++p) = static_cast<unsigned char>((value >> 16) & 0xFF);
    *(++p) = static_cast<unsigned char>((value >>  8) & 0xFF);
    *(++p) = static_cast<unsigned char>((value      ) & 0xFF);
}

int main(){
    auto buf = make_shared<unsigned char[]>(512);
    uint32_t data = 1234;
    writeUint32_t(data, buf.get() + 8);
}

However, I am receiving the following compilation error:

u.cpp:15:37: error: invalid use of array with unspecified bounds
 writeUint32_t(data, buf.get() + 8);
                                 ^
u.cpp:15:38: error: cannot convert ‘unsigned char (*)[]’ to ‘unsigned char*’ for argument ‘2’ to ‘void writeUint32_t(uint32_t, unsigned char*)’
 writeUint32_t(data, buf.get() + 8);

I am using g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609 Is there a way to use smart pointers in such a situation?


Solution

  • I recommend you use std::vector<unsigned char> vec(512);, wrapping contiguous dynamic arrays is exactly what it's for. Getting the raw buffer pointer is as simple as vec.data();

    If the vector needs to be shared, than you can still use a smart pointer

    auto p_vec = make_shared<vector<unsigned char>>(512);
    

    You'll get the benefit of reference counting with virtually no overhead due to using vector, and you'll get the entire vector API.