c++ - 隐式构造函数与 "empty"构造函数

标签 c++ constructor

在下面的代码中,除了构造函数之外,模板结构BB和CC几乎完全相同。模板 BB 使用什么都不做的构造函数,而模板 CC 使用默认构造函数。当我使用 Visual Studio 2013 update 4 编译它时,在声明 constInst2 的行中抛出错误,但在声明 constInst 的行中没有抛出错误:

error C4700: uninitialized local variable 'instance2' used"

我在初始化“实例”时也预料到了同样的错误。我误解了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;
}

最佳答案

Visual Studio 中有一个编译器标志将警告视为错误 (/WX)。您可以关闭该标志以不将警告视为错误。您还可以选择忽略特定警告(/wd4100 以禁用警告 C4100)。

您看到的是被视为错误的编译器警告。

这与标准引用的解释无关。

如果是

BB< AA > instance;

编译器不会发出警告消息,因为您可能在构造函数中执行了一些有副作用的操作。编译器选择不深入研究构造函数是如何实现的细节来推断调用构造函数是否有副作用。

如果是

CC< AA > instance2;

能够推断出构造对象没有副作用。

关于c++ - 隐式构造函数与 "empty"构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27237022/

相关文章:

c++ - 以 root 身份运行时 setlocale() 返回 'C'

c++ - 将现有函数复制到内存缓冲区

c++ - 在 qml 列表中显示查询结果

c++ - 了解线程构造函数的基础知识

design-patterns - 什么时候使用工厂模式而不是重载的构造函数来实例化对象更有意义?

C++:构造函数没有匹配的函数调用?

C++ Pig Latin 不工作

c++ - 如果存在则调用成员函数,回退到自由函数,反之亦然

c++ - (C++) 使类静态 : put the constructor as private or delete it publically? 时什么更好

java - 在 Java 中运行构造函数代码之前字段是否已初始化?