c++ - 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
解决方案
推荐阅读
- javascript - 如何在打字稿中投射对象
- c# - 在 QuickFIX/n 中监控断开连接
- system-verilog - Systemverilog 函数综合——自动 vs 静态
- html - VS Code - 如何自动转换内联样式字符串以响应内联样式对象
- discord - discord.py wait_for 没有读取消息
- function - 用玩笑模拟导入函数的依赖项
- dax - DAX 度量无法找到所有表
- azure-devops - 如何在 Azure DevOps 中使用具有阶段依赖性的 DependsOn
- bash - 使用文本文件每一行的修改版本作为 sed 命令 (bash) 中的参数
- css - Tailwind CSS 在构建后创建 4 mb 文件