Startec
Startec

Reputation: 13206

How to pass a smart pointer to a function expecting a raw pointer?

I have the following code:

unsigned char* frame_buffer_data{ new unsigned char[data_size] };
glReadPixels(origin_x, origin_y, width, height, GL_BGR, GL_UNSIGNED_BYTE, frame_buffer_data);

I want to get rid of the raw pointer (frame_buffer_data) and use a unique pointer.

Trying this:

std::unique_ptr<unsigned char> framebuffer_data(new unsigned char[data_size] );

does not work.

How can I pass the unique pointer (or other smart pointer) to this function?

After the call to glReadPixels I need to be able to reinterpret cast the data type and write the data to a file, like so:

screenshot.write(reinterpret_cast<char*>(frame_buffer_data), data_size);

Upvotes: 2

Views: 288

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38623

When you need an array owned by a smart pointer, you should use unique_ptr<T[]>.

std::unique_ptr<unsigned char[]> framebuffer_data(new unsigned char[data_size] );
glReadPixels(origin_x, origin_y, width, height, GL_BGR, GL_UNSIGNED_BYTE, framebuffer_data.get());

But better case is like below, it is cleaner and shorter.

std::vector<unsigned char> framebuffer_data(data_size);
glReadPixels(origin_x, origin_y, width, height, GL_BGR, GL_UNSIGNED_BYTE, &framebuffer_data[0]);

Upvotes: 5

Related Questions