c++ - 在一行中初始化 pointer(new uint8_t[height * width*3])

标签 c++ pointers unique-ptr procedural

我正在学习一门 c++ 类(class),有些事情我希望能够在一行中完成。我有以下类(class):

class example {
private:
    int height, width;
    std::unique_ptr<uint8_t[]> pointer = nullptr;
public:
    example()
        :pointer(new uint8_t[height * width * 3]) // this works
    {}
};

但我宁愿像这样初始化 pointer 成员内联:

unique_ptr<uint8_t[]> pointer = new uint8_t[height * width * 3]; // doesnt work

这可能吗?

最佳答案

可以,这会起作用:

struct P {
    size_t height, width;
    std::unique_ptr<size_t[]> vals = std::make_unique<size_t[]>(height * width * 3);
};

Live example

但是不要这样做。为什么?

如果我这样做:

struct P {
    size_t height;
    std::unique_ptr<size_t[]> vals = std::make_unique<size_t[]>(height * width * 3);
    size_t width;
};

我有未定义的行为,因为我将使用未初始化的width。至少如果我这样做:

struct P {
    P(size_t h, size_t w) :
       height{h}, width{w},
       vals{height * width * 3}
    {} // Initialization in the initialization list

    size_t height;
    std::vector<size_t> vals;
    size_t width;
};

然后会出现一条警告,指出初始化列表中的元素顺序错误。由于我应该将警告作为错误进行编译,幸运的是,我将无法编译这个有缺陷的代码。最后,我使用的是 vector ,这绝对是您正在寻找的,使用起来要好得多:)

关于c++ - 在一行中初始化 pointer(new uint8_t[height * width*3]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677894/

相关文章:

c++ - GNU C++ 中的原子交换

c++ - 自动选择目标文件进行编译

c++ - 如何在 C++ 中实现对函数的二分查找?

c++ - 为父/子关系正确使用 unique_ptr

c++ - 使用 C++ 构造函数时什么时候必须使用 'this'?

c - malloc、realloc 后出现 "Pointer being freed was not allocated."错误

c++ - 静态指针 C++ 用法

c - 使用指针的数组内存地址分配声明的相同优先级

c++ - 如何使用静态删除器创建 unique_ptr

c++ - 在 C++/CLI 中使用 unique_ptr 时出现链接器错误