Using the element initialization list,
#include <string> struct Fred { Fred() : x_("hello") { } std::string x_; }; int main() { Fred fred; }
Clang 3.9.1 and gcc 6.3 generate the following using -O3 -fno-exceptions ( Compiler Explorer ):
main:
If we perform an assignment in the body:
#include <string> struct Fred { Fred() { x_ = "hello"; } std::string x_; }; int main() { Fred fred; }
both generate a lot more code, for example. Clang 3.9.1 displays this:
main: # @main push rbx sub rsp, 32 lea rbx, [rsp + 16] mov qword ptr [rsp], rbx mov qword ptr [rsp + 8], 0 mov byte ptr [rsp + 16], 0 lea rdi, [rsp] xor esi, esi xor edx, edx mov ecx, .L.str mov r8d, 5 call std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_replace(unsigned long, unsigned long, char const*, unsigned long) mov rdi, qword ptr [rsp] cmp rdi, rbx je .LBB0_2 call operator delete(void*) .LBB0_2: xor eax, eax add rsp, 32 pop rbx ret .L.str: .asciz "hello"
So, it seems that init member lists are indeed more efficient, at least for some cases, even with modern compilers.
emlai
source share