是否可以返回指向类中声明的结构的指针
Is it possible to return a pointer to a struct declared in a class?
以下代码
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*
相关文章:
- 在哪里声明结构运算符重载
- 如何正确转发声明结构"using XXX"?
- 在C++我可以在不在本地声明结构的情况下将结构作为指针传递吗?
- 在 for 循环中声明结构是否合法C++?
- 为什么我们可以创建一个模板类结构,其中包含许多与声明结构时指定的参数不同的参数
- 当声明结构数组时,CPPCHECK停止对整个文件的分析
- C++ - 声明结构和类时不允许使用不完整的类型
- 在声明末尾或 main 中声明结构或类实例之间的区别
- 在模板类中声明结构,未为成员函数定义
- C++ .h 文件中转发声明结构,并在.cpp文件中定义结构
- 如何在C++中声明结构变量
- 在 C 中声明结构的新实例
- 在类内部声明结构
- 为什么可以用相同的名称声明结构和非结构
- 在结构定义内部声明结构的堆栈
- 为什么在声明结构时不能初始化结构中的向量成员?
- 在c++头文件中声明结构体
- 如何声明结构体?
- c++中声明结构体的问题
- 只在库cpp中有定义的前向声明结构