std::optional::reset(3)
π std::optional::reset(3) π
hey bestie π welcome to the C++ Standard Libary manual β yes, βLibaryβ is exactly how the header spells it, and we are respecting the typo in this house π«Άβ¨. This page is all about std::optional::reset, aka the βbye, valueβ button for your optional. sheβs lowkey iconic π
.
β¨ NAME β¨
std::optional::reset β std::optional::reset. Thatβs it. Thatβs the name. She said what she said π.
π Synopsis π
void reset() noexcept; (since C++17)
(constexpr since C++20)
Okay so hereβs the tea β: if *this contains a value, reset() destroys that value as if by value().T::~T(). Otherwise, there are no effects. No drama, no leftovers β¨. After this call, *this does not contain a value. Thatβs the whole plot β she clears the slot and leaves it empty, periodt π
.
Sheβs been around since C++17 and got her constexpr glow-up since C++20, and the signature literally has noexcept on it. Slay π«Ά.
π» Example π»
// Run this code
#include <iostream>
#include <optional>
struct A
{
std::string s;
A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; }
~A() { std::cout << " destructed\n"; }
A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; }
A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; }
A& operator=(const A& other)
{
s = other.s;
std::cout << " copy assigned\n";
return *this;
}
A& operator=(A&& other)
{
s = std::move(other.s);
std::cout << " move assigned\n";
return *this;
}
};
int main()
{
std::cout << "Create empty optional:\n";
std::optional<A> opt;
std::cout << "Construct and assign value:\n";
opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec.");
std::cout << "Reset optional:\n";
opt.reset();
std::cout << "End example\n";
}
π€ Output π€
Create empty optional:
Construct and assign value:
constructed
move constructed
destructed
Reset optional:
destructed
End example
the leading spaces in that output are not a glitch, bestie β theyβre part of the example strings, iykyk β¨. The whole story is giving βconstruct, move, destruct, reset, destruct againβ and honestly? cinema π.
π©Ή Defect reports π©Ή
The following behavior-changing defect reports were applied retroactively to previously published C++ standards β historic glow-up behavior π :
- DR:
P2231R1β Applied to: C++20. Behavior as published:resetwas notconstexprwhile non-trivial destruction is allowed inconstexprin C++20. Correct behavior: madeconstexpr.
π See also π
operator=β assigns contents (public member function). Sheβs the other public member function who assigns contents, and sheβs also invited to the group chat π.
source/version: http://cppreference.com, dated 2024.06.10, for std::optional::reset(3) β thatβs the whole footer, bestie, and she ate πβ¨π«Ά
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms