2

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);
Startec
  • 12,496
  • 23
  • 93
  • 160
  • 1
    Does not work how? Are you getting a compilation error? Which error? – nwp Mar 05 '18 at 09:44
  • 1
    I'd look at a `std::vector` first, rather than a smart pointer. Also, this will call the wrong version of `delete`. – Quentin Mar 05 '18 at 09:48

1 Answers1

5

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]);
273K
  • 29,503
  • 10
  • 41
  • 64
  • 6
    or better yet: [`std::vector::data`](http://en.cppreference.com/w/cpp/container/vector/data) ;) – YSC Mar 05 '18 at 09:54
  • nitpick: `framebuffer_data` or `frame_buffer_data`. My preference: `std::vector frame_buffer ... frame_buffer.data()` – Caleth Mar 05 '18 at 11:28