是否可以返回指向类中声明的结构的指针

Is it possible to return a pointer to a struct declared in a class?

本文关键字:声明 结构 指针 返回 是否      更新时间:2023-10-16

以下代码

class Test{
private:
    struct Node{
        int element;
        Node* next;
    };
    Node* stupidFunction(); // Line 8
};
///////////////////////////////
struct Node;
Node* Test::stupidFunction(){ // Line 15
    Node foo;
    return &foo;
}
///////////////////////////////
int main(){}

将不会编译并给出以下错误消息:

Line 15: error: prototype for 'Node* Test::studpidFunction()' does not match any in class 'Test'
Line 8: error: candidate is: Test::Node* Test::stupidFunction()

是无法返回指向类中声明的结构的指针,还是我做错了什么?

由于它是在Test内部定义的,Node是一个嵌套类型,即 Test::Node .因此,(非内联)函数定义必须编写为

Test::Node* Test::stupidFunction() {

但是,返回局部变量地址的实现严重不正确。变量,这里foo,一旦函数返回就会超出范围,因此调用者留下了一个错误的指针。

一种选择如下

Test::Node* Test::stupidFunction() {
  Node * pNode = new Node;
  // update pNode
  return pNode;
}

但是,此设计也存在一个问题,即调用方必须确保返回指针在超出范围之前delete -ed。否则,new Node分配的内存将被泄漏。

更好的选择是使用智能指针

std::shared_ptr<Test::Node> Test::stupidFunction() {
  auto pNode = std::make_shared<Test::Node>();
  // update pNode;
  return pNode;
}

这样,调用方就不需要显式delete。一旦没有指向此资源的指针,内存就会释放,即 Node .

结构节点在测试类中定义

class Test{
private:
    struct Node{
        int element;
        Node* next;
    };
    Node* stupidFunction(); // Line 8
};
///////////////////////////////
struct Node;
Test::Node* Test::stupidFunction(){ //use Node which define in class Test
    Node foo;
    return &foo;
}
int main(void)

对于多样性,以下作品

auto Test::stupidFunction() -> Node*