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

梦想与她 提交于 2021-02-10 08:13:35

问题


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

回答1:


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]);


来源:https://stackoverflow.com/questions/49107332/how-to-pass-a-smart-pointer-to-a-function-expecting-a-raw-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!