Implicit constructor versus empty constructor

In the following code, the pattern structures of BB and CC are almost identical, with the exception of the constructors. The BB pattern uses a constructor that does nothing, while the CC pattern uses a default constructor. When I compile it using Visual Studio 2013 update 4, an error appears in the line declaring constInst2 , but not in the line declaring constInst :

error C4700: uninitialized local variable 'instance2' is used

I expected the same error when initializing the "instance". Am I misinterpreting this sentence ?

"If the implicitly declared default constructor is not deleted or trivial, it is determined (that is, the function body is generated and compiled) by the compiler, and it has the same effect as a user-defined constructor with an empty body and an empty initializer list."

 struct AA { typedef int a; typedef const int b; }; template< typename A > struct BB { typename A::a a_A; typedef typename A::b a_B; BB() {}; }; template< typename A > struct CC { typename A::a a_A; typedef typename A::b a_B; CC() = default; }; int main() { BB< AA > instance; BB< AA >::a_B constInst( instance.a_A ); CC< AA > instance2; CC< AA >::a_B constInst2( instance2.a_A ); return 0; } 
+5
source share
1 answer

Visual Studio has a compiler flag for handling warnings as errors (/ WX). You can disable this flag so that warnings are not treated as errors. You can also ignore specific warnings (/ wd4100 to disable the C4100 warning).

What you see is a compiler warning, which is seen as an error.

This is not related to the interpretation of the quotation from the standard.

When

 BB< AA > instance; 

the compiler does not give a warning message, because you can do something in a constructor that has side effects. The compiler prefers not to delve into the details of how the constructor is implemented to determine whether the calling constructor has side effects or not.

When

 CC< AA > instance2; 

he can deduce that there are no side effects of building the object.

+1
source

Source: https://habr.com/ru/post/1208080/


All Articles