STL push_back优化导致数组下标高于数组边界

Dan*_*Lin 8 c++ stl g++

测试环境:

  • CentOS 7.0 g ++ 4.8.2
  • Arch Linux g ++ 4.9.0 20140604(预发布)
  • Arch Linux g ++ 4.9.1

编译命令案例:

  1. 通过:g ++ -Wall t.cpp
  2. 失败:g ++ -Wall -O2 t.cpp
  3. 通过:g ++ -Wall -O2 t.cpp#并在第13行用3替换2
  4. 通过:g ++ -Wall -O2 t.cpp#并注释掉第14行
  5. 通过:g ++ -Wall -O2 --std = c ++ 11 t.cpp#for g ++ 4.8/4.9

失败的消息:

t.cpp: In member function ‘void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vecto
<_Tp, _Alloc>::iterator, const _Tp&) [with _Tp = Object; _Alloc = std::allocator<Ob
ject>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Object*, s
td::vector<Object> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = Object*]’
t.cpp:17:15: warning: array subscript is above array bounds [-Warray-bounds]
     ~Object() {};
               ^
t.cpp:17:15: warning: array subscript is above array bounds [-Warray-bounds]
Run Code Online (Sandbox Code Playgroud)

t.cpp

#include <vector>                      
class TestCls {                        
public:                                
    TestCls() {};                      
    virtual ~TestCls() {};             
};                                     
class TestCls1 : public TestCls        
{                                      
};                                     
class Object {                         
public:                                
    TestCls    m_member[2];            
    TestCls1   m_member1[2]; // LINE 13, if change to [3] it works.
    TestCls1   m_member2[2]; // LINE 14, if comment out this line, it works.

    Object() {};                       
    ~Object() {}; // LINE 17 the warning line                     
};                                     
class Container {                      
public:                                
    std::vector<Object> m_obj;         

    Container() {};                    
    ~Container() {};                   
};                                     
int main() {                           
        Container con;                 
        Object obj;                    
        con.m_obj.push_back(obj);      
}                                      
Run Code Online (Sandbox Code Playgroud)

Dan*_*Lin 0

我找到了解决办法,但不知道原因。

// ...
class Object {
public:
    // ...
    ~Object();
};
Object::~Object() {}; // move to outside LINE 19
//...
Run Code Online (Sandbox Code Playgroud)