Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly return null/empty object in C++?

Tags:

c++

I am a Java developer trying to solve a simple C++ task. In Java, if I want to return an empty/null object, to indicate that object is not found I just return null. Example:

Person getGetByName(String name) {

    for (int i = 0; i < 10; i++) {
        if (people[i].name == name) {
            return people[i];
        }
    }
    return null;
}

later in code I can do

Person p = getByName("Sam");

if (p == null) { ...
}

In C++ I have the following method

It seems that if I declare a method like the above, returning NULL is not an option since the method doesn't return a pointer but rather a class. So what do I return to indicate that no person is found ?

like image 690
Adelin Avatar asked Oct 21 '25 17:10

Adelin


2 Answers

If you're using C++17 or above, use std::optional.

Alternatively, return a value that would convey a similar meaning, e.g. a std::pair<bool, Person> Note that this would still require a Person object to be there, it merely does not need to be valid. If the objects are too large to be returned emptily like that, you'll have to find a workaround, like a union, or a pointer.

like image 83
IWonderWhatThisAPIDoes Avatar answered Oct 23 '25 07:10

IWonderWhatThisAPIDoes


There's one more problem to the above code - the C++ version is inefficient. In C++, returning Person by-value always returns a copy of it (except for RVO, which is not applicable here).

Unlike C++, Java has no value semantics for objects, in Java returning Person always returns a reference to an object. A reference in Java works more like a pointer in C++, e.g. it can be null.

So the equivalent C++ code would actually be:

Person* getGetByName(std::string const& name) {
  for(int i = 0 ;i<10 ;i++) { 
    if(people[i].name == name){
      return &people[i]; 
    }  
  }
  return nullptr;
}

Now you can do

Person* p = getGetByName("blah");
if (p == nullptr) {
  // not found ...
} else {
  // use p->name etc.
}

C++ has no automatic memory management. The lifetime of the people vector must thus outlast the returned pointer. If that's not the case then it's more idiomatic to work with smart pointers instead (e.g. unique_ptr or shared_ptr). Thinking about object lifetimes is the responsibility of the C++ developer.

like image 31
rustyx Avatar answered Oct 23 '25 08:10

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!