Last updated:2026-10-12
C++17 std::variant¶
I recently came up with some interesting questions and put together a little summary - how many of them can you answer?
Note: the complete answers will be revealed in the members' community.
Question 1: How many types' constructors does the std::variant constructor invoke - one, two, or n?
Related questions:
- What is the default construction behavior of
std::variant? - What happens when the types contained in a
std::variantdo not have a default constructor? - How do you specify the initial value type of a
std::variant?
Question 2: Can the following code run correctly? If it can, explain why; otherwise give several solutions.
struct X {
X(int v) : v_(v) {}
int v_;
};
struct Y {
Y(double v) : v_(v) {}
double v_;
};
std::variant<X, Y> a1;
Related questions:
- How do you add a type with a default constructor to a
std::variant? - What are the solutions when there is no default constructor in the
std::varianttype list? - How do you explicitly construct a
std::variantto avoid default construction problems?
Question 3: What is monostate, and what problem does it solve?
Related questions:
- How do you use
std::monostatein astd::variant? - What impact does the introduction of
std::monostatehave on the design ofstd::variant? - In what situations is it appropriate to use
std::monostate?
Question 4: What are the differences between defer_lock_t, try_to_lock_t, and adopt_lock_t? In which scenarios are they used?
Related questions:
- What are the usage scenarios and implementation mechanism of
defer_lock_t? - How does
try_to_lock_thandle attempting to lock a mutex? - What should be noted when
adopt_lock_ttakes ownership of an already-held lock?
Related Topics¶
- C++17 [[nodiscard]] Attribute | C++那些事
- C++17 std::string_view | C++那些事
- C++17 PMR Memory Resources | C++那些事
- C++17 Seventeen Advanced Features | C++那些事
- C++17 Class Template Argument Deduction CTAD | C++那些事
- C++17 optional_ref | C++那些事
- C++17 Structured Bindings | C++那些事
- C++17 Template auto Deduction | C++那些事
- C++17 Variable Templates | C++那些事