In many cases I would like to pass reference to const string parameter with default being empty string.
void func(std::string const& z = std::string());
I am wondering how expensive is calling default constructor vs. passing reference to some static empty string?
void func(std::string const& z = my_staticEmptyStr);
What about lists and vectors?
Update. Unfortunately, I do not see a nice generic way to have static empty-xxx objects, except having its own copy in every class that needs it. Fortunately, it seems to me that none of the default constructors for stl classes require memory allocations, so I decided to do it in a traditional way on all paths except frequently called ones.
It depends on the implementation. If the string in your standard library uses the "small string optimization" (which most modern libraries do), string
s default constructor might be as small as three instructions. (zeroing three words).
vector
and list
can also be very cheap to initialize, but it depends on the implementation.
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