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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With