【问题标题】:Field initialization in constructor corrupts memory构造函数中的字段初始化会破坏内存
【发布时间】:2014-08-29 07:47:34
【问题描述】:

由于 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) 后内存会损坏?一切看起来都那么简单..

【问题讨论】:

  • 发布一个完整的编译示例。
  • 我很想知道如果初始化列表顺序颠倒(即它与你的类中的 decls 匹配)是否会发生同样的问题。注意:没关系;它们应该始终按照标准按照自上而下的 decl 顺序进行初始化,而不是初始化列表顺序,但我不会让 MS 放弃这个球。

标签: c++ visual-studio unit-testing


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-22
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2010-11-28
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多