类成员没有初始化

时间:2013-11-11 21:20:24

标签: c++ initialization-list

我有以下代码和简单的if语句:if (voxels_)其中voxels_应为NULL失败。代码:

template<class T, typename REAL = float>
class NDIMVoxelStructure
{
public:
    inline NDIMVoxelStructure (): voxels_(NULL){}
    inline virtual ~NDIMVoxelStructure (){ this->clear();}

    /////////////////ERROR occurs at if(voxels_) //////////////////
    inline void 
    clear (){if ( voxels_ ){delete[] voxels_; voxels_ = NULL;}} 


    inline void
    build (const std::vector<REAL> bounds, std::vector<int> num_of_voxels) {
        this->clear();
        // more code
    }

protected:
    T* voxels_;
};

Class ModelLibrary {

    ModelLibrary () {
        hash_table_.build (bounds_vector, num_of_cells_vector);
    }

    struct Quad{
            const ORROctree::Node::Data* first;
            const ORROctree::Node::Data* second;
            const float* f1;
            const float* f2;
    };

    typedef std::list<Quad > quad_list;
    // these two types hide base class types
    typedef std::map<const Model*, quad_list> HashTableCell; 
    typedef NDIMVoxelStructure<HashTableCell, float> HashTable;

protected:
    HashTable hash_table;
};

int main() {
    ModelLibrary library; 
}

我在clear()方法中遇到了段错误。使用gdb我将voxels_的地址设置为0xa,这很奇怪。我正在将其初始化为NULL,因此if (voxels_)应该只返回false。任何想法都会有所帮助。这让我发疯了

1 个答案:

答案 0 :(得分:1)

考虑到这只是真实代码中的“微型”版本。可能是您的实际代码正在调用NDIMVoxelStructure的复制构造函数(例如,通过返回NDIMVoxelStructure元素的函数),然后,voxels_未正确初始化?

在以前的情况下,如果voxels_是一个指针,默认的复制构造函数最初会吞下复制NULL值,但可能还有其他东西可以在后台运行。

我建议也定义NDIMVoxelStructure的复制构造函数,并检查它是否被调用。