我对智能指针非常陌生,并且正在尝试重构一些现有的代码以使用auto_ptr。我的问题是关于双指针和它们的auto_ptr等效项,如果这有意义的话。
我有一个函数,它接受一个双指针作为它的参数,并为它分配资源:
void foo ( Image** img ) { ... *img = new Image(); ...}然后按如下方式使用此函数:
Image* img = NULL;
foo ( &img );
...
delete img;我想使用auto_ptr来避免显式调用delete。下面的是正确的吗?
void foo ( auto_ptr<Image>* img ) { ... *img = auto_ptr<Image>(new Image()); ...}然后
auto_ptr<Image> img = NULL;
foo ( &img );谢谢。
发布于 2010-04-29 16:02:03
std::auto_ptr<>有奇怪的复制语义(实际上它是移动语义,而不是复制语义),当你想要一个智能指针时,它通常不是你想要的。例如,它不能放入STL容器中。
如果您的标准库附带TR1支持,请改用std::tr1::shared_ptr<>。(如果没有,请使用boost's boost::shared_ptr<>,这就是std::tr1::shared_ptr<>的来源。)
如果你想在你的代码中坚持使用std::auto_ptr<>,你可以把它传递给每个非const引用的函数:
void foo ( std::auto_ptr<Image>& img ) { ... img.reset(new Image();) ...}
std::auto_ptr<Image> img;
foo ( img );
...
// no need to delete或者你可以直接返回指针:
std::auto_ptr<Image> foo () {return std::auto_ptr<Image> img(new Image();)}发布于 2010-04-29 16:11:36
这取决于你的auto_ptr的STL实现是否覆盖了'&‘操作符来返回一个指针到指针(大多数智能指针类倾向于,但不是所有的auto_ptr实现都是这样)。
如果你真的想重写你的代码来传递auto_ptr对象,那么你应该做一些类似这样的事情,这会更安全:
void foo ( std::auto_ptr<Image> &img ) { ... img.reset(new Image()); ...}
std::auto_ptr<Image> img;
foo ( img );发布于 2010-04-29 16:32:42
既然您正在重构,我将更进一步,将参数转换为返回值:
// void foo( Image ** img )
std::auto_ptr<Image> foo() {
std::auto_ptr<Image> tmp( new Image() );
// ...
return tmp;
}即使我更喜欢从接口中删除需求(以便调用者可以随意更改代码以使用任何其他类型的智能指针):
Image* foo() {
std::auto_ptr<Image> tmp( new Image() );
// ...
return tmp.release();
}
int main() {
std::auto_ptr<Image> ptr( foo() );
}https://stackoverflow.com/questions/2735605
复制相似问题