Question about smart pointers in C++
Is auto_ptr good to 开发者_StackOverflow中文版work with only for local variables?
If I need to work with classes too, do i need copied pointer ?The auto_ptr destructor does deallocate the memory, so you are correct. Once you leave the auto_ptr's scope the thing you're pointing to will go away. You might be looking for something like a shared_ptr, which is a reference counted smart pointer. It will be part of the next C++ standard. Boost has an implementation of it, and it's also part of the TR1 library. If your compiler supports std::tr1 entities then you should have the shared_ptr.
Edit
As pointed out in comments, auto_ptr copy semantics cause a transfer of ownership that does not necessarily result in deletion of the object. So, an auto_ptr type variable can be assigned to another, and could be used as a function return value. The key with auto_ptr is that only one of them at a time can reference a particular entity.
I think I was assigning the traits of scoped_ptr to auto_ptr incorrectly and a little unfairly. My own bias is against auto_ptr because that transfer of ownership causes a side effect on the source object that is not normally associated with copying.
You aren't required to use pointers in C++ in many cases, so you may not need any kind of smart pointer:
struct Foo {
int bar;
int twice_bar()
{
return 2 * bar;
}
};
int twice_x(int x)
{
Foo f;
f.bar = x;
return f.twice_bar();
}
精彩评论