如何
访问由智能指针管理的数组的元素?
我收到错误
结构没有成员 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++ 中的工作方式用词不当。在您的示例中,您有 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]) {}
};