是否使用auto_ptr与新的char [n] [英] Is it wrong to use auto_ptr with new char[n]
问题描述
如果我使用
std::auto_ptr<char> buffer(new char[n]);
那么当缓冲区超出范围时,缓冲区会自动删除。我假设使用delete删除缓冲区。
then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.
但是缓冲区是使用new []创建的,所以严格来说,缓冲区应该使用delete []删除。
However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].
这种不匹配可能导致内存泄漏的可能性是什么?
What possibility is there that this mismatch might cause a memory leak?
推荐答案
对分配有新[]的指针调用delete的行为是 undefined 。如您所假设的,当智能指针超出范围时,auto_ptr 会调用删除。它不只是内存泄漏你必须担心 - 崩溃和其他奇怪的行为是可能的。
The behaviour of calling delete on a pointer allocated with new[] is undefined. As you assumed, auto_ptr does call delete when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
如果你不需要转让指针的所有权,Boost的 scoped_array 类可能是您要找的。
If you don't need to transfer the ownership of the pointer, Boost's scoped_array class might be what you're looking for.
这篇关于是否使用auto_ptr与新的char [n]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!