构造函数中的字段初始化会损坏内存

Field initialization in constructor corrupts memory

本文关键字:损坏 内存 初始化 字段 构造函数      更新时间:2023-10-16

出于某种原因,来自 UNIT 测试的构造函数中的字段初始化会损坏内存。

我有以下课程

//.h 
    class Entity
    {
    public:
...
    Entity();
    private:
        unsigned int _nextOperatorId;
        unsigned int _operators[30][4]; //from consts
... 
    }
//.cpp
Entity::Entity() : _operators(), _nextOperatorId(1)
    {
      /* If i run this from unit test i see:
         _operators [0] 0x0569bb38 {3452816845, 3452816845, 3452816845, 3452816845, 1}
         _operators [1] 0x0569bb4c {3452816845, 0, 0, 0, 0} 
         _operators [2] 0x0569bb4c {0, 0, 0, 0, 0}
        ... (all other rows are zeroes).
        If i delete _nextOperatorId(1) initialiazation, or if i run constructor from       console app, here all as expected - all rows in operators array are zeroes * /   

    }

我在 VS 单元测试类初始值设定项中运行它,如下所示:

private
        Entity* entity;
public:
        TEST_METHOD_INITIALIZE(ClassInitialize)
        {
            entity = new Entity();
        }

那么为什么我加_nextOperatorId(1(后内存会变坏呢?一切看起来都那么简单..

VC++编译器中有一个已知的错误;除非在你的版本中修复了它,否则不幸的是,你不能依靠VC++来按照C++标准的要求对类成员进行值初始化。

http://connect.microsoft.com/VisualStudio/feedback/details/564268/c-value-initialization

https://connect.microsoft.com/VisualStudio/feedback/details/746973/incorrect-c-11-value-initialization-for-type-with-implicitly-declared-but-non-trivial-default-constructor