如何将智能指针传递给期望原始指针的函数?

问题描述 投票:1回答:1

我有以下代码:

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);
c++ smart-pointers
1个回答
4
投票

当您需要智能指针所拥有的数组时,您应该使用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]);
© www.soinside.com 2019 - 2024. All rights reserved.