I wrote a File IO library. One function, File::read looks like this:
template <typename T>
void File::read(T * t, unsigned long count) const
It reads count T into *t.
Now, skipping to the client. I allocate a memory buffer which I want to read into. I wrote this and it works great:
float * buffer = new float [16];
file->read(buffer, 16);
However, this not exception safe. So I decided to wrap the buffer in a std::unique_ptr. Somewhere in here I am making a mistake.
std::unique_ptr<float[]> buffer (new float[16]);
file->read(*buffer , 16);
This produces the following error on file->read:
no match for 'operator*' (operand type is 'std::unique_ptr')
I thought that by dereferencing the unique_ptr I'd get a pointer to the first element of the float[] array. Where is my mistake and what is the fix?
You have a couple of problems: The first is that you make a std::unique_ptr of float[] (i.e. you have a pointer to arrays of float).
The other problem is that smart pointers acts just as normal pointers. When you dereference a normal pointer with the * operator, you no longer have a pointer but a value (the value of what the pointer points to).
Also, I would suggest you to use either std::array (if you know the size at compile-time) or std::vector instead of smart pointers. In modern C++ there is almost no need for pointers at all.
You could use it like
std::array<float, 16> buffer;
file->read(buffer.data(), buffer.size());
If you don't have std::array you can use std::vector instead:
std::vector<float> buffer(16); // Create a vector of 16 floats,
// default initialized (i.e. 0.0)
// &buffer[0] is a pointer to the first element in the vector
// all vectors are guaranteed to be contiguous like normal arrays
file->read(&buffer[0], buffer.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With