首页 > 解决方案 > Initialisation of const member array c++17

问题描述

I'm working on a PNG image decoder in c++17 and defined the following class.

// chunk.h
class Chunk {
    const unsigned dataLength;
    const std::string dataType;
    const unsigned char *const data;
    const unsigned char *const crc;

public:
    Chunk(unsigned dataLength, const std::string &dataType, const unsigned char *data, const unsigned char *const crc);
    ~Chunk();
};
// chunk.cpp
Chunk::Chunk(unsigned dataLength, const std::string &dataType, const unsigned char *data, const unsigned char *crc)
        : dataLength(dataLength),
          dataType(std::string(dataType)),
          data(static_cast<unsigned char *>(memcpy(new unsigned char[dataLength], data, dataLength))),
          crc(static_cast<unsigned char *>(memcpy(new unsigned char[4], crc, dataLength))) {
    if (dataType.size() != 4) {
        throw std::invalid_argument("Chunk type has to be defined on 4 chars");
    }
}

Chunk::~Chunk() {
    delete[] data;
    delete[] crc;
}

My goal is to initialize both constant arrays(data and crc) in the initializer list with a copy of the arrays passed as arguments to the constructor without having to rely on a dedicated method.

I came up with these rather akward lines. I'm a bit afraid of potential unwanted side-effects. Isn't there a better way of doing this ?

I use CLion with mingw-w64\x86_64-8.1.0 and c++17

标签: c++arraysconstantsinitializer-list

解决方案


推荐阅读