-2

I have a function that returns an object (an object representing a record in a database), but if the requested data are not present in the DB, it should return a NULL value. According to this answer, is not possible to set an object NULL, but it is possible to return a pointer to the object and the pointer can be NULL. So I did it on my method, but - as the pointer is a local object - the applications does not work as expected (actually, it does work on Windows, but not in Linux). After investigating the issue, I found that returning a pointer to a local variable is not a good idea. What is the best solution to handle my case? Using a smart pointer seems to me overcomplicated for this case.

Giorgio R
  • 85
  • 1
  • 9

1 Answers1

3

You can use std::optional (or boost::optional) to represent a value that might exist or not exist without requiring any dynamic allocation.

std::optional<int> read_from_database(const std::string& id)
{
    return db.has(id) ? std::optional<int>{} : db.get(id); 
}
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • 1
    Btw, there is not need to repeat the type here. See [Return Optional value with ?: operator](//stackoverflow.com/a/45390238) Not that it matters much in this simple case of course. – Baum mit Augen May 04 '18 at 15:43