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

问题描述 投票:-2回答:1

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

我收到了一个错误

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;
}
c++ smart-pointers
1个回答
1
投票

看起来你对变量如何在c ++中起作用有误。在您的示例中,您有两个名为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]) {}
};
© www.soinside.com 2019 - 2024. All rights reserved.