在我的代码中,我使用new分配一个整数数组.之后我将这个指针包装到auto_ptr.我知道auto_ptr会自动调用它的析构函数.由于我的auto_ptr指向一个数组(使用new分配),数组是否会与auto_ptr一起被删除,否则会导致内存泄漏.这是我的示例代码.
std::auto_ptr<int> pointer;
void function()
{
int *array = new int[2];
array[0] = 10;
array[1] = 20;
pointer.reset((int*) array);
}
int _tmain(int argc, _TCHAR* argv[])
{
function();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该阵列将无法正确删除.auto_ptr用途delete contained_item;.对于数组,它需要使用delete [] contained_item;.结果是未定义的行为.
正如詹姆斯麦克尼利斯所说,你真的想要std::vector在这里 - 不new,不auto_ptr,不担心.
你不能使用std :: auto_ptr来处理动态数组,因为它不知道如何区分delete和delete [].
此外,auto_ptr不推荐使用,在C++ 11中,您可以使用std::unique_ptr:
int *array = new int[2];
std::unique_ptr<int[]> pointer(array);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
574 次 |
| 最近记录: |