如何将智能指针传递给需要原始指针的函数?
How to pass a smart pointer to a function expecting a raw pointer?
我有以下代码:
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);
我想摆脱原始指针 (frame_buffer_data
) 并使用唯一指针。
试试这个:
std::unique_ptr<unsigned char> framebuffer_data(new unsigned char[data_size] );
无效。
如何将唯一指针(或其他智能指针)传递给此函数?
调用 glReadPixels
后,我需要能够 reinterpret cast
数据类型并将数据写入文件,如下所示:
screenshot.write(reinterpret_cast<char*>(frame_buffer_data), data_size);
当你需要一个由智能指针拥有的数组时,你应该使用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());
但更好的情况是像下面这样,它更简洁、更短。
std::vector<unsigned char> framebuffer_data(data_size);
glReadPixels(origin_x, origin_y, width, height, GL_BGR, GL_UNSIGNED_BYTE, &framebuffer_data[0]);
我有以下代码:
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);
我想摆脱原始指针 (frame_buffer_data
) 并使用唯一指针。
试试这个:
std::unique_ptr<unsigned char> framebuffer_data(new unsigned char[data_size] );
无效。
如何将唯一指针(或其他智能指针)传递给此函数?
调用 glReadPixels
后,我需要能够 reinterpret cast
数据类型并将数据写入文件,如下所示:
screenshot.write(reinterpret_cast<char*>(frame_buffer_data), data_size);
当你需要一个由智能指针拥有的数组时,你应该使用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());
但更好的情况是像下面这样,它更简洁、更短。
std::vector<unsigned char> framebuffer_data(data_size);
glReadPixels(origin_x, origin_y, width, height, GL_BGR, GL_UNSIGNED_BYTE, &framebuffer_data[0]);