简体   繁体   English

Segfault在gtest中初始化堆栈上的参考变量

[英]Segfault initializing reference variable on stack in gtest

I'm creating a test for my TwoDArray container and I'm getting a segfault. 我正在为TwoDArray容器创建一个测试,并且遇到了段错误。 The TwoDArray object initializes fine on the heap but when I try to test it on the stack, I get a segfault. TwoDArray对象在堆上初始化良好,但是当我尝试在堆栈上对其进行测试时,出现了段错误。 It uses a vector on the heap as the underlying container. 它使用堆上的向量作为基础容器。 I initialized a vector perfectly fine but the TwoDArray object gives a segfault as soon as it runs. 我初始化了一个非常好的向量,但是TwoDArray对象在运行时立即给出了段错误。

I've cut out the functions as I'm mostly concerned with initialization. 我已经把函数切掉了,因为我最关心的是初始化。

 21 template<typename T>
 22 class TwoDArray{
 23 
 24   private:
 25     int numRows;
 26     int numCols;
 27     std::vector<T> * vecPtr; // Underlying container
 28 
 29   public:
 30     TwoDArray(){ TwoDArray( DEF_ROW_SIZE, DEF_COL_SIZE ); }

 ...

 40     TwoDArray( int m, int n ):numRows(m), numCols(n),
 41                               vecPtr(new std::vector<T>(m*n)){ }

 ...

 43     /* Destructor that specifies the size of the 2D Array
 44      */
 45     ~TwoDArray(){ delete vecPtr; }
 ...

then the actual test: 然后进行实际测试:

  2 #include <vector>
  3 #include <gtest/gtest.h>
  4 #include "TwoDArray.hpp"
  5 
  6 class TestTwoDArray : public testing::Test{
  7   public:
  8 
  9     TwoDArray<int> arr1;
 10     std::vector<int> vec;
 11 
 12     virtual void SetUp(){
 14     }
 15 
 16     virtual void TestDown(){
 17     }
 18 };
 19 
 20 TEST_F( TestTwoDArray, validSizeTest ){
 21   //arr1 = TwoDArray<int>();
 22   
 24 }
 25 

 30 int main(int argc, char* argv[]){
 31   TwoDArray<int> arr1;
 32   testing::InitGoogleTest(&argc,argv);
 33   return RUN_ALL_TESTS();
 34 }

I have another class that creates the object fine on the heap. 我还有另一个类可以在堆上创建对象。 Here line 9 gives the segfault. 这里的第9行给出了段错误。 But line 31 doesn't. 但是第31行没有。 Maybe I'm not understanding how to initialize something. 也许我不了解如何初始化某些东西。

Your default constructor doesn't do what you think it does. 您的默认构造函数不会执行您认为的操作。 It leaves the various member variables uninitialized, then creates a temporary TwoDArray object. 它使各种成员变量保持未初始化状态,然后创建一个临时的TwoDArray对象。

What you want for a delegating constructor is 您想要的委派构造函数是

TwoDArray(): TwoDArray( DEF_ROW_SIZE, DEF_COL_SIZE ) { }

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

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