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:
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_ptras @templatetypedef mentions. Avoid pointers whenever you can.