Pregunta

I have been reading up on the c++ auto_ptr and unique_ptr and stuff and thought to try and use them in a class I am playing with... but I was having trouble getting it to work...

How would I convert these pointers to auto pointers or some equivalent so the deletion of the pointers is handled automatically?

Header - http://ideone.com/Z9bc5 Body - http://ideone.com/WfwBY

At the moment it is working using normal pointers but I sometimes get a access violation error. I am pretty sure I know what it causing it.. but the "best" way might be to use the automatic deletion stuff recently added to c++11?

Thanks in advance.

¿Fue útil?

Solución

Don't use auto_ptr. Try one of unique_ptr or shared_ptr. Here's Sutter explaining when to use which:

When in doubt, prefer unique_ptr by default, and you can always later move-convert to shared_ptr if you need it. If you know from the start you need shared ownership, however, go directly to shared_ptr via make_shared (see #2 below).

Also from his blog-post:

3. What’s the deal with auto_ptr?

auto_ptr is most charitably characterized as a valiant attempt to create a unique_ptr before C++ had move semantics.

auto_ptr is now deprecated, and should not be used in new code. When you get a chance, try doing a global search-and-replace of auto_ptr to unique_ptr in your code base; the vast majority of uses will work the same, and it might expose (as a compile-time error) or fix (silently) a bug or two you didn’t know you had.

So, your member declarations change from:

 sf::Texture * tSpriteSheet;

to:

 std::unique_ptr<sf::Texture> tSpriteSheet;

As for member functions which return a raw pointer you have but the obvious choice: You cannot return a unique_ptr if the class is not movable. So, you can either:

  • Keep the signature as-is
  • Return a const& unique_ptr<T>
  • Return a reference to the object

Choose the one that suits your needs the best.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top