Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does default-initializing a non-const reference function parameter from a dynamically allocated dereferenced pointer create a memory leak?

I'm in front of this and will have to deal with C++98, possibly C++03, and C++11 :

type1 myfunc( type2& var = /*some value of type "type2"*/ )
{
   // Some code
}

I tried this :

type1 myfunc( type2& var = *(new type2) )
{
   // Some code
}

And of course it works, but I'm not sure wether this creates or not a memory leak. What does this code exacty do in the computer memory ? If I can't do this, do I have any other solutions than to overload my function?


1 Answers

The question is tagged C++11, so I suppose you can use std::unique_ptr to solve this problem.

A little example

#include <memory>
#include <iostream>

std::size_t myfunc( std::string const & var
   = * std::unique_ptr<std::string>(new std::string("default string")) )
{ return var.size(); }

int main ()
 {
   std::cout << "default:  " << myfunc() << std::endl;
   std::cout << "argument: " << myfunc("no default") << std::endl;

   return 0;
 }

Hoping this helps.

--- added C++98/C++03 solution ---

Isn't clear what language the OP want to use.

In case of C++98/C++03, it's possible to use std::auto_ptr instead of the C++11 std::unique_ptr.

I remember that std::auto_ptr is deprecated from C++11, so use it only if you can't use C++11 (or a newer standard)

The following example should be C++98 compliant (I've removed the const too)

#include <memory>
#include <iostream>

std::size_t myfunc(std::string & var
   = * std::auto_ptr<std::string>(new std::string("default string")) )
{ return var.size(); }

int main ()
 {
   std::string noDef("no default");

   std::cout << "default:  " << myfunc() << std::endl;
   std::cout << "argument: " << myfunc(noDef) << std::endl;

   return 0;
 }
like image 191
max66 Avatar answered Mar 26 '26 21:03

max66



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!