简体   繁体   English

未初始化的局部变量,默认为c ++ 11

[英]uninitialized local variable with c++11 default

Why does printing bk give a warning when printing ak does not? 打印ak时为什么打印bk会发出警告? I Use VS2013 我使用VS2013

//warning C4700: uninitialized local variable 'b' used
#include<iostream> 

using namespace std;

struct A {
  A() {};
  int k;
};
struct B {
  B() = default;
  int k;
};

int main() {
  A a;
  cout << a.k << endl;
  B b;
  cout << b.k << endl; // this gives a warning, uninitialized local variable

  return 0;
}

Accessing uninitialized variables is undefined behavior and no diagnostic is required. 访问未初始化的变量是未定义的行为 ,不需要诊断。 This means that you can get a warning for bk (MSVC++), for ak (g++) or for neither (Clang). 这意味着您可以获得bk (MSVC ++), ak (g ++)或两者(Clang)的警告。

Standard quotes: 标准报价:

12.6.2 Initializing bases and members [class.base.init] 12.6.2初始化基数和成员[class.base.init]

8 In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then 8在非委托构造函数中,如果给定的非静态数据成员或基类未由mem-initializer-id指定(包括没有mem-initializer-list的情况,因为构造函数没有ctor-initializer然后,实体不是抽象类(10.4)的虚基类

[bunch of non-applicable clauses] [一堆不适用的条款]

— otherwise, the entity is default-initialized (8.5). - 否则,实体默认初始化(8.5)。

8.5 Initializers [dcl.init] 8.5初始值设定项[dcl.init]

7 To default-initialize an object of type T means: 7默认初始化T类型的对象意味着:

[bunch of non-applicable clauses] [一堆不适用的条款]

— otherwise, no initialization is performed. - 否则,不执行初始化。

The 12.6.2/8 quote has this example: 12.6.2 / 8引用有这个例子:

struct C {
    C() { }    // initializes members as follows:
    A a;         // OK: calls A::A()
    const B b;   // error: B has no default constructor
    int i;       // OK: i has indeterminate value // <---------- your code
    int j = 5;   // OK: j has the value 5
};

As per § 8.5 Initializers 按照§8.5初始化程序

if T has a non-trivial default constructor, the object is default-initialized;

Which means both ak and bk are not value initialized, access them are UB 这意味着ak and bk都没有初始化值,访问它们是UB

To initialize A::k , you could put it in member initialize list 要初始化A::k ,您可以将其放在成员初始化列表中

A():k(42) {};

For B::K , you could call it with: 对于B::K ,您可以使用以下方法调用它:

B b = {}; // value initialize  members, k initialized to 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM