Implicit constructor versus “empty” constructor

可紊 提交于 2019-12-12 11:24:26

问题


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:


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.



来源:https://stackoverflow.com/questions/27237022/implicit-constructor-versus-empty-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!