我写了一个文件IO库.一个功能,File::read如下所示:
template <typename T>
void File::read(T * t, unsigned long count) const
Run Code Online (Sandbox Code Playgroud)
它读入countT成*t.
现在,跳到客户端.我分配了一个我想读入的内存缓冲区.我写了这个并且效果很好:
float * buffer = new float [16];
file->read(buffer, 16);
Run Code Online (Sandbox Code Playgroud)
但是,这不是例外的安全.所以我决定将缓冲区包装成一个std::unique_ptr.在这里的某个地方,我犯了一个错误.
std::unique_ptr<float[]> buffer (new float[16]);
file->read(*buffer , 16);
Run Code Online (Sandbox Code Playgroud)
这会在file-> read上产生以下错误:
'operator*'不匹配(操作数类型为'std :: unique_ptr')
我认为通过解除引用unique_ptr我会得到一个指向float[]数组第一个元素的指针.我的错误在哪里,解决了什么?
你有两个问题:第一个是你做出std::unique_ptr的float[](即你有一个指针数组float).
另一个问题是智能指针就像普通指针一样.当您使用*运算符取消引用普通指针时,您不再有指针而是一个值(指针指向的值).
另外,我建议你使用std::array(如果你知道编译时的大小)或者std::vector使用智能指针.在现代C++中,根本不需要指针.
你可以像使用它一样
std::array<float, 16> buffer;
file->read(buffer.data(), buffer.size());
Run Code Online (Sandbox Code Playgroud)
如果你没有,std::array你可以使用std::vector:
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());
Run Code Online (Sandbox Code Playgroud)