How can I return a data type other than function type in C++?

时间:2016-10-20 18:35:19

标签: c++ type-conversion

I'm trying to build a Tree for practicing searching algorithms and I need to access a null pointer in order to make sure a particular node is empty upon creation... However, I can't figure out how to get a null pointer to return from a T& type function. Right now I have the nullptr defined as a standard

int * key = 0;

The function that needs to access and return a nullptr is

T& getData() { ... }

I looked into implicit conversion, but I am not sure if that's the right way to go, or even how to do it. Also, it might be useful to know that I have to build everything in a single header file and the main file can't be changed. Thanks in advance for any insight that can help me to understand how to approach this!

2 个答案:

答案 0 :(得分:1)

A function that returns a T& must return a reference to a T, and references cannot be NULL. As such, you cannot return NULL - you would effectively have to return *NULL;, which for obvious reasons is invalid.

You have a few options:

  1. Convert the T& to a T*. You may then return NULL or nullptr. I would suggest avoiding 0 as a symbol for a NULL, as it is potentially confusing.
  2. Throw an exception. If getData() is supposed to return a reference to data, it might be fair to assume getting data that does not exist (to provide a reference for) is undefined behavior/a bug and can be treated as such.
  3. Depending on what T actually is (is this really a template, or is T just shorthand?), you could create a "NullType" for that type. For example, you might have a Data isa DataInterface, and NullData isa DataInterface.
  4. In some very rare cases, returning a reference to some sort of "dead" data (think /dev/null) is an option. I doubt it is in this case, as you likely want to know that the value returned was invalid; however, in cases where data absolutely must be returned and you have no data, creating a static object to return in these cases can be a trick to pair with error reporting.

I would say the only particularly good option you have is the one you have ruled out, #1.

答案 1 :(得分:0)

However, I can't figure out how to get a null pointer to return from a T& type function.

You cant. If the function is delcared to return a reference to a T, it has to return a reference to a T not a pointer.

(...unless T is a pointer type, e.g. int* but the you still have to return a reference to a int*.)

If you want to have the option to return "nothing" from the function, then make it return a pointer, because references (in contrast to pointers) always reference something.

PS: I hope you are not doing something similar to this:

T& getData() {
    T data = T(....);
    return data;   // BOOM // dont do this
}