如何将元素添加到由智能指针组成的数组中

时间:2019-04-17 12:24:46

标签: c++ smart-pointers

如何访问由智能指针管理的数组的元素?

我遇到错误

  

struct没有成员xadj

我在下面提供了一些代码。

我这里有关于智能指针的文档 https://www.internalpointers.com/post/beginner-s-look-smart-pointers-modern-c

struct GraphStructure
{
std::unique_ptr<idx_t[]>  xadj;

GraphStructure() {

    //xadj = new idx_t[5];
    std::unique_ptr<idx_t[]>  xadj(new idx_t[5]);

}   

void function(GraphStructure& Graph) {
int adjncyIndex = 0;
int xadjIndex = 0;
Graph.xadj[xadjIndex] = adjncyIndex;
}

1 个答案:

答案 0 :(得分:1)

您似乎对变量在c ++中的工作方式有误称。在您的示例中,您有2个名为xadj的不同类型的不同对象,其中一个阴影另一个:

struct GraphStructure {
idx_t* xadj; // A class member object named xadj of type idx_t*                    
GraphStructure() {


    std::unique_ptr<idx_t[]>  xadj(new idx_t[5]);  // A function scope object called xadj 
                                                   // that shadows the one above
} // At the end of this scope the xadj unique pointer is destroyed

...
void function(GraphStructure& Graph) {
    Graph.xadj[xadjIndex] = adjncyIndex; // Here you use the idx_t* xadj which cannot be 
                                         // accessed with operator[], only by derefencing 
                                         // (with ->). Even if you did use this accessor,
                                         // it would be undefined behaviour because xadj is
                                         // not initialized.

您可能正在寻找的东西是这样的:

struct GraphStructure {
    std::unique_ptr<idx_t[]> xadj;     
    GraphStructure() : xadj(new idx_t[5]) {}
};