std::variant::operator=(3)
π NAME π
Okay bestie, this is std::variant::operator= β the assignment operator for std::variant β from the std::variant::operator=(3) manual page in the C++ Standard Libary (yes, thatβs literally the spelling on the page π
). Itβs giving βassign a new value to an existing variant object,β and it has three overloads: copy-assignment, move-assignment, and converting assignment. All since C++17, with the converting one getting its constexpr glow-up in C++20. Periodt. β¨
β¨ Synopsis β¨
constexpr variant& operator=( const variant& rhs ); (1) (since C++17)
constexpr variant& operator=( variant&& rhs ) (2) (since C++17)
noexcept(/* see below */);
template< class T >
variant& operator=( T&& t ) noexcept(/* see below */); (3) (since C++17) (until C++20)
template< class T >
constexpr variant& operator=( T&& t ) noexcept(/* see below */); (since C++20)
Assigns a new value to an existing variant object. Slay. π
- Copy-assignment:
- If both
*thisandrhsare valueless by exception, does nothing. - Otherwise, if
rhsis valueless, but*thisis not, destroys the value contained in*thisand makes it valueless. - Otherwise, if
rhsholds the same alternative as*this, assigns the value contained inrhsto the value contained in*this. If an exception is thrown,*thisdoes not become valueless: the value depends on the exception safety guarantee of the alternativeβs copy assignment. - Otherwise, if the alternative held by
rhsis either nothrow copy constructible or not nothrow move constructible (as determined bystd::is_nothrow_copy_constructibleandstd::is_nothrow_move_constructible, respectively), equivalent tothis->emplace<rhs.index()>(*std::get_if<rhs.index()>(std::addressof(rhs))).*thismay becomevalueless_by_exceptionif an exception is thrown on the copy-construction insideemplace. - Otherwise, equivalent to
this->operator=(variant(rhs)). - This overload is defined as deleted unless
std::is_copy_constructible_v<T_i>andstd::is_copy_assignable_v<T_i>are both true for allT_iinTypes.... This overload is trivial ifstd::is_trivially_copy_constructible_v<T_i>,std::is_trivially_copy_assignable_v<T_i>andstd::is_trivially_destructible_v<T_i>are all true for allT_iinTypes....
- If both
- Move-assignment:
- If both
*thisandrhsare valueless by exception, does nothing. - Otherwise, if
rhsis valueless, but*thisis not, destroys the value contained in*thisand makes it valueless. - Otherwise, if
rhsholds the same alternative as*this, assignsstd::move(*std::get_if<j>(std::addressof(rhs)))to the value contained in*this, withjbeingindex(). If an exception is thrown,*thisdoes not become valueless: the value depends on the exception safety guarantee of the alternativeβs move assignment. - Otherwise (if
rhsand*thishold different alternatives), equivalent tothis->emplace<rhs.index()>(std::move(*std::get_if<rhs.index()>(std::addressof(rhs)))). If an exception is thrown byT_iβs move constructor,*thisbecomesvalueless_by_exception. - This overload participates in overload resolution only if
std::is_move_constructible_v<T_i>andstd::is_move_assignable_v<T_i>are both true for allT_iinTypes.... This overload is trivial ifstd::is_trivially_move_constructible_v<T_i>,std::is_trivially_move_assignable_v<T_i>, andstd::is_trivially_destructible_v<T_i>are all true for allT_iinTypes....
- If both
- Converting assignment:
- Determines the alternative type
T_jthat would be selected by overload resolution for the expressionF(std::forward<T>(t))if there was an overload of imaginary functionF(T_i)for everyT_ifromTypes...in scope at the same time, except that:- An overload
F(T_i)is only considered if the declarationT_i x[] = { std::forward<T>(t) };is valid for some invented variablex; - If
*thisalready holds aT_j, assignsstd::forward<T>(t)to the value contained in*this. If an exception is thrown,*thisdoes not become valueless: the value depends on the exception safety guarantee of the assignment called. - Otherwise, if
std::is_nothrow_constructible_v<T_j, T> || !std::is_nothrow_move_constructible_v<T_j>is true, equivalent tothis->emplace<j>(std::forward<T>(t)).*thismay becomevalueless_by_exceptionif an exception is thrown on the initialization insideemplace. - Otherwise, equivalent to
this->emplace<j>(T_j(std::forward<T>(t))).
- An overload
- This overload participates in overload resolution only if
std::decay_t<T>(until C++20)std::remove_cvref_t<T>(since C++20) is not the same type asvariantandstd::is_assignable_v<T_j&, T>is true andstd::is_constructible_v<T_j, T>is true and the expressionF(std::forward<T>(t))(withFbeing the above-mentioned set of imaginary functions) is well formed.
- Determines the alternative type
Also, the lilβ overload-resolution vibe-check examples:
std::variant<std::string> v1;
v1 = "abc"; // OK
std::variant<std::string, std::string> v2;
v2 = "abc"; // Error
std::variant <std::string, bool> v3;
v3 = "abc"; // OK, chooses string; bool is not a candidate
std::variant<float, long, double> v4; //holds float
v4 = 0; // OK, holds long; float and double are not candidates
π Parameters π
rhsβ anothervarianttβ a value convertible to one of thevariantβs alternatives
π«Ά Return value π«Ά
*this β it returns itself, main-character energy only. π
π Exceptions π
- May throw any exception thrown by assignment and copy/move initialization of any alternative.
noexceptspecification:
noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...))
noexceptspecification:
noexcept(std::is_nothrow_assignable_v<T_j&, T> &&
std::is_nothrow_constructible_v<T_j, T>)
π Example π
// Run this code
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
std::ostream& operator<<(std::ostream& os, std::variant<int, std::string> const& va)
{
os << ": { ";
std::visit([&](auto&& arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, int>)
os << arg;
else if constexpr (std::is_same_v<T, std::string>)
os << std::quoted(arg);
}, va);
return os << " };\n";
}
int main()
{
std::variant<int, std::string> a{2017}, b{"CppCon"};
std::cout << "a" << a << "b" << b << '\n';
std::cout << "(1) operator=( const variant& rhs )\n";
a = b;
std::cout << "a" << a << "b" << b << '\n';
std::cout << "(2) operator=( variant&& rhs )\n";
a = std::move(b);
std::cout << "a" << a << "b" << b << '\n';
std::cout << "(3) operator=( T&& t ), where T is int\n";
a = 2019;
std::cout << "a" << a << '\n';
std::cout << "(3) operator=( T&& t ), where T is std::string\n";
std::string s{"CppNow"};
std::cout << "s: " << std::quoted(s) << '\n';
a = std::move(s);
std::cout << "a" << a << "s: " << std::quoted(s) << '\n';
}
πΈ Possible output πΈ
a: { 2017 };
b: { "CppCon" };
(1) operator=( const variant& rhs )
a: { "CppCon" };
b: { "CppCon" };
(2) operator=( variant&& rhs )
a: { "CppCon" };
b: { "" };
(3) operator=( T&& t ), where T is int
a: { 2019 };
(3) operator=( T&& t ), where T is std::string
s: "CppNow"
a: { "CppNow" };
s: ""
π¦ Defect reports π¦
The following behavior-changing defect reports were applied retroactively to previously published C++ standards. History really said βlet me fix her.β π
LWG 3024(C++17) β behavior as published: copy assignment operator doesn't participate in overload resolution if any member type is not copyable. Correct behavior: defined as deleted instead.P0602R4(C++17) β behavior as published: copy/move assignment may not be trivial even if underlying operations are trivial. Correct behavior: required to propagate triviality.P0608R3(C++17) β behavior as published: converting assignment blindly assembles an overload set, leading to unintended conversions. Correct behavior: narrowing and boolean conversions not considered.P2231R1(C++20) β behavior as published: converting assignment was not constexpr while the required operations can be in C++20. Correct behavior: made constexpr.LWG 3585(C++17) β behavior as published: converting assignment was sometimes unexpectedly ill-formed because there was no available move assignment. Correct behavior: made well-formed.
π See also π
emplaceβ constructs a value in the variant, in place (public member function). Obsessed. π«Ά
β Category β
- Category: conditionally noexcept
Source/version + date vibes, bestie: http://cppreference.com Β· 2024.06.10. Now go forth and assign with main-character energy π
β¨π¦
π¦ 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