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.
Asked
Active
Viewed 85 times
-2
-
3Can you use `std::optional`? – NathanOliver May 04 '18 at 15:38
-
1Had you scrolled down to the second answer, you would have found the solution. – Baum mit Augen May 04 '18 at 15:41
-
I find it hard to believe that searching `C++ return optional` would not have already resolved this for you. – underscore_d May 04 '18 at 15:41
1 Answers
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
-
1Btw, 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