I have a class PackageSingleton and got a function getPackage whose return type is another class Package.
1 2 3
class PackageSingleton{
Package getPackage()
}
This function iterates over a queue and retrieves a package and executes it.
If a queue is empty i want to return nothing and keep looping the queue until a package is found.
1 2 3 4 5 6 7
Package PackageSingleton::getPackage
{
if (isEmpty()) {
std::cout << "Queue is empty" << std::endl;
return Package(); // I want to return nothing here
}
In C++ NULL cant be returned and to return a nullptr i have to change the class to return a pointer and i dont want to do that.
Any idea how should i handle this situation??
PS: I am not allowed to use any library like std::optional etc also
You only choices are
* Use std::optional.
* Write your own, equivalent, version of std::optional.
* Return a pointer.
* Return an invalid instance of Package (e.g. Package::Package(const InvalidPackage &) constructs an invalid instance) and add a function member that tests validity.
If you return a pointer you need to think about the lifetime of the object. Where is the object stored and who is responsible for destroying it?
Another option is to let the caller pass in a Package that the function can modify. The function could then use the return value to tell whether or not the package was successfully updated.