Вопрос

I need to use RAII idiom, am I doing it right ?:

std::auto_ptr<std::vector<string>> MyFunction1()
{
   std::auto_ptr<std::vector<string>> arrayOfStrings;

   MyFunction2(arrayOfStrings); // work with arrayOfStrings

   return arrayOfStrings;
}

void MyFunction2(std::auto_ptr<std::vector<string>> array)
{
   auto_ptr<string> str;
   *str = "foo string";
   array.push_back(str)
}

Or maybe shoudl I free the memory by myself instead of using smart pointers ? If so, how to do that ? Thanks in advance.

Это было полезно?

Решение

Just don't use pointers, not even smart ones in this case:

std::vector<string> MyFunction1()
{
   std::vector<string> arrayOfStrings;
   MyFunction2(arrayOfStrings); // work with arrayOfStrings
   return arrayOfStrings;
}

void MyFunction2(std::vector<string> &array)
{
   array.push_back("foo string");
}

The compiler will surely optimize the return value copy away, applying an optimization called Return Value Optimization, so you shouldn't worry about that. Using pointers, in this case, to avoid copying will probably end up being more inefficient and tedious to work with, compared to using objects allocated on the stack and relying on this optimization.

Otherwise, consider using std::unique_ptr as @templatetypedef mentions. Avoid pointers whenever you can.

Другие советы

If you have a function that takes a std::auto_ptr by value, then whatever std::auto_ptr that you pass into that function will relinquish control of the resource and hand it off to the function that it calls. As a result, when the function returns, the original std::auto_ptr will no longer point to the resource it originally pointed to. As a result, you can think of taking in a std::auto_ptr by value as saying "I am going to take your resource away from you and do something with it."

To fix this, consider making your function take the std::auto_ptr by reference, which doesn't steal the reference.

But that said, you should stop using std::auto_ptr and start using std::unique_ptr instead. std::unique_ptr is a much safer and more sane replacement for std::auto_ptr. You can't pass std::unique_ptr by value without explicitly using std::move to relinquish control of the resource, and there aren't any "gotcha!"-style surprises with it.

Hope this helps!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top