Magic Statics

As mentioned in the C++11 Core Language Features Table: Concurrency table, the Magic statics feature is supported under Visual Studio 2015.

Beware that this does not apply to non-local statics (e.g global static variables) and if you’re rightfully concerned about the order of such statics initialization when one depends on the other, a solution is to wrap their access in a static function:

static std::string const & GetString() {
    static std::string const s{"OperationResult"};
    return s;
}

The assembly that protects the static is:

; 8 : static std::string const s{"OperationResult"};

mov eax, DWORD PTR __tls_index
mov ecx, DWORD PTR fs:__tls_array
mov edx, DWORD PTR [ecx+eax*4]
mov eax, DWORD PTR ?$TSS0@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4HA
cmp eax, DWORD PTR __Init_thread_epoch[edx]
jle SHORT $LN2@GetString
push OFFSET ?$TSS0@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4HA
call __Init_thread_header
add esp, 4
cmp DWORD PTR ?$TSS0@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4HA, -1
jne SHORT $LN2@GetString
mov DWORD PTR __$EHRec$[ebp+8], 0
push OFFSET ??_C@_0BA@PFGBCHGN@OperationResult?$AA@
mov ecx, OFFSET ?s@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4V23@B
call ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@PBD@Z ; std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> >
push OFFSET ??__Fs@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@YAXXZ ; `GetString'::`2'::`dynamic atexit destructor for 's''
call _atexit
add esp, 4
mov DWORD PTR __$EHRec$[ebp+8], -1
push OFFSET ?$TSS0@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4HA
call __Init_thread_footer
add esp, 4

$LN2@GetString:

; 9 : return s;
mov eax, OFFSET ?s@?1??GetString@@YAABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ@4V23@B

Finally, have a look at this nice video: C++ Weekly With Jason Turner – Ep 2 Cost of Using Statics

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s