[英]Segfault initializing reference variable on stack in gtest
我正在為TwoDArray容器創建一個測試,並且遇到了段錯誤。 TwoDArray對象在堆上初始化良好,但是當我嘗試在堆棧上對其進行測試時,出現了段錯誤。 它使用堆上的向量作為基礎容器。 我初始化了一個非常好的向量,但是TwoDArray對象在運行時立即給出了段錯誤。
我已經把函數切掉了,因為我最關心的是初始化。
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; }
...
然后進行實際測試:
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 }
我還有另一個類可以在堆上創建對象。 這里的第9行給出了段錯誤。 但是第31行沒有。 也許我不了解如何初始化某些東西。
您的默認構造函數不會執行您認為的操作。 它使各種成員變量保持未初始化狀態,然后創建一個臨時的TwoDArray
對象。
您想要的委派構造函數是
TwoDArray(): TwoDArray( DEF_ROW_SIZE, DEF_COL_SIZE ) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.