Yes, std::optional
can be used with pointers. This is particularly useful when you want to express that a pointer might be null, without the risk of null pointer dereferences.
Here's an example of how you might use std::optional
with a pointer:
#include <iostream>
#include <optional>
class Player {
public:
Player(const std::string& name) : name(name) {}
std::string name;
};
int main() {
std::optional<Player*> player;
// Player does not exist yet, player is nullopt
if (!player) {
std::cout << "Player does not exist\n";
}
// Create an object and assign it to player
Player real_player("Hero");
player = &real_player;
// Player exists, we can access it
if (player) {
std::cout << "Player name: "
<< (*player)->name << '\n';
}
// Reset player to nullopt
player = std::nullopt;
// Player does not exist anymore
if (!player) {
std::cout << "Player does not exist\n";
}
}
This will output:
Player does not exist
Player name: Hero
Player does not exist
When using std::optional
with pointers, you need to be careful about the lifetime of the pointed-to object. In the example above, real_player
must outlive player
, otherwise player
will be left pointing to an object that no longer exists.
Also, when accessing the pointer in an std::optional
, you need to first dereference the optional (using *
) and then dereference the pointer (using ->
or *
).
Using std::optional
with pointers can help make your code more expressive and safer by explicitly representing the possibility of a null pointer.
Answers to questions are automatically generated and may not have been reviewed.
std::optional
A comprehensive guide to using std::optional
to represent values that may or may not be present.