Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit constructor versus "empty" constructor

In the following code, template structures BB and CC are almost identical except for the constructors. Template BB uses a constructor that does nothing whereas template CC uses the default constructor. When I compile it using Visual Studio 2013 update 4, an error is thrown in the line that declares constInst2 but not on the line that declares constInst:

error C4700: uninitialized local variable 'instance2' used"

I expected the same error when initializing 'instance' as well. Am I misinterpreting this sentence?

"If the implicitly-declared default constructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler, and it has exactly the same effect as a user-defined constructor with empty body and 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;
}
like image 423
Hector Avatar asked Nov 10 '22 22:11

Hector


1 Answers

There is a compiler flag in Visual Studio to treat warnings as errors (/WX). You can turn that flag off to not treat warnings as errors. You can also choose to ignore specific warnings (/wd4100 to disable warning C4100).

What you are seeing is a compiler warning that is being treated as an error.

This is unrelated to the interpretation of the quote from the standard.

In case of

BB< AA > instance;

the compiler does not issue a warning message since you could be doing something in the constructor that has side effects. The compiler is choosing not to delve into the details of how the constructor is implemented to deduce whether calling the constructor has side effects or not.

In the case of

CC< AA > instance2;

it is able to deduce that there are no side effects of constructing the object.

like image 72
R Sahu Avatar answered Nov 14 '22 23:11

R Sahu