auto_ptr
的含义是什么?
看这段代码:
#include <iostream>
#include <memory>
class A
{
public:
~A()
{
std::cout << "DEST";
};
};
void func(A* pa)
{
std::cout << "A pointer";
}
void test()
{
A a;
std::auto_ptr<A> pA(new A);
//func(pA); //compiler error here cannot convert parameter 1 from 'std::auto_ptr<_Ty>' to 'A *'
std::cout << "end";
}
int main(int argc, char* argv[])
{
test();
return 0;
}
使用这个 auto_ptr
有什么意义?
- 当超出正常类初始化变量 (a) 的范围时调用类析构函数。
- 我无法将此指针传递给具有类指针 (func) 的函数
- 我不能为
A[]
或char[]
使用指针auto_ptr
因为 auto_ptr 调用 delete 而不是delete[]
.
唯一的想法是我不必写 delete,但是如果当我离开范围时它会被销毁,那么指针的意义是什么。我使用指针来控制变量的生命。
普通变量初始化在栈上,指针在堆上,但告诉我使用 auto_ptr
而不是普通指针有什么意义?
最佳答案
The only think is that I dont have to write delete
是的,考虑到内存泄漏是您会遇到的最常见错误之一,这是一个相当大的好处。
whats the sense of pointer if it will be destoyed when I get out of scope. I use pointer to control the live of the variable.
您改变了这种心态,使用范围来定义变量的生命周期。您只需在适当的范围内声明这些东西,而不必再担心清理。这就是重点。
您的示例是人为设计的,但您仍然可以看出它的值(value)。当然,您可能不会忘记在一个什么都不做的两行函数中调用 delete
。在实际应用中,事情变得更加复杂。
当您新建
一堆对象时,您可以相信,当函数退出时,对象将被清除。类(class)也是如此;当一个实例超出范围时,您可以依靠它的析构函数来为您解除分配内存。考虑抛出异常时会发生什么。如果没有 auto_ptr,你需要确保你处理了每一个可能的异常和每一个可能的返回路径,以确保你自己清理干净。
还有...
The normal variable initialize is on the stack and pointer on heap
不完全是。本例中的指针具有自动存储持续时间,它指向的内容但是没有。
你的编译器对你传递 auto_ptr
的原因咆哮是因为该函数不采用 auto_ptr
。您需要调用 get()
来传入指针本身。
就是说,您也不应该使用 auto_ptr
;使用 unique_ptr如果您有权访问 C++ 0x 编译器,那么您应该这样做。
关于c++ - 使用 std::auto_ptr 的感觉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867949/