4 ms·
One of my pet peeves in C++ is seeing: std::string s = ""; It causes calls to strlen and potentially memory allocations. Just use the default constructor!
by hermitdev 10y ago
One of my pet peeves in C++ is seeing:
std::string s = "";
It causes calls to strlen and potentially memory allocations. Just use the default constructor!
- MereInterest 10y agoAbsolutely agreed that the default constructor is better style, but won't it be optimized down to the same code anyways?
- sqeaky 10y agoIt used to, but it doesn't anymore, presuming you use a reasonably recent compiler. If you enable optimizations the assembly for that snippet and the default constructor are identical, I last checked on some GCC 5 flavor, but I think it was like this all the way back in GCC 3 something. Compilers can do some pretty fancy things with literals because they know they optimize constants known at compile time.
- hermitdev 10y agoI just started using GCC 5.4 - I'll have to check again. Last I checked was around 4.8, and it was still generating sub optimal code with the empty literal.
- sqeaky 10y agoEnabling the optimizations is important too. If you leave it on the defaults it does a very direct translation to machine code. GCC 7 is available for use now.