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;
}