The following code
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(){}
will not compile and gives the following error messages:
Line 15: error: prototype for 'Node* Test::studpidFunction()' does not match any in class 'Test'
Line 8: error: candidate is: Test::Node* Test::stupidFunction()
Is it not possible to return a pointer to a struct declared in a class, or am I doing something wrong?
Since it is defined inside Test
, Node
is a nested type, ie Test::Node
. So, the (non-inline) function definition must be written as
Test::Node* Test::stupidFunction() {
However, the implementation, returning the address of a local variable, is seriously incorrect. The variable, here foo
, goes out of scope as soon as the function returns and hence the caller is left with a bad pointer.
One option is the following
Test::Node* Test::stupidFunction() {
Node * pNode = new Node;
// update pNode
return pNode;
}
However, this design too has an issue that the caller must ensure the return pointer is delete
-ed before it goes out of scope. Otherwise the memory allocated by new Node
would be leaked.
A better option is to use a smart pointer
std::shared_ptr<Test::Node> Test::stupidFunction() {
auto pNode = std::make_shared<Test::Node>();
// update pNode;
return pNode;
}
This way, the caller does not need explicit delete
. The memory is released as soon as there is no pointer left that points to this resource, ie Node
.
the struct node is define in Test Class
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*
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.