Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::auto_ptr as a parameter of function?

Tags:

c++

auto-ptr

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.

like image 611
Romz Avatar asked Feb 26 '26 03:02

Romz


1 Answers

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.

like image 58
mfontanini Avatar answered Mar 01 '26 16:03

mfontanini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!