Question

I am wary of using = for initializing a new variable:

MyClass my_var = MyClass(some_data);
  1. Because I believe that this requires my_var to first be default constructed, and then assigned.
  2. When my_var is shared memory, this can cause race conditions.

Can someone confirm or deny my fears? Are primitive types treated differently?

Was it helpful?

Solution

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:

  1. 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));
    
  2. 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.

OTHER TIPS

Because I believe that this requires my_var to first be default constructed, and then assigned.

No. my_var is never default constructed, nor is the temporary. An rvalue of type MyClass is first constructed, using some_data, and then the copy constructor (or move constructor if you are in C++11) is called to construct my_var.

When my_var is shared memory, this can cause race conditions.

Well, yes. Theoretically it could cause race conditions.

In your code line, only the copy-constructor of MyClass is called.

If you wrote MyClass my_var and later in the code my_var = some_data, then MyClass::operator=(...) would be called.

To complete this answer, I don't see how a shared variable can be "in risk of a race condition" during construction (becaused it cannot be shared until it has been constructed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top