5
votes

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;
}
1
When asking a question about a specific compiler error, please include the full error message in the question. It helps a lot. - Mark Ransom
@MarkRansom: Updated the question. - Hector
@Hector I took your code verbatim, compiled it with Visual Studio 2013 Update 4, and only received a warning: warning C4700: uninitialized local variable 'instance2' used It also compiles with no issues here: ideone.com/Hc1jB4 - PaulMcKenzie
@PaulMcKenzie: I have "warnings go to errors" settings. In any case, the point is that the warning should also appear in the initialization of 'instance'. - Hector
@Hector - A warning is whatever a compiler thinks is a warning. There is no standard on what a warning should be. There is a standard on what an error should be, and the above code has no errors. - PaulMcKenzie

1 Answers

1
votes

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.