Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize pointer(new uint8_t[height * width*3]) in one line

I am following a c++ course and there is something I would like to be able to do in one line. I have the following 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
    {}
};

But I would rather initialize the pointer member inline like:

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

Is this possible?

like image 208
CerribleToder Avatar asked Sep 20 '25 22:09

CerribleToder


1 Answers

You can, this will work:

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

Live example

But don't do this. Why?

If I do this:

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

I have undefined behaviour, because I will be using width uninitialized. At least if I do this:

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;
};

Then a warning will appear stating out of order elements in the initializer list. And since I should be compiling with warnings as errors, I will, luckily, be unable to compile this buggy code. Finally, I am using a vector, which is definitely what you are looking for, it is much much nicer to use :)

like image 194
Fantastic Mr Fox Avatar answered Sep 22 '25 14:09

Fantastic Mr Fox