Because I believe that this requires my_var to first be default constructed, and then assigned.
No. Using the =
operator on a variable declaration of a class type has special handling. The compiler will never default-construct-then-copy the variable object like you think. What will actually happen instead is either:
a temp MyClass
object will be copy-constructed from some_data
, then my_var
will be copy-constructed from the temp, then the temp will be freed. As if you had written this:
MyClass my_var(MyClass(some_data));
the compiler will optimize away the temp completely and simply copy-construct my_var
from some_data
directly. As if you had written this:
MyClass my_var(some_data);
This is the usual case, especially if you write this:
MyClass my_var = some_data;
Instead of this:
MyClass my_var = MyClass(some_data);
When my_var is shared memory, this can cause race conditions.
The way you have written it, no. my_var
is either a local variable of a function/method, or it is a global variable. Either way, declaring and assigning a variable in the same statement is not a race condition since the variable cannot be shared until after it has been constructed. If you declare the variable first and assign it in a separate statement, then there would be a race condition.