简体   繁体   中英

How to return null from a function whose return type is map in Visual C++?

I want to return null data from a function that return type is map.

Here is my code.

map<string, string> something_to_do(string something) { 
    // something to do..
    // if above code is something wrong, it should return null.
    return null;
}

But, there seems to be no type casting to return null in map library.

How can I do it?

(I'm sorry my awful English..)

as an alternative you can in C++17 use instead std::optional

std::optional<std::map<string,string>> something_to_do(string something) {
  std::map<std::string,std::string> yourmap;
  yourmap["a"] = "b";
  ...
  return yourmap;

  // or 
  // return std::null_t;
}

...

auto d = something_to_do(something);
if (d)
{
  auto& m = d.value();
  std::cout << m["a"] << std::endl;
}

If the function returns a map you must return a map - you cannot return nullptr (an empty map , sure, but that's as close as you'll get). Maybe you are looking for std::optional so you can have your function return an optional map that may or may not be there?

I think the functionality you are looking for would be better handled by throwing an exception.

That way you can proceed as normally, but if something goes wrong like you allude to in your comment, then you want to throw an exception and have any client code handle the exception accordingly. See this SO post .

It allows you to write straight-forward code without having custom types to return for every possible situation of your running code. It also eliminates the need to check for certain values being returned just to handle any errors.

To call the function and handle the error, you would simply wrap the method call in a try-catch block:

from @nsanders' orginal answer

 try { compare( -1, 3 ); } catch( const std::invalid_argument& e ) { // do stuff with exception... } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM