Reputation: 1615
In my code I use a method getNumberOfP_ForAdd()
. This method opens a file and returns a XMLDocumentWrapper*.
XMLDocumentWrapper* Tab::getNumberOfP_ForAdd()
{
QString defaultName = GuiUtil::getLastPath();
QString fileName = QFileDialog::getOpenFileName(this, "Open " + displayName + " File",
defaultName, displayName + " Files (*." + fileSuffix + ")", 0, 0);
if (fileName.isNull() || fileName.isEmpty()) {
qDebug() << "Load" << displayName << "aborted.";
return NULL;
}
GuiUtil::setLastPath(fileName);
// Open file
XMLDocumentWrapper* inputDoc = XMLDocumentWrapper::readFromFile(fileName);
if (inputDoc == NULL) {
qDebug() << "Load" << displayName << "aborted.";
return NULL ;
}
return inputDoc;
}
When I try to read a file there are 2 things I check first: Wheather
(fileName.isNull() || fileName.isEmpty())
and
(inputDoc == NULL)
If these statements are true I do
return NULL;
Can I simply return a NULL-Ptr or would I run into problems in doing so? Do I have to free that pointer again?
Upvotes: 2
Views: 9863
Reputation: 836
I think that your question in general has been answered, but.... be careful. I know nothing about the XMLDocumentWrapper class. Off hand, I expect that the caller must clean-up (delete) this returned pointer.
Upvotes: 0
Reputation: 26476
You can return a null pointer if your function's return type is a pointer.
If the caller checks the return value and handles the case where the return value is null - then there shouldn't be any problem. if the caller tries to dereference this pointer, then problems do occur.
The fact that the function returns a pointer doesn't necessarily mean the developer needs to free the memory. the pointer could point to anything, including stack and global variables. The developer should look at the function's documentation to make sure what to do with the return value. Anyway, there is no problem in deleting null pointers, but again , one should look if she/he needs to deallocate something at the first place.
Upvotes: 6
Reputation: 15229
You can return a NULL
pointer.
Do I have to free that pointer again?
delete
is only necessary if you allocate space on the free store.
However, if you use C++11 or higher, I recommend the usage of nullptr
instead of NULL
. In this particular code, it doesn't provide a significant improvement but I consider it good style, also to draw the line between C and C++.
Upvotes: 6
Reputation: 65600
Can I simply return a NULL-Ptr?
Yes
Would I run into problems in doing so?
Only if you try to call methods on that pointer, that would be undefined behaviour.
Do I have to free that pointer again?
No, using delete
or free
on a NULL
pointer is valid but unnecessary.
Upvotes: 5