Is there a way to return null instead of a custom object (not a pointer)?

Is there a way to do what I'm trying to do without using pointers or links?

Here is the code:

Node getSmallest() { if (openList.empty()) return 0; // syntax error // some other code } 
+4
source share
4 answers

It seems you want to return a copy of the Node object when your code is successful.

 struct Node{ int a; bool isEmpty_; Node(bool isEmpty):isEmpty_(isEmpty) }; Node getSmallest() { if (openList.empty()) return Node(false); // some other code } 

There is no other way, you have to return an object that inside could have the isEmpty flag to indicate an error.

+3
source

You can use boost::optional to return an optional value. Or wait C ++ 14 and use std::optional .

+7
source

Yes. You can create an exception.

+6
source

The return type of your getSmallest () function is defined as a Node object, which in C ++ means that the return expression must be of Node type, and at run time the memory of the returned object will be copied back to the caller.

Since you cannot return the integer 0.

Instead, you can define a specific instance object for a Node that represents a NULL Node. This mainly depends on the definition of Node, assuming the following:

 class Node { // Some representative field int a; // Some basic constructor Node(int a){ this->a = a; } } 

You can define a NULL Node in the same way as:

 class Node { // Some representative field int a; // Some basic constructor Node(int a){ this->a = a; } static Node NULL_NODE(-1); } 

The above example assumes that you really never set field a to -1 in other Node objects. If -1 does not match your goal, you can choose a value that is supposed to never be used. If you have multiple fields in Node, you can represent NULL_NODE with a combination of values.

EDIT: As innosam points out, you can also (and probably better) add a boolean field to the Node class to represent if Node is NULL or.

Using the above, you can implement your function as follows:

 Node getSmallest() { if (openList.empty()) return Node.NULL_NODE; // syntax error // some other code } 

Otherwise, you can use a third-party tool that allows you to do the same. See other people's answers in this case.

+2
source

Source: https://habr.com/ru/post/1495187/


All Articles