Say I have a class A
, that consumes messages of a network. Class A
has 2 members b
and c
of corresponding type B
and C
. The members can only be initialized with information, that comes from the network.
Is there a way to initialize the members at a later point, without having the members to be of type B*
and C*
(initialize with nullptr and set the wanted value later)?
I feel like in such a scenario the design has a flaw, but I am still asking myself what the best practice would be, as I am kind of sluggish when using pointers after reading Why should I use a pointer rather than the object itself? ?
CodePudding user response:
std::optional<T>
is a "nullable" wrapper around a type T
. It acts a bit like a pointer in syntax, but there is no dynamic allocation.
std::optional<int> bob;
if (bob) // is there anything in the box?
std::cout << *bob; // print what is in the box.
You can do:
bob = 7; // Assign 7 to what is in `bob`, or construct with a 7.
bob.emplace(3); // construct the contents of `bob` with the value 3
When reading, you can do:
std::cout << bob.value_or(-1);
which either prints the value in bob
, or (a T
constructed from) -1
if there is nothing there.