Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cost of default constructors for string, list, vector

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.

like image 585
uuu777 Avatar asked Oct 15 '25 14:10

uuu777


1 Answers

It depends on the implementation. If the string in your standard library uses the "small string optimization" (which most modern libraries do), strings 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.

like image 90
Marshall Clow Avatar answered Oct 18 '25 07:10

Marshall Clow



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!