【问题标题】:How to pass a smart pointer to a function expecting a raw pointer?如何将智能指针传递给期望原始指针的函数?
【发布时间】:2018-03-05 09:41:01
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 不工作怎么办?你得到一个编译错误?哪个错误?
  • 我会先看std::vector,而不是智能指针。此外,这将调用错误版本的delete

标签: c++ smart-pointers


【解决方案1】:

当你需要一个智能指针拥有的数组时,你应该使用unique_ptr&lt;T[]&gt;

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

【讨论】:

  • 或者更好:std::vector::data ;)
  • 挑剔:framebuffer_dataframe_buffer_data。我的偏好:std::vector&lt;unsigned char&gt; frame_buffer ... frame_buffer.data()
猜你喜欢
  • 1970-01-01
  • 2021-12-03
  • 2015-05-29
  • 1970-01-01
  • 2012-09-13
  • 2021-07-22
  • 1970-01-01
  • 2021-03-10
  • 2012-05-29
相关资源
最近更新 更多