code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
cpp std::ranges::viewable_range std::ranges::viewable\_range
============================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template<class T>
concept viewable_range =
ranges::range<T> &&
((ranges::view<std::remove_cvref_t<T>> &&
std::constructible_from<std::remove_cvref_t<T>, T>) ||
(!ranges::view<std::remove_cvref_t<T>> &&
(std::is_lvalue_reference_v<T> ||
(std::movable<std::remove_reference_t<T>> && !/*is-initializer-list*/<T>))));
```
| | (since C++20) |
The `viewable_range` concept is a refinement of [`range`](range "cpp/ranges/range") that describes a range that can be converted into a [`view`](view "cpp/ranges/view") through [`views::all`](all_view "cpp/ranges/all view").
The constant `/*is-initializer-list*/<T>` is `true` if and only if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>` is a specialization of `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")`.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3481](https://cplusplus.github.io/LWG/issue3481) | C++20 | `viewable_range` accepted an lvalue of a move-only view | rejects |
| [P2415R2](https://wg21.link/P2415R2) | C++20 | `viewable_range` only accepted non-[`view`](view "cpp/ranges/view") rvalues that are [`borrowed_range`](borrowed_range "cpp/ranges/borrowed range") | accepts more types |
### See also
| | |
| --- | --- |
| [views::all\_tviews::all](all_view "cpp/ranges/all view")
(C++20) | a [`view`](view "cpp/ranges/view") that includes all elements of a [`range`](range "cpp/ranges/range") (alias template) (range adaptor object) |
cpp std::ranges::common_range std::ranges::common\_range
==========================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class T >
concept common_range =
ranges::range<T> && std::same_as<ranges::iterator_t<T>, ranges::sentinel_t<T>>;
```
| | (since C++20) |
The `common_range` concept is a refinement of [`range`](range "cpp/ranges/range") for which `[std::ranges::begin()](begin "cpp/ranges/begin")` and `[std::ranges::end()](end "cpp/ranges/end")` return the same type (e.g. all standard library containers).
### Example
```
#include <ranges>
struct A {
char* begin();
char* end();
};
static_assert( std::ranges::common_range<A> );
struct B {
char* begin();
bool end();
}; // not a common_range: begin/end have different types
static_assert( not std::ranges::common_range<B> );
struct C {
char* begin();
}; // not a common_range, not even a range: has no end()
static_assert( not std::ranges::common_range<C> );
int main() { }
```
cpp std::ranges::borrowed_range, std::ranges::enable_borrowed_range std::ranges::borrowed\_range, std::ranges::enable\_borrowed\_range
==================================================================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template<class R>
concept borrowed_range =
ranges::range<R> &&
(std::is_lvalue_reference_v<R> ||
ranges::enable_borrowed_range<std::remove_cvref_t<R>>);
```
| (1) | (since C++20) |
|
```
template<class R>
inline constexpr bool enable_borrowed_range = false;
```
| (2) | (since C++20) |
1) The concept `borrowed_range` defines the requirements of a range such that a function can take it by value and return iterators obtained from it without danger of dangling.
2) The `enable_borrowed_range` variable template is used to indicate whether a [`range`](range "cpp/ranges/range") is a `borrowed_range`. The primary template is defined as `false`. ### Semantic requirements
Let `U` be `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>` if `T` is an rvalue reference type, and `T` otherwise. Given a variable `u` of type `U`, `T` models `borrowed_range` only if the validity of iterators obtained from `u` is not tied to the lifetime of that variable.
### Specializations
Specializations of `enable_borrowed_range` for all specializations of the following standard templates are defined as `true`:
* [`std::basic_string_view`](../string/basic_string_view "cpp/string/basic string view")
* [`std::span`](../container/span "cpp/container/span")
* [`std::ranges::subrange`](subrange "cpp/ranges/subrange")
* [`std::ranges::ref_view`](ref_view "cpp/ranges/ref view")
* [`std::ranges::empty_view`](empty_view "cpp/ranges/empty view")
* [`std::ranges::iota_view`](iota_view "cpp/ranges/iota view")
Specialization of `enable_borrowed_range` for the following standard range adaptors are defined as `true` if and only if `std::ranges::enable_borrowed_range<V>` is `true`, where `V` is the underlying view type:
* [`std::ranges::owning_view`](owning_view "cpp/ranges/owning view")
* [`std::ranges::take_view`](take_view "cpp/ranges/take view")
* [`std::ranges::drop_view`](drop_view "cpp/ranges/drop view")
* [`std::ranges::drop_while_view`](drop_while_view "cpp/ranges/drop while view")
* [`std::ranges::common_view`](common_view "cpp/ranges/common view")
* [`std::ranges::reverse_view`](reverse_view "cpp/ranges/reverse view")
* [`std::ranges::elements_view`](elements_view "cpp/ranges/elements view")
| | |
| --- | --- |
| * [`std::ranges::adjacent_view`](adjacent_view "cpp/ranges/adjacent view")
| (since C++23) |
| | |
| --- | --- |
| Specialization for [`std::ranges::zip_view`](zip_view "cpp/ranges/zip view") is defined as `true` if and only if `(std::ranges::enable_borrowed_range<Vs> && ...)` is `true`, where `Vs...` are all view types it adapts. | (since C++23) |
Users may specialize `enable_borrowed_range` to `true` for cv-unqualified program-defined types which model `borrowed_range`, and `false` for types which do not. Such specializations shall be usable in [constant expressions](../language/constant_expression "cpp/language/constant expression") and have type `const bool`.
### Example
Demonstrates the specializations of `enable_borrowed_range` for program defined types. Such specializations protect against potentially dangling results.
```
#include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>
#include <ranges>
#include <span>
#include <type_traits>
template <typename T, std::size_t N>
struct MyRange : std::array<T, N> { };
template <typename T, std::size_t N>
inline constexpr bool std::ranges::enable_borrowed_range<MyRange<T, N>> = false;
template <typename T, std::size_t N>
struct MyBorrowedRange : std::span<T, N> { };
template <typename T, std::size_t N>
inline constexpr bool std::ranges::enable_borrowed_range<MyBorrowedRange<T, N>> = true;
int main()
{
static_assert(std::ranges::range<MyRange<int, 8>>);
static_assert(std::ranges::borrowed_range<MyRange<int, 8>> == false);
static_assert(std::ranges::range<MyBorrowedRange<int, 8>>);
static_assert(std::ranges::borrowed_range<MyBorrowedRange<int, 8>> == true);
auto getMyRangeByValue = [] { return MyRange<int, 4>{ {1, 2, 42, 3} }; };
auto dangling_iter = std::ranges::max_element(getMyRangeByValue());
static_assert(std::is_same_v<std::ranges::dangling, decltype(dangling_iter)>);
// *dangling_iter; // compilation error (i.e. dangling protection works.)
auto my = MyRange<int, 4>{ {1, 2, 42, 3} };
auto valid_iter = std::ranges::max_element(my);
std::cout << *valid_iter << ' '; // OK: 42
auto getMyBorrowedRangeByValue = [] {
static int sa[4] {1, 2, 42, 3};
return MyBorrowedRange<int, std::size(sa)>{sa};
};
auto valid_iter2 = std::ranges::max_element(getMyBorrowedRangeByValue());
std::cout << *valid_iter2 << '\n'; // OK: 42
}
```
Output:
```
42 42
```
### See also
| | |
| --- | --- |
| [ranges::dangling](dangling "cpp/ranges/dangling")
(C++20) | a placeholder type indicating that an iterator or a `subrange` should not be returned since it would be dangling (class) |
cpp std::ranges::empty std::ranges::empty
==================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
inline namespace /*unspecified*/ {
inline constexpr auto empty = /*unspecified*/;
}
```
| | (since C++20) (customization point object) |
| Call signature | | |
|
```
template< class T >
requires /* see below */
constexpr bool empty( T&& t );
```
| | (since C++20) |
Determines whether or not `t` has any elements.
A call to `ranges::empty` is expression-equivalent to:
1. `bool(t.empty())`, if that expression is valid.
2. Otherwise, `([ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(t) == 0)`, if that expression is valid.
3. Otherwise, `bool([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(t) == [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(t))`, if that expression is valid and `decltype([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(t))` models `[std::forward\_iterator](../iterator/forward_iterator "cpp/iterator/forward iterator")`.
In all other cases, a call to `ranges::empty` is ill-formed, which can result in [substitution failure](../language/sfinae "cpp/language/sfinae") when `ranges::empty(t)` appears in the immediate context of a template instantiation.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Customization point objects
The name `ranges::empty` denotes a *customization point object*, which is a const [function object](../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_empty\_fn*`.
All instances of `*\_\_empty\_fn*` are equal. The effects of invoking different instances of type `*\_\_empty\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::empty` can be copied freely and its copies can be used interchangeably.
Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::empty` above, `*\_\_empty\_fn*` models
.
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__empty_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __empty_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__empty_fn&, Args...>`, and
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __empty_fn&, Args...>`.
Otherwise, no function call operator of `*\_\_empty\_fn*` participates in overload resolution.
### Example
```
#include <iostream>
#include <ranges>
#include <vector>
template <std::ranges::input_range R>
void print(char id, R&& r)
{
if (std::ranges::empty(r)) {
std::cout << '\t' << id << ") Empty\n";
return;
}
std::cout << '\t' << id << ") Elements:";
for (const auto& element : r) {
std::cout << ' ' << element;
}
std::cout << '\n';
}
int main()
{
{
auto v = std::vector<int>{1, 2, 3};
std::cout << "(1) ranges::empty uses std::vector::empty:\n";
print('a', v);
v.clear();
print('b', v);
}
{
std::cout << "(2) ranges::empty uses ranges::size(initializer_list):\n";
auto il = {7, 8, 9};
print('a', il);
print('b', std::initializer_list<int>{});
}
{
std::cout << "(2) ranges::empty on a raw array uses ranges::size:\n";
int array[] = {4, 5, 6}; // array has a known bound
print('a', array);
}
{
struct Scanty : private std::vector<int> {
using std::vector<int>::begin;
using std::vector<int>::end;
using std::vector<int>::push_back;
// Note: both empty() and size() are hidden
};
std::cout << "(3) calling ranges::empty on an object w/o empty() or size():\n";
Scanty y;
print('a', y);
y.push_back(42);
print('b', y);
}
}
```
Output:
```
(1) ranges::empty uses std::vector::empty:
a) Elements: 1 2 3
b) Empty
(2) ranges::empty uses ranges::size(initializer_list):
a) Elements: 7 8 9
b) Empty
(2) ranges::empty on a raw array uses ranges::size:
a) Elements: 4 5 6
(3) calling ranges::empty on an object w/o empty() or size():
a) Empty
b) Elements: 42
```
### See also
| | |
| --- | --- |
| [empty](../iterator/empty "cpp/iterator/empty")
(C++17) | checks whether the container is empty (function template) |
cpp std::ranges::iterator_t, std::ranges::const_iterator_t, std::ranges::sentinel_t, std::ranges::range_size_t, std::ranges::range_difference_t, std::ranges::range_value_t, std::ranges::range_reference_t, std::ranges::range_const_reference_t std::ranges::iterator\_t, std::ranges::const\_iterator\_t, std::ranges::sentinel\_t, std::ranges::range\_size\_t, std::ranges::range\_difference\_t, std::ranges::range\_value\_t, std::ranges::range\_reference\_t, std::ranges::range\_const\_reference\_t
============================================================================================================================================================================================================================================================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template <class T>
using iterator_t = decltype(ranges::begin(std::declval<T&>()));
```
| (1) | (since C++20) |
|
```
template <ranges::range R>
using const_iterator_t = std::const_iterator<ranges::iterator_t<R>>;
```
| (2) | (since C++23) |
|
```
template <ranges::range R>
using sentinel_t = decltype(ranges::end(std::declval<R&>()));
```
| (3) | (since C++20) |
|
```
template <ranges::sized_range R>
using range_size_t = decltype(ranges::size(std::declval<R&>()));
```
| (4) | (since C++20) |
|
```
template <ranges::range R>
using range_difference_t = std::iter_difference_t<ranges::iterator_t<R>>;
```
| (5) | (since C++20) |
|
```
template <ranges::range R>
using range_value_t = std::iter_value_t<ranges::iterator_t<R>>;
```
| (6) | (since C++20) |
|
```
template <ranges::range R>
using range_reference_t = std::iter_reference_t<ranges::iterator_t<R>>;
```
| (7) | (since C++20) |
|
```
template <ranges::range R>
using range_const_reference_t =
std::iter_const_reference_t<ranges::iterator_t<R>>;
```
| (8) | (since C++23) |
|
```
template <ranges::range R>
using range_rvalue_reference_t =
std::iter_rvalue_reference_t<ranges::iterator_t<R>>;
```
| (9) | (since C++20) |
1) Used to obtain the iterator type of the type `T`.
2) Used to obtain the constant iterator type of the [`range`](range "cpp/ranges/range") type `R`.
3) Used to obtain the sentinel type of the range type `R`.
4) Used to obtain the size type of the [`sized_range`](sized_range "cpp/ranges/sized range") type `R`.
5) Used to obtain the difference type of the iterator type of range type `R`.
6) Used to obtain the value type of the iterator type of range type `R`.
7) Used to obtain the reference type of the iterator type of range type `R`.
8) Used to obtain the const\_reference type of the iterator type of range type `R`.
9) Used to obtain the rvalue\_reference type of the iterator type of range type `R`. ### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type that can be used in `[std::ranges::begin](begin "cpp/ranges/begin")` |
| R | - | a [`range`](range "cpp/ranges/range") type or a [`sized_range`](sized_range "cpp/ranges/sized range") type |
### Notes
`iterator_t` can be applied to non-range types, e.g. arrays with unknown bound.
### See also
| | |
| --- | --- |
| [iter\_value\_titer\_reference\_titer\_const\_reference\_titer\_difference\_titer\_rvalue\_reference\_titer\_common\_reference\_t](../iterator/iter_t "cpp/iterator/iter t")
(C++20)(C++20)(C++23)(C++20)(C++20)(C++20) | computes the associated types of an iterator (alias template) |
cpp std::ranges::begin std::ranges::begin
==================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
inline namespace /*unspecified*/ {
inline constexpr /*unspecified*/ begin = /*unspecified*/;
}
```
| | (since C++20) (customization point object) |
| Call signature | | |
|
```
template< class T >
requires /* see below */
constexpr std::input_or_output_iterator auto begin( T&& t );
```
| | (since C++20) |
Returns an iterator to the first element of the argument.
![range-begin-end.svg]()
If the argument is an lvalue or `[ranges::enable\_borrowed\_range](http://en.cppreference.com/w/cpp/ranges/borrowed_range)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>>` is `true`, then a call to `ranges::begin` is expression-equivalent to:
1. `t + 0` if `t` has an array type. If `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>>` is incomplete, then the call to `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)` is ill-formed, no diagnostic required.
2. Otherwise, `t.begin()` converted to its [decayed type](../types/decay "cpp/types/decay"), if that expression with conversion is valid, and its converted type models `[std::input\_or\_output\_iterator](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator")`.
3. Otherwise, `begin(t)` converted to its [decayed type](../types/decay "cpp/types/decay"), if `t` has a class or enumeration type, the aforementioned unqualified call with conversion is valid, and its converted type models `[std::input\_or\_output\_iterator](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator")`, where the [overload resolution](../language/overload_resolution "cpp/language/overload resolution") is performed with the following candidates:
* any declarations of `begin` found by [argument-dependent lookup](../language/adl "cpp/language/adl").
* `void begin(auto&) = delete;`
* `void begin(const auto&) = delete;`
In all other cases, a call to `ranges::begin` is ill-formed, which can result in [substitution failure](../language/sfinae "cpp/language/sfinae") when the call appears in the immediate context of a template instantiation.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Customization point objects
The name `ranges::begin` denotes a *customization point object*, which is a const [function object](../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_begin\_fn*`.
All instances of `*\_\_begin\_fn*` are equal. The effects of invoking different instances of type `*\_\_begin\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::begin` can be copied freely and its copies can be used interchangeably.
Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::begin` above, `*\_\_begin\_fn*` models
.
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__begin_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __begin_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__begin_fn&, Args...>`, and
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __begin_fn&, Args...>`.
Otherwise, no function call operator of `*\_\_begin\_fn*` participates in overload resolution.
### Notes
If the argument is an rvalue (i.e. `T` is an object type) and `[ranges::enable\_borrowed\_range](http://en.cppreference.com/w/cpp/ranges/borrowed_range)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>>` is `false`, the call to `ranges::begin` is ill-formed, which also results in substitution failure.
The return type models `[std::input\_or\_output\_iterator](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator")` in all cases.
The C++20 standard requires that if the underlying `begin` function call returns a prvalue, the return value is move-constructed from the materialized temporary object. All implementations directly return the prvalue instead. The requirement is corrected by the post-C++20 proposal [P0849R8](https://wg21.link/P0849R8) to match the implementations.
### Example
```
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector<int> v = { 3, 1, 4 };
auto vi = std::ranges::begin(v);
std::cout << *vi << '\n';
*vi = 42; // OK
int a[] = { -5, 10, 15 };
auto ai = std::ranges::begin(a);
std::cout << *ai << '\n';
*ai = 42; // OK
}
```
Output:
```
3
-5
```
### See also
| | |
| --- | --- |
| [ranges::cbegin](cbegin "cpp/ranges/cbegin")
(C++20) | returns an iterator to the beginning of a read-only range (customization point object) |
| [begincbegin](../iterator/begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| programming_docs |
cpp std::ranges::views::transform, std::ranges::transform_view std::ranges::views::transform, std::ranges::transform\_view
===========================================================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< ranges::input_range V,
std::copy_constructible F >
requires ranges::view<V> &&
std::is_object_v<F> &&
std::regular_invocable<F&, ranges::range_reference_t<V>> &&
/* invoke_result_t<F&, range_reference_t<V>>& is a valid type */
class transform_view : public ranges::view_interface<transform_view<V, F>>
```
| (1) | (since C++20) |
|
```
namespace views {
inline constexpr /*unspecified*/ transform = /*unspecified*/;
}
```
| (2) | (since C++20) |
| Call signature | | |
|
```
template< ranges::viewable_range R, class F >
requires /* see below */
constexpr ranges::view auto transform( R&& r, F&& fun );
```
| | (since C++20) |
|
```
template< class F >
constexpr /*range adaptor closure*/ transform( F&& fun );
```
| | (since C++20) |
1) A range adaptor that represents [`view`](view "cpp/ranges/view") of an underlying sequence after applying a transformation function to each element.
2) [Range adaptor object](../ranges#Range_adaptor_objects "cpp/ranges"). The expression `views::transform(e, f)` is *expression-equivalent* to `transform_view(e, f)` for any suitable subexpressions `e` and `f`. `transform_view` models the concepts [`random_access_range`](random_access_range "cpp/ranges/random access range"), [`bidirectional_range`](bidirectional_range "cpp/ranges/bidirectional range"), [`forward_range`](forward_range "cpp/ranges/forward range"), [`input_range`](input_range "cpp/ranges/input range"), [`common_range`](common_range "cpp/ranges/common range"), and [`sized_range`](sized_range "cpp/ranges/sized range") when the underlying view `V` models respective concepts.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Member functions
| | |
| --- | --- |
| [(constructor)](transform_view/transform_view "cpp/ranges/transform view/transform view")
(C++20) | constructs a `transform_view` (public member function) |
| [base](transform_view/base "cpp/ranges/transform view/base")
(C++20) | returns a copy of the underlying (adapted) view (public member function) |
| [begin](transform_view/begin "cpp/ranges/transform view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [end](transform_view/end "cpp/ranges/transform view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [size](transform_view/size "cpp/ranges/transform view/size")
(C++20) | returns the number of elements. Provided only if the underlying (adapted) range satisfies [`sized_range`](sized_range "cpp/ranges/sized range"). (public member function) |
| Inherited from `[std::ranges::view\_interface](view_interface "cpp/ranges/view interface")` |
| [empty](view_interface/empty "cpp/ranges/view interface/empty")
(C++20) | Returns whether the derived view is empty. Provided if it satisfies [`sized_range`](sized_range "cpp/ranges/sized range") or [`forward_range`](forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
| [operator bool](view_interface/operator_bool "cpp/ranges/view interface/operator bool")
(C++20) | Returns whether the derived view is not empty. Provided if `[ranges::empty](empty "cpp/ranges/empty")` is applicable to it. (public member function of `std::ranges::view_interface<D>`) |
| [front](view_interface/front "cpp/ranges/view interface/front")
(C++20) | Returns the first element in the derived view. Provided if it satisfies [`forward_range`](forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
| [back](view_interface/back "cpp/ranges/view interface/back")
(C++20) | Returns the last element in the derived view. Provided if it satisfies [`bidirectional_range`](bidirectional_range "cpp/ranges/bidirectional range") and [`common_range`](common_range "cpp/ranges/common range"). (public member function of `std::ranges::view_interface<D>`) |
| [operator[]](view_interface/operator_at "cpp/ranges/view interface/operator at")
(C++20) | Returns the nth element in the derived view. Provided if it satisfies [`random_access_range`](random_access_range "cpp/ranges/random access range"). (public member function of `std::ranges::view_interface<D>`) |
### [Deduction guides](transform_view/deduction_guides "cpp/ranges/transform view/deduction guides")
### Nested classes
| | |
| --- | --- |
| [*iterator*](transform_view/iterator "cpp/ranges/transform view/iterator")
(C++20) | the iterator type (exposition-only member class template) |
| [*sentinel*](transform_view/sentinel "cpp/ranges/transform view/sentinel")
(C++20) | the sentinel type (exposition-only member class template) |
### Example
```
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <ranges>
#include <string>
char rot13a(const char x, const char a)
{
return a + (x - a + 13) % 26;
}
char rot13(const char x)
{
if (x >= 'A' && x <= 'Z') {
return rot13a(x, 'A');
}
if (x >= 'a' && x <= 'z') {
return rot13a(x, 'a');
}
return x;
}
int main()
{
auto show = [](const unsigned char x) { std::putchar(x); };
std::string in{ "cppreference.com\n" };
std::ranges::for_each(in, show);
std::ranges::for_each(in | std::views::transform(rot13), show);
std::string out;
std::ranges::copy( std::views::transform(in, rot13), std::back_inserter(out) );
std::ranges::for_each(out, show);
std::ranges::for_each(out | std::views::transform(rot13), show);
}
```
Output:
```
cppreference.com
pccersrerapr.pbz
pccersrerapr.pbz
cppreference.com
```
### See also
| | |
| --- | --- |
| [ranges::transform](../algorithm/ranges/transform "cpp/algorithm/ranges/transform")
(C++20) | applies a function to a range of elements (niebloid) |
cpp std::ranges::views::elements, std::ranges::elements_view std::ranges::views::elements, std::ranges::elements\_view
=========================================================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< ranges::input_range V, std::size_t N >
requires
view<V> &&
/*has-tuple-element*/<ranges::range_value_t<V>, N> &&
/*has-tuple-element*/<std::remove_reference_t<ranges::range_reference_t<V>>, N> &&
/*returnable-element*/<ranges::range_reference_t<V>, N>
class elements_view : public ranges::view_interface<elements_view<V, N>>;
```
| (1) | (since C++20) |
|
```
namespace views {
template< std::size_t N >
inline constexpr /*unspecified*/ elements = /*unspecified*/;
}
```
| (2) | (since C++20) |
| Call signature | | |
|
```
template< ranges::viewable_range R >
requires /* see below */
constexpr ranges::view auto elements<N>( R&& r );
```
| | (since C++20) |
| Helper concepts | | |
|
```
template< class T, std::size_t N >
concept /*has-tuple-element*/ = // exposition only
requires(T t) {
typename std::tuple_size<T>::type;
requires N < std::tuple_size_v<T>;
typename std::tuple_element_t<N, T>;
{ std::get<N>(t) } -> std::convertible_to<const std::tuple_element_t<N, T>&>;
};
```
| (3) | (since C++20) |
|
```
template< class T, std::size_t N >
concept /*returnable-element*/ = // exposition only
std::is_reference_v<T> || std::move_constructible<std::tuple_element_t<N, T>>;
```
| (4) | (since C++20) |
1) Accepts a [`view`](view "cpp/ranges/view") of *tuple-like* values, and issues a view with a *value-type* of the `N`-th element of the adapted view's value-type.
2) Every specialization of `views::elements` is a [range adaptor object](../ranges#Range_adaptor_objects "cpp/ranges"). The expression `views::elements<M>(e)` is *expression-equivalent* to `elements_view<[views::all\_t](http://en.cppreference.com/w/cpp/ranges/all_view)<decltype((e))>, M>{e}` for any suitable subexpression `e` and constant expression `M`.
3) Ensures that the elements of the underlying view are *tuple-like* values.
4) Ensures that dangling references cannot be returned. `elements_view` models the concepts [`random_access_range`](random_access_range "cpp/ranges/random access range"), [`bidirectional_range`](bidirectional_range "cpp/ranges/bidirectional range"), [`forward_range`](forward_range "cpp/ranges/forward range"), [`input_range`](input_range "cpp/ranges/input range"), [`common_range`](common_range "cpp/ranges/common range"), and [`sized_range`](sized_range "cpp/ranges/sized range") when the underlying view `V` models respective concepts.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Member functions
| | |
| --- | --- |
| [(constructor)](elements_view/elements_view "cpp/ranges/elements view/elements view")
(C++20) | constructs a `elements_view` (public member function) |
| [base](elements_view/base "cpp/ranges/elements view/base")
(C++20) | returns a copy of the underlying (adapted) view (public member function) |
| [begin](elements_view/begin "cpp/ranges/elements view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [end](elements_view/end "cpp/ranges/elements view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [size](elements_view/size "cpp/ranges/elements view/size")
(C++20) | returns the number of elements. Provided only if the underlying (adapted) range satisfies [`sized_range`](sized_range "cpp/ranges/sized range"). (public member function) |
| Inherited from `[std::ranges::view\_interface](view_interface "cpp/ranges/view interface")` |
| [empty](view_interface/empty "cpp/ranges/view interface/empty")
(C++20) | Returns whether the derived view is empty. Provided if it satisfies [`sized_range`](sized_range "cpp/ranges/sized range") or [`forward_range`](forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
| [operator bool](view_interface/operator_bool "cpp/ranges/view interface/operator bool")
(C++20) | Returns whether the derived view is not empty. Provided if `[ranges::empty](empty "cpp/ranges/empty")` is applicable to it. (public member function of `std::ranges::view_interface<D>`) |
| [front](view_interface/front "cpp/ranges/view interface/front")
(C++20) | Returns the first element in the derived view. Provided if it satisfies [`forward_range`](forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
| [back](view_interface/back "cpp/ranges/view interface/back")
(C++20) | Returns the last element in the derived view. Provided if it satisfies [`bidirectional_range`](bidirectional_range "cpp/ranges/bidirectional range") and [`common_range`](common_range "cpp/ranges/common range"). (public member function of `std::ranges::view_interface<D>`) |
| [operator[]](view_interface/operator_at "cpp/ranges/view interface/operator at")
(C++20) | Returns the nth element in the derived view. Provided if it satisfies [`random_access_range`](random_access_range "cpp/ranges/random access range"). (public member function of `std::ranges::view_interface<D>`) |
### Nested classes
| | |
| --- | --- |
| [*iterator*](elements_view/iterator "cpp/ranges/elements view/iterator")
(C++20) | the iterator type (exposition-only member class template) |
| [*sentinel*](elements_view/sentinel "cpp/ranges/elements view/sentinel")
(C++20) | the sentinel type (exposition-only member class template) |
### Helper templates
| | | |
| --- | --- | --- |
|
```
template<class T, std::size_t N>
inline constexpr bool enable_borrowed_range<std::ranges::elements_view<T, N>> =
std::ranges::enable_borrowed_range<T>;
```
| | (since C++20) |
This specialization of [`std::ranges::enable_borrowed_range`](borrowed_range "cpp/ranges/borrowed range") makes `elements_view` satisfy [`borrowed_range`](borrowed_range "cpp/ranges/borrowed range") when the underlying view satisfies it.
### Example
```
#include <iostream>
#include <ranges>
#include <tuple>
#include <vector>
int main()
{
const std::vector<std::tuple<int, char, std::string>> vt {
{1, 'A', "α"},
{2, 'B', "β"},
{3, 'C', "γ"},
{4, 'D', "δ"},
{5, 'E', "ε"},
};
for (int const e: std::views::elements<0>(vt)) { std::cout << e << ' '; }
std::cout << '\n';
for (char const e: vt | std::views::elements<1>) { std::cout << e << ' '; }
std::cout << '\n';
for (std::string const& e: std::views::elements<2>(vt)) { std::cout << e << ' '; }
std::cout << '\n';
}
```
Output:
```
1 2 3 4 5
A B C D E
α β γ δ ε
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3494](https://cplusplus.github.io/LWG/issue3494) | C++20 | `elements_view` was never a `borrowed_range` | it is a `borrowed_range` if its underlying view is |
| [LWG 3502](https://cplusplus.github.io/LWG/issue3502) | C++20 | dangling reference could be obtained from `elements_view` | such usage is forbidden |
### See also
| | |
| --- | --- |
| [ranges::keys\_viewviews::keys](keys_view "cpp/ranges/keys view")
(C++20) | takes a [`view`](view "cpp/ranges/view") consisting of pair-like values and produces a [`view`](view "cpp/ranges/view") of the first elements of each pair (class template) (range adaptor object) |
| [ranges::values\_viewviews::values](values_view "cpp/ranges/values view")
(C++20) | takes a [`view`](view "cpp/ranges/view") consisting of pair-like values and produces a [`view`](view "cpp/ranges/view") of the second elements of each pair (class template) (range adaptor object) |
| [ranges::zip\_viewviews::zip](zip_view "cpp/ranges/zip view")
(C++23) | a [`view`](view "cpp/ranges/view") consisting of tuples of references to corresponding elements of the adapted views (class template) (customization point object) |
| [ranges::zip\_transform\_viewviews::zip\_transform](zip_transform_view "cpp/ranges/zip transform view")
(C++23) | a [`view`](view "cpp/ranges/view") consisting of tuples of results of application of a transformation function to corresponding elements of the adapted views (class template) (customization point object) |
| [slice](../numeric/valarray/slice "cpp/numeric/valarray/slice") | BLAS-like slice of a valarray: starting index, length, stride (class) |
cpp std::ranges::end std::ranges::end
================
| Defined in header `[<ranges>](../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
inline namespace /*unspecified*/ {
inline constexpr /*unspecified*/ end = /*unspecified*/;
}
```
| | (since C++20) (customization point object) |
| Call signature | | |
|
```
template< class T >
requires /* see below */
constexpr std::sentinel_for<ranges::iterator_t<T>> auto end( T&& t );
```
| | (since C++20) |
Returns a sentinel indicating the end of a range.
![range-begin-end.svg]()
Let `t` be an object of type `T`. If the argument is an lvalue or `[ranges::enable\_borrowed\_range](http://en.cppreference.com/w/cpp/ranges/borrowed_range)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>>` is `true`, then a call to `ranges::end` is expression-equivalent to:
1. `t + [std::extent\_v](http://en.cppreference.com/w/cpp/types/extent)<T>` if `t` has an array type of known bound. If `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>>` is incomplete, then the call to `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)` is ill-formed, [no diagnostic required](../language/ndr "cpp/language/ndr").
2. Otherwise, `t.end()` converted to its [decayed type](../types/decay "cpp/types/decay"), if that expression with conversion is valid, and its converted type models `[std::sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sentinel_for)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<T>>`.
3. Otherwise, `end(t)` converted to its [decayed type](../types/decay "cpp/types/decay"), if `t` has a class or enumeration type, the aforementioned unqualified call with conversion is valid, and its converted type models `[std::sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sentinel_for)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<T>>`, where the [overload resolution](../language/overload_resolution "cpp/language/overload resolution") is performed with the following candidates:
* any declarations of `end` found by [argument-dependent lookup](../language/adl "cpp/language/adl").
* `void end(auto&) = delete;`
* `void end(const auto&) = delete;`
In all other cases, a call to `ranges::end` is ill-formed, which can result in [substitution failure](../language/sfinae "cpp/language/sfinae") when the call to `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)` appears in the immediate context of a template instantiation.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Customization point objects
The name `ranges::end` denotes a *customization point object*, which is a const [function object](../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_end\_fn*`.
All instances of `*\_\_end\_fn*` are equal. The effects of invoking different instances of type `*\_\_end\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::end` can be copied freely and its copies can be used interchangeably.
Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::end` above, `*\_\_end\_fn*` models
.
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__end_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __end_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__end_fn&, Args...>`, and
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __end_fn&, Args...>`.
Otherwise, no function call operator of `*\_\_end\_fn*` participates in overload resolution.
### Notes
If the argument is an rvalue (i.e. `T` is an object type) and `[ranges::enable\_borrowed\_range](http://en.cppreference.com/w/cpp/ranges/borrowed_range)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>>` is `false`, or if it is of an array type of unknown bound, the call to `ranges::end` is ill-formed, which also results in substitution failure.
If `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t))` is valid, then `decltype([ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)))` and `decltype([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)))` model `[std::sentinel\_for](../iterator/sentinel_for "cpp/iterator/sentinel for")` in all cases, while `T` models `[std::ranges::range](range "cpp/ranges/range")`.
The C++20 standard requires that if the underlying `end` function call returns a prvalue, the return value is move-constructed from the materialized temporary object. All implementations directly return the prvalue instead. The requirement is corrected by the post-C++20 proposal [P0849R8](https://wg21.link/P0849R8) to match the implementations.
### Example
```
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
std::vector<int> v = { 3, 1, 4 };
namespace ranges = std::ranges;
if (ranges::find(v, 5) != ranges::end(v)) {
std::cout << "found a 5 in vector v!\n";
}
int a[] = { 5, 10, 15 };
if (ranges::find(a, 5) != ranges::end(a)) {
std::cout << "found a 5 in array a!\n";
}
}
```
Output:
```
found a 5 in array a!
```
### See also
| | |
| --- | --- |
| [ranges::cend](cend "cpp/ranges/cend")
(C++20) | returns a sentinel indicating the end of a read-only range (customization point object) |
| [ranges::begin](begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [endcend](../iterator/end "cpp/iterator/end")
(C++11)(C++14) | returns an iterator to the end of a container or array (function template) |
| programming_docs |
cpp std::ranges::common_view<V>::size std::ranges::common\_view<V>::size
==================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::sized_range<V>;
```
| (1) | (since C++20) |
|
```
constexpr auto size() const requires ranges::sized_range<const V>;
```
| (2) | (since C++20) |
Returns the number of elements.
Equivalent to `{ return [ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base_); }`, where `base_` is the underlying view.
### Parameters
(none).
### Return value
The number of elements.
### Example
```
#include <ranges>
#include <string_view>
int main()
{
constexpr static auto v1 = {1, 2, 3, 4, 5};
constexpr auto common1 { v1 | std::views::common };
static_assert(common1.size() == 5);
constexpr auto take3 { v1 | std::views::reverse | std::views::take(3) };
constexpr auto common2 { take3 | std::views::common };
static_assert(common2.size() == 3);
using namespace std::literals;
constexpr static auto v2 = { "∧"sv, "∨"sv, "∃"sv, "∀"sv };
static_assert(std::ranges::views::common(v2).size() == 4);
}
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::common_view
deduction guides for `std::ranges::common_view`
===============================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template<class R>
common_view(R&&) -> common_view<views::all_t<R>>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `std::ranges::common_view` to allow deduction from [`range`](../range "cpp/ranges/range").
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `common_view<R>`; otherwise, the deduced type is usually `common_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
cpp std::ranges::common_view<V>::base std::ranges::common\_view<V>::base
==================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
```
#include <iostream>
#include <ranges>
#include <string>
int main()
{
std::string str { "C++20" };
auto view = std::views::common(str);
std::string copy_of_str = view.base();
std::cout << "copy of str: [" << copy_of_str << "]\n";
std::cout << "view.base(): [" << view.base() << "]\n";
std::string move_str = std::move(view.base());
std::cout << "moved str: [" << move_str << "]\n";
std::cout << "view.base(): [" << view.base() << "]\n"; // unspecified
}
```
Possible output:
```
copy of str: [C++20]
view.base(): [C++20]
moved str: [C++20]
view.base(): []
```
cpp std::ranges::common_view<V>::common_view std::ranges::common\_view<V>::common\_view
==========================================
| | | |
| --- | --- | --- |
|
```
common_view() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit common_view( V r );
```
| (2) | (since C++20) |
Constructs a `common_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view. After construction, [`base()`](base "cpp/ranges/common view/base") returns a copy of `V()`.
2) Initializes the underlying view with `std::move(r)`. ### Parameters
| | | |
| --- | --- | --- |
| r | - | underlying view to be adapted into a common-range |
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3405](https://cplusplus.github.io/LWG/issue3405) | C++20 | the redundant converting constructor might cause constraint recursion | removed |
cpp std::ranges::common_view<V>::begin std::ranges::common\_view<V>::begin
===================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const requires range<const V>;
```
| (2) | (since C++20) |
1) Returns an iterator to the first element of the `common_view`, that is: * `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)`, if both `[ranges::random\_access\_range](http://en.cppreference.com/w/cpp/ranges/random_access_range)<V>` and `[ranges::sized\_range](http://en.cppreference.com/w/cpp/ranges/sized_range)<V>` are satisfied,
* `[std::common\_iterator](http://en.cppreference.com/w/cpp/iterator/common_iterator)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>, [ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_))` otherwise.
Here `*base\_*` (the name is for exposition only purposes) is the underlying view.
2) Same as (1), but `V` is const-qualified. ### Parameters
(none).
### Return value
An iterator to the beginning of the underlying view.
### Example
```
#include <iostream>
#include <numeric>
#include <ranges>
#include <string_view>
int main()
{
constexpr auto common = std::views::iota(1)
| std::views::take(3)
| std::views::common
;
for (int i{}; int e : common) { std::cout << (i++ ? " + " : "") << e; }
std::cout << " = " << std::accumulate(common.begin(), common.end(), 0) << '\n';
}
```
Output:
```
1 + 2 + 3 = 6
```
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/common view/end")
(C++20) | returns an iterator to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::common_view<V>::end std::ranges::common\_view<V>::end
=================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end();
```
| (1) | (since C++20) |
|
```
constexpr auto end() const requires ranges::range<const V>;
```
| (2) | (since C++20) |
1) Returns an iterator representing the end of the `common_view`, that is: * `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_) + [ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base_)`, if both `[ranges::random\_access\_range](http://en.cppreference.com/w/cpp/ranges/random_access_range)<V>` and `[ranges::sized\_range](http://en.cppreference.com/w/cpp/ranges/sized_range)<V>` are satisfied,
* `[std::common\_iterator](http://en.cppreference.com/w/cpp/iterator/common_iterator)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>, [ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>([ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_))` otherwise.
Here `*base\_*` (the name is for exposition only purposes) is the underlying view.
2) Same as (1), but `V` is const-qualified. ### Parameters
(none).
### Return value
An iterator representing the end of the underlying view.
### Example
```
#include <iostream>
#include <numeric>
#include <ranges>
int main()
{
constexpr int n{4};
constexpr auto cv1 = std::views::iota(1)
| std::views::take(n)
| std::views::common
;
constexpr auto cv2 = std::views::iota(2)
| std::views::take(n)
;
const int product = std::inner_product(cv1.begin(), cv1.end(),
cv2.begin(),
0);
std::cout << product << '\n';
}
```
Output:
```
40
```
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/common view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp deduction guides for std::ranges::drop_while_view
deduction guides for `std::ranges::drop_while_view`
===================================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class R, class Pred >
drop_while_view( R&&, Pred ) -> drop_while_view<views::all_t<R>, Pred>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::ranges::drop\_while\_view](../drop_while_view "cpp/ranges/drop while view")` to allow deduction from [`range`](../range "cpp/ranges/range") and predicate.
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `drop_while_view<R>`; otherwise, the deduced type is usually `drop_while_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
cpp std::ranges::drop_while_view<V,Pred>::base std::ranges::drop\_while\_view<V,Pred>::base
============================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
```
#include <array>
#include <ranges>
#include <iostream>
#include <algorithm>
void print(auto first, auto last) {
for (; first != last; ++first)
std::cout << *first << ' ';
std::cout << '\n';
}
int main()
{
std::array data{ 1, 2, 3, 4, 5 };
print(data.cbegin(), data.cend());
auto func = [](int x) { return x < 3; };
auto view = std::ranges::drop_while_view{ data, func };
print(view.begin(), view.end());
auto base = view.base(); // `base` refers to the `data`
std::ranges::reverse(base); //< changes `data` indirectly
print(data.cbegin(), data.cend());
}
```
Output:
```
1 2 3 4 5
3 4 5
5 4 3 2 1
```
cpp std::ranges::drop_while_view<V,Pred>::drop_while_view std::ranges::drop\_while\_view<V,Pred>::drop\_while\_view
=========================================================
| | | |
| --- | --- | --- |
|
```
drop_while_view() requires std::default_initializable<V> &&
std::default_initializable<Pred> = default;
```
| (1) | (since C++20) |
|
```
constexpr drop_while_view( V base, Pred pred );
```
| (2) | (since C++20) |
Constructs a `drop_while_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and the predicate.
2) Move constructs the underlying view from `base` and the predicate from `pred`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | underlying view |
| pred | - | predicate |
### Example
```
#include <array>
#include <iostream>
#include <ranges>
int main()
{
constexpr std::array data{ 0, -1, -2, 3, 1, 4, 1, 5, };
auto view = std::ranges::drop_while_view{
data, [](int x) { return x <= 0; }
};
for (int x: view) {
std::cout << x << ' ';
}
std::cout << '\n';
}
```
Output:
```
3 1 4 1 5
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | if `Pred` is not [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable"), the default constructorconstructs a `drop_while_view` which does not contain an `Pred` | the `drop_while_view` is alsonot [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") |
cpp std::ranges::drop_while_view<V,Pred>::begin std::ranges::drop\_while\_view<V,Pred>::begin
=============================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| | (since C++20) |
Returns an iterator to the first element of the view.
Effectively returns `[ranges::find\_if\_not](http://en.cppreference.com/w/cpp/algorithm/ranges/find)(base_, [std::cref](http://en.cppreference.com/w/cpp/utility/functional/ref)(pred()))`, where `*base\_*` is the underlying view. The behavior is undefined if `*this` does not store a predicate.
In order to provide the amortized constant time complexity required by the [`range`](../range "cpp/ranges/range") concept, this function caches the result within the `drop_while_view` object for use on subsequent calls.
### Parameters
(none).
### Return value
Iterator to the first element of the view.
### Example
```
#include <array>
#include <iostream>
#include <ranges>
int main()
{
constexpr std::array data{ 0, -1, -2, 3, 1, 4, 1, 5 };
auto view = std::ranges::drop_while_view{
data, [](int x) { return x <= 0; }
};
std::cout << *view.begin() << '\n';
}
```
Output:
```
3
```
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/drop while view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
cpp std::ranges::drop_while_view<V,Pred>::pred std::ranges::drop\_while\_view<V,Pred>::pred
============================================
| | | |
| --- | --- | --- |
|
```
constexpr const Pred& pred() const;
```
| | (since C++20) |
Returns a reference to the stored predicate.
If `*this` does not store a predicate (e.g. an exception is thrown on the assignment to `*this`, which copy-constructs or move-constructs a `Pred`), the behavior is undefined.
### Parameters
(none).
### Return value
a reference to the stored predicate.
### Example
```
#include <array>
#include <iostream>
#include <iomanip>
#include <ranges>
int main()
{
constexpr std::array data{ 0, -1, -2, 3, 1, 4, 1, 5, };
auto view = std::ranges::drop_while_view{
data, [](int x) { return x <= 0; }
};
std::cout << std::boolalpha;
for (int x: data) {
std::cout << "predicate(" << std::setw(2) << x << ") : "
<< view.pred()(x) << '\n';
}
}
```
Output:
```
predicate( 0) : true
predicate(-1) : true
predicate(-2) : true
predicate( 3) : false
predicate( 1) : false
predicate( 4) : false
predicate( 1) : false
predicate( 5) : false
```
cpp std::ranges::drop_while_view<V,Pred>::end std::ranges::drop\_while\_view<V,Pred>::end
===========================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end();
```
| | (since C++20) |
Returns a sentinel or an iterator representing the end of the `drop_while_view`.
Effectively returns `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)`, where `*base\_*` is the underlying view.
### Parameters
(none).
### Return value
a sentinel or an iterator representing the end of the view.
### Example
```
#include <array>
#include <iostream>
#include <ranges>
int main()
{
constexpr std::array data{ 0, -1, -2, 3, 1, 4, 1, 5 };
auto view = std::ranges::drop_while_view{
data, [](int x) { return x <= 0; }
};
for (auto it = view.begin(); it != view.end(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
}
```
Output:
```
3 1 4 1 5
```
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/drop while view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
cpp std::ranges::lazy_split_view<V, Pattern>::outer_iterator<Const>::value_type std::ranges::lazy\_split\_view<V, Pattern>::*outer\_iterator*<Const>::value\_type
=================================================================================
| | | |
| --- | --- | --- |
|
```
struct value_type : ranges::view_interface<value_type>
```
| | (since C++20) |
The value type of the iterator `ranges::lazy_split_view<V, Pattern>::/*outer_iterator*/<Const>`.
### Data members
Typical implementations of `value_type` hold only one non-static data member: an iterator of type [`*outer\_iterator*`](outer_iterator "cpp/ranges/lazy split view/outer iterator") (shown here as `*i\_*` for exposition only) into underlying [`view`](../view "cpp/ranges/view") of the outer class.
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs a `*value\_type*` object (public member function) |
| begin
(C++20) | returns an [`*inner\_iterator*`](inner_iterator "cpp/ranges/lazy split view/inner iterator") to the beginning of the inner range (public member function) |
| end
(C++20) | returns a `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` (public member function) |
| Inherited from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` |
| [empty](../view_interface/empty "cpp/ranges/view interface/empty")
(C++20) | Returns whether the derived view is empty. Provided if it satisfies [`sized_range`](../sized_range "cpp/ranges/sized range") or [`forward_range`](../forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
| [operator bool](../view_interface/operator_bool "cpp/ranges/view interface/operator bool")
(C++20) | Returns whether the derived view is not empty. Provided if `[ranges::empty](../empty "cpp/ranges/empty")` is applicable to it. (public member function of `std::ranges::view_interface<D>`) |
| [front](../view_interface/front "cpp/ranges/view interface/front")
(C++20) | Returns the first element in the derived view. Provided if it satisfies [`forward_range`](../forward_range "cpp/ranges/forward range"). (public member function of `std::ranges::view_interface<D>`) |
### Member functions
std::ranges::lazy\_split\_view::*outer\_iterator*::value\_type::value\_type
----------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
value_type() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit value_type(/*outer_iterator*/ i);
```
| (2) | (since C++20) |
1) Value initializes the exposition-only non-static data member `i_` via its default member initializer (`= /*outer_iterator*/()`).
2) Initializes `i_` with `std::move(i)`.
std::ranges::lazy\_split\_view::*outer\_iterator*::value\_type::begin
----------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*inner_iterator*/<Const> begin() const;
```
| | (since C++20) |
Equivalent to `return /*inner_iterator*/<Const>{i_};`.
std::ranges::lazy\_split\_view::*outer\_iterator*::value\_type::end
--------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr std::default_sentinel_t end() const noexcept;
```
| | (since C++20) |
Returns `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")`.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | `end` always returns `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` but might not be noexcept | made noexcept |
| programming_docs |
cpp deduction guides for std::ranges::lazy_split_view
deduction guides for `std::ranges::lazy_split_view`
===================================================
| | | |
| --- | --- | --- |
|
```
template< class R, class P >
lazy_split_view( R&&, P&& )
-> lazy_split_view<ranges::all_t<R>, ranges::all_t<P>>;
```
| (1) | (since C++20) |
|
```
template< ranges::input_range R >
lazy_split_view( R&&, ranges::range_value_t<R> )
-> lazy_split_view<ranges::all_t<R>, ranges::single_view<ranges::range_value_t<R>>>;
```
| (2) | (since C++20) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `lazy_split_view` to allow deduction from a range and a delimiter.
1) The delimiter is a range of elements.
2) The delimiter is a single element. ### Example
```
#include <ranges>
#include <string_view>
#include <type_traits>
using std::operator""sv;
// A temporary patch until P2210R2 is available in the online compiler
#define lazy_split_view split_view
int main() {
std::ranges::lazy_split_view w1{"a::b::c"sv, "::"sv};
// type of w1 is lazy_split_view<string_view, string_view>:
static_assert(std::is_same_v<
decltype(w1),
std::ranges::lazy_split_view<
std::basic_string_view<char, std::char_traits<char>>,
std::basic_string_view<char, std::char_traits<char>>>>);
std::ranges::lazy_split_view w2{"x,y,z"sv, ','};
// type of w2 is lazy_split_view<string_view, single_view<char>>:
static_assert(std::is_same_v<
decltype(w2),
std::ranges::lazy_split_view<
std::basic_string_view<char, std::char_traits<char>>,
std::ranges::single_view<char>>>);
}
```
cpp std::ranges::lazy_split_view<V,Pattern>::base std::ranges::lazy\_split\_view<V,Pattern>::base
===============================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
```
#include <iostream>
#include <ranges>
#include <string_view>
// A temporary patch until P2210R2 is implemented
#define lazy_split_view split_view
#define lazy_split split
void print(std::string_view rem, auto const& r, std::string_view post = "\n") {
for (std::cout << rem; auto const& e : r)
std::cout << e;
std::cout << post;
}
int main()
{
constexpr std::string_view keywords{ "this,..throw,..true,..try,.." };
constexpr std::string_view pattern{",.."};
constexpr std::ranges::lazy_split_view lazy_split_view{keywords, pattern};
print("base() = [", lazy_split_view.base(), "]\n"
"substrings: ");
for (auto const& split: lazy_split_view)
print("[", split, "] ");
}
```
Output:
```
base() = [this,..throw,..true,..try,..]
substrings: [this] [throw] [true] [try]
```
### See also
| | |
| --- | --- |
| [base](../split_view/base "cpp/ranges/split view/base")
(C++20) | returns a copy of the underlying (adapted) view (public member function of `std::ranges::split_view<V,Pattern>`) |
cpp std::ranges::lazy_split_view<V,Pattern>::lazy_split_view std::ranges::lazy\_split\_view<V,Pattern>::lazy\_split\_view
============================================================
| | | |
| --- | --- | --- |
|
```
lazy_split_view()
requires std::default_initializable<V> &&
std::default_initializable<Pattern> = default;
```
| (1) | (since C++20) |
|
```
constexpr lazy_split_view( V base, Pattern pattern );
```
| (2) | (since C++20) |
|
```
template< ranges::input_range R >
requires std::constructible_from<V, views::all_t<R>> &&
std::constructible_from<Pattern,
ranges::single_view<ranges::range_value_t<R>>>
constexpr lazy_split_view( R&& r, ranges::range_value_t<R> e );
```
| (3) | (since C++20) |
Constructs a `lazy_split_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and the delimiter.
2) Initializes the underlying view with `std::move(base)` and the delimiter with `std::move(pattern)`.
3) Initializes the underlying view with `[views::all](http://en.cppreference.com/w/cpp/ranges/all_view)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<R>(r))` and the delimiter with `[ranges::single\_view](http://en.cppreference.com/w/cpp/ranges/single_view){std::move(e)}`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | the underlying view (to be split) |
| pattern | - | view to be used as the delimiter |
| e | - | element to be used as the delimiter |
### Example
cpp std::ranges::lazy_split_view<V, Pattern>::outer_iterator
std::ranges::lazy\_split\_view<V, Pattern>::*outer\_iterator*
=============================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
struct /*outer_iterator*/;
```
| (1) | (since C++20) |
The return type of [`lazy_split_view::begin`](../lazy_split_view "cpp/ranges/lazy split view"), and of [`lazy_split_view::end`](../lazy_split_view "cpp/ranges/lazy split view") when the underlying view is a [`common_range`](../common_range "cpp/ranges/common range") and [`forward_range`](../forward_range "cpp/ranges/forward range").
If either `V` or `Pattern` is not a [simple view](../../ranges#Helper_concepts "cpp/ranges") (e.g. if `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const V>` is invalid or different from `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>`), `Const` is true for iterators returned from the const overloads, and false otherwise. If `V` is a simple view, `Const` is true if and only if `V` is a [`forward_range`](../forward_range "cpp/ranges/forward range").
The name of this class template (shown here as `/*outer_iterator*/`) is unspecified.
### Member types
| Member type | Definition |
| --- | --- |
| `*Parent*` (private) | `const ranges::lazy_split_view` if `Const` is `true`, otherwise `ranges::lazy_split_view`. The name is for exposition only. |
| `*Base*` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only. |
| `iterator_concept` | `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `Base` models [`forward_range`](../forward_range "cpp/ranges/forward range"), otherwise `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`. |
| `iterator_category` | `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `Base` models [`forward_range`](../forward_range "cpp/ranges/forward range"). Not present otherwise. |
| `value_type` | `ranges::lazy_iterator_view<V, Pattern>::/*outer_iterator*/<Const>::value_type`. |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>`. |
### Data members
Typical implementations of `*outer\_iterator*` hold two or three non-static data members:
* A pointer of type `*Parent\**` to the parent `lazy_split_view` object (shown here as `*parent\_*` for exposition only).
* An iterator of type `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>` (shown here as `*current\_*` for exposition only) into the underlying [`view`](../view "cpp/ranges/view"); present only if `V` models [`forward_range`](../forward_range "cpp/ranges/forward range").
* A boolean flag (shown here as `*trailing\_empty\_*` for exposition only) that indicates whether an empty trailing subrange (if any) was reached.
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs an iterator (public member function) |
| operator\*
(C++20) | returns the current subrange (public member function) |
| operator++operator++(int)
(C++20) | advances the iterator (public member function) |
| *cur*
(C++20) | returns conditionally a reference to the `*current\_*` (if present) or to the `*parent_->current_` (exposition-only member function) |
### Member functions
std::ranges::lazy\_split\_view::*outer\_iterator*::*outer\_iterator*
---------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*outer_iterator*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*outer_iterator*/( Parent& parent )
requires (!ranges::forward_range<Base>);
```
| (2) | (since C++20) |
|
```
constexpr /*outer_iterator*/( Parent& parent, ranges::iterator_t<Base> current )
requires ranges::forward_range<Base>;
```
| (3) | (since C++20) |
|
```
constexpr /*outer_iterator*/( /*outer_iterator*/<!Const> i )
requires Const && std::convertible_to<ranges::iterator_t<V>,
ranges::iterator_t<Base>>;
```
| (4) | (since C++20) |
1) Value initializes the exposition-only non-static data members with their default member initializer, that is: * `parent_ = nullptr;`,
* `current_ = iterator_t<Base>();` (present only if `V` models [`forward_range`](../forward_range "cpp/ranges/forward range")),
2) Initializes `*parent\_*` with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)`.
3) Initializes `*parent\_*` with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)` and `*current\_*` with `std::move(current)`.
4) Initializes `*parent\_*` with `i.parent_` and `*current\_*` with `std::move(i.current_)`. The exposition-only non-static data member `*trailing\_empty\_*` is initialized with its default member initializer to `false`.
std::ranges::lazy\_split\_view::*outer\_iterator*::operator\*
--------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr value_type operator*() const;
```
| | (since C++20) |
Equivalent to `return value_type{*this};`.
std::ranges::lazy\_split\_view::*outer\_iterator*::operator++
--------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*outer_iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) operator++(int);
```
| (2) | (since C++20) |
1) The function body is equivalent to
```
const auto end = ranges::end(parent_->base_);
if (/*cur*/() == end) {
trailing_empty_ = false;
return *this;
}
const auto [pbegin, pend] = ranges::subrange{parent_->pattern_};
if (pbegin == pend) ++/*cur*/();
else if constexpr (/*tiny_range*/<Pattern>) {
/*cur*/() = ranges::find(std::move(/*cur*/()), end, *pbegin);
if (/*cur*/() != end) {
++/*cur*/();
if (/*cur*/() == end)
trailing_empty_ = true;
}
}
else {
do {
auto [b, p] = ranges::mismatch(/*cur*/(), end, pbegin, pend);
if (p == pend) {
/*cur*/() = b;
if (/*cur*/() == end)
trailing_empty_ = true;
break; // The pattern matched; skip it
}
} while (++/*cur*/() != end);
}
return *this;
```
2) Equivalent to
```
if constexpr (ranges::forward_range<Base>) {
auto tmp = *this;
++*this;
return tmp;
} else {
++*this; // no return statement
}
```
std::ranges::lazy\_split\_view::*outer\_iterator*::*cur*()
-----------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr auto& /*cur*/() noexcept; // exposition only
```
| (1) | (since C++20) |
|
```
constexpr auto& /*cur*/() const noexcept; // exposition only
```
| (2) | (since C++20) |
This exposition-only convenience member function is referred to from `/*outer_iterator*/::operator++()`, from the non-member `operator==(const /\*outer\_iterator\*/&, [std::default\_sentinel\_t](http://en.cppreference.com/w/cpp/iterator/default_sentinel_t))`, and from some member functions of the possible implementation of [`*inner\_iterator*`](inner_iterator "cpp/ranges/lazy split view/inner iterator").
1,2) Equivalent to
`if constexpr ([ranges::forward\_range](http://en.cppreference.com/w/cpp/ranges/forward_range)<V>)
return current\_;
else
return \*parent->current\_;`
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the underlying iterators or the underlying iterator and `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` (function) |
operator==(std::ranges::split\_view::*outer\_iterator*)
--------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*outer_iterator*/& x,
const /*outer_iterator*/& y )
requires forward_range<Base>;
```
| (1) | (since C++20) |
|
```
friend constexpr bool operator==( const /*outer_iterator*/& x,
std::default_sentinel_t );
```
| (2) | (since C++20) |
1) Equivalent to `return x.current_ == y.current_ and x.trailing_empty_ == y.trailing_empty_;`.
2) Equivalent to `return x./\*cur\*/() == [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(x.parent\_->base_) and !x.trailing\_empty\_;`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*outer\_iterator*` is an associated class of the arguments.
### Nested classes
| | |
| --- | --- |
| [value\_type](value_type "cpp/ranges/lazy split view/value type")
(C++20) | the value type of the `*outer\_iterator*` (public member class) |
cpp std::ranges::lazy_split_view<V, Pattern>::inner_iterator
std::ranges::lazy\_split\_view<V, Pattern>::*inner\_iterator*
=============================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
struct /*inner_iterator*/;
```
| (1) | (since C++20) |
The return type of [`lazy_split_view::outer_iterator::value_type::begin()`](value_type "cpp/ranges/lazy split view/value type").
`Const` matches the template argument of [`outer_iterator`](outer_iterator "cpp/ranges/lazy split view/outer iterator").
The name of this class template (shown here as `/*inner_iterator*/`) is unspecified.
### Member types
| Member type | Definition |
| --- | --- |
| `*Base*` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only. |
| `iterator_concept` | equivalent to `/*outer_iterator*/<Const>::iterator_concept`, that is `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`forward_range`](../forward_range "cpp/ranges/forward range"), or `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise. |
| `iterator_category` | * Not present if `*Base*` does not model [`forward_range`](../forward_range "cpp/ranges/forward range").
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>>::iterator\_category` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::forward\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`.
* `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>>::iterator\_category` otherwise.
|
| `value_type` | `[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>`. |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>`. |
### Data members
Typical implementations of `*inner\_iterator*` hold two non-static data members:
* An iterator of type `/*outer_iterator*/<Const>` (shown here as `*i\_*` for exposition only) into the underlying [`view`](../view "cpp/ranges/view") of the parent `lazy_split_view`.
* A boolean flag (shown here as `*incremented\_*` for exposition only) that indicates whether the `operator++` was invoked on this object at least once.
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs an iterator (public member function) |
| base
(C++20) | returns the underlying iterator (public member function) |
| operator\*
(C++20) | returns the current element (public member function) |
| operator++operator++(int)
(C++20) | advances the iterator (public member function) |
### Member functions
std::ranges::lazy\_split\_view::*inner\_iterator*::*inner\_iterator*
---------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*inner_iterator*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*inner_iterator*/( /*outer_iterator*/<Const> i );
```
| (2) | (since C++20) |
1) Value initializes the exposition-only data member `*i\_*` via its default member initializer (= `/*outer_iterator*/<Const>()`).
2) Initializes `*i\_*` with `std::move(i)`. The exposition-only data member `*incremented\_*` is initialized with its default member initializer to `false`.
std::ranges::lazy\_split\_view::*inner\_iterator*::*base*
----------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr const ranges::iterator_t<Base>& base() const & noexcept;
```
| (1) | (since C++20) |
|
```
constexpr ranges::iterator_t<Base> base() &&
requires ranges::forward_range<V>;
```
| (2) | (since C++20) |
Returns a copy of the underlying iterator.
1) Copy constructs the result from the underlying iterator. Equivalent to `return i_./*cur*/();`.
2) Move constructs the result from the underlying iterator. Equivalent to `return std::move(i_./*cur*/());`.
std::ranges::lazy\_split\_view::*inner\_iterator*::operator\*
--------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*() const;
```
| | (since C++20) |
Returns the element the underlying iterator points to.
Equivalent to `return *i_./*cur*/();`.
std::ranges::lazy\_split\_view::*inner\_iterator*::operator++
--------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*inner_iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) operator++(int);
```
| (2) | (since C++20) |
1) The function body is equivalent to
`incremented_ = true;
if constexpr (<Base>) {
if constexpr (Pattern::size() == 0) {
return \*this;
}
}
++i\_./\*cur\*/();
return \*this;`
2) Equivalent to
`if constexpr ([ranges::forward\_range](http://en.cppreference.com/w/cpp/ranges/forward_range)<Base>) {
auto tmp = \*this;
++\*this;
return tmp;
} else {
++\*this; // no return statement
}`
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the iterators or the iterator and `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` (function) |
| iter\_move
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| iter\_swap
(C++20) | swaps the objects pointed to by two underlying iterators (function) |
operator==(std::ranges::split\_view::*inner\_iterator*)
--------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*inner_iterator*/& x,
const /*inner_iterator*/& y )
requires forward_range<Base>;
```
| (1) | (since C++20) |
|
```
friend constexpr bool operator==( const /*inner_iterator*/& x,
std::default_sentinel_t );
```
| (2) | (since C++20) |
1) Equivalent to `return x.i_./*cur*/() == y.i_./*cur*/();`.
2) The function body is equivalent to
```
auto [pcur, pend] = ranges::subrange{x.i_.parent_->pattern_};
auto end = ranges::end(x.i_.parent_->base_);
if constexpr (/*tiny_range*/<Pattern>) {
const auto& cur = x.i_./*cur*/();
if (cur == end) return true;
if (pcur == pend) return x.incremented_;
return *cur == *pcur;
} else {
auto cur = x.i_./*cur*/();
if (cur == end) return true;
if (pcur == pend) return x.incremented_;
do {
if (*cur != *pcur) return false;
if (++pcur == pend) return true;
} while (++cur != end);
return false;
}
```
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*inner\_iterator*` is an associated class of the arguments.
iter\_move(std::ranges::split\_view::*inner\_iterator*)
--------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr decltype(auto) iter_move( const /*inner_iterator*/& i )
noexcept(noexcept(ranges::iter_move(i.i_./*cur*/())));
```
| | (since C++20) |
Equivalent to `return [ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.i\_./\*cur\*/());`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*inner\_iterator*` is an associated class of the arguments.
iter\_swap(std::ranges::split\_view::*inner\_iterator*)
--------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr void iter_swap( const /*inner_iterator*/& x,
const /*inner_iterator*/& y )
noexcept(noexcept(ranges::iter_swap(x.i_.current, y.i_.current)))
requires std::indirectly_swappable<ranges::iterator_t<Base>>;
```
| | (since C++20) |
Equivalent to `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.i\_./\*cur\*/(), y.i\_./\*cur\*/())`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*inner\_iterator*` is an associated class of the arguments.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3591](https://cplusplus.github.io/LWG/issue3591) | C++20 | the `&&` overload of `base` might invalidate outer iterators | constraints added |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the `const&` overload of `base` returns a reference but might not be noexcept | made noexcept |
| programming_docs |
cpp std::ranges::lazy_split_view<V,Pattern>::begin std::ranges::lazy\_split\_view<V,Pattern>::begin
================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const
requires ranges::forward_range<V> && ranges::forward_range<const V>;
```
| (2) | (since C++20) |
Returns an [`*outer\_iterator*`](outer_iterator "cpp/ranges/lazy split view/outer iterator") to the first element of the `lazy_split_view`.
Let `*base\_*` be the underlying view.
1) Equivalent to
```
constexpr auto begin() {
if constexpr (ranges::forward_range<V>)
return /*outer_iterator*/</*simple_view*/<V>>{*this, ranges::begin(base_)};
else {
current_ = ranges::begin(base_);
return /*outer_iterator*/<false>{*this};
}
}
```
2) Equivalent to `return /\*outer\_iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`. ### Parameters
(none).
### Return value
[`*outer\_iterator*`](outer_iterator "cpp/ranges/lazy split view/outer iterator") to the first element.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/lazy split view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::lazy_split_view<V,Pattern>::end std::ranges::lazy\_split\_view<V,Pattern>::end
==============================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() requires ranges::forward_range<V> && ranges::common_range<V>;
```
| (1) | (since C++20) |
|
```
constexpr auto end() const;
```
| (2) | (since C++20) |
1) Returns an iterator representing the end of the [`view`](../view "cpp/ranges/view"). Equivalent to: `return /\*outer\_iterator\*/</\*simple\_view\*/<V>>{\*this, [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
2) Returns an [`*outer\_iterator*`](outer_iterator "cpp/ranges/lazy split view/outer iterator") or a `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` representing the end of the [`view`](../view "cpp/ranges/view"). Equivalent to:
```
if constexpr (ranges::forward_range<V> && ranges::forward_range<const V> &&
ranges::common_range<const V>)
return /*outer_iterator*/<true>{*this, ranges::end(base_)};
else
return std::default_sentinel;
```
### Parameters
(none).
### Return value
An [`*outer\_iterator*`](outer_iterator "cpp/ranges/lazy split view/outer iterator") or a `[std::default\_sentinel](../../iterator/default_sentinel "cpp/iterator/default sentinel")` representing the end of the [`view`](../view "cpp/ranges/view").
### Example
```
#include <iostream>
#include <ranges>
#include <string_view>
// A temporary patch until g++-12 is available online
#if (__GNUC__ < 12)
#define lazy_split_view split_view
#endif
int main()
{
constexpr std::string_view keywords{ "false float for friend" };
std::ranges::lazy_split_view kw{ keywords, ' ' };
const auto count = std::ranges::distance(kw.begin(), kw.end());
std::cout << "Words count: " << count << '\n';
}
```
Output:
```
Words count: 4
```
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/lazy split view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [end](../split_view/end "cpp/ranges/split view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function of `std::ranges::split_view<V,Pattern>`) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::basic_istream_view::iterator
std::ranges::basic\_istream\_view::*iterator*
=============================================
| | | |
| --- | --- | --- |
|
```
struct /*iterator*/;
```
| | (since C++20) |
The return type of `basic_istream_view::begin`. The name `/*iterator*/` shown here is exposition only.
`/*iterator*/` is an [`input_iterator`](../../iterator/input_iterator "cpp/iterator/input iterator"), but does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), and thus does not work with pre-C++20 [algorithms](../../algorithm "cpp/algorithm").
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_concept`(C++20) | `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` |
| `difference_type`(C++20) | `[std::ptrdiff\_t](../../types/ptrdiff_t "cpp/types/ptrdiff t")` |
| `value_type`(C++20) | `Val` |
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs an iterator (public member function) |
| operator=
(C++20) | the copy assignment operator is deleted; `/*iterator*/` is move-only (public member function) |
| operator++
(C++20) | advances the iterator (public member function) |
| operator\*
(C++20) | returns the current element (public member function) |
std::ranges::basic\_istream\_view::*iterator*::*iterator*
----------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr explicit /*iterator*/( basic_istream_view& parent );
```
| (1) | (since C++20) |
|
```
/*iterator*/( const /*iterator*/& ) = delete;
```
| (2) | (since C++20) |
|
```
/*iterator*/( /*iterator*/&& ) = default;
```
| (3) | (since C++20) |
1) Constructs an iterator from the parent `basic_istream_view`.
2) The copy constructor is deleted. The iterator is not copyable.
3) The move constructor is defaulted. The iterator is movable. std::ranges::basic\_istream\_view::*iterator*::operator=
---------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*iterator*/& operator=( const /*iterator*/& ) = delete;
```
| (1) | (since C++20) |
|
```
/*iterator*/& operator=( /*iterator*/&& ) = default;
```
| (2) | (since C++20) |
1) The copy assignment operator is deleted. The iterator is not copyable.
2) The move assignment operator is defaulted. The iterator is movable. std::ranges::basic\_istream\_view::*iterator*::operator++
----------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
void operator++(int);
```
| (2) | (since C++20) |
Reads a value from the underlying stream and stores it into the parent `basic_istream_view`.
### Return value
1) `*this`
2) (none) std::ranges::basic\_istream\_view::*iterator*::operator\*
----------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
Val& operator*() const;
```
| | (since C++20) |
Returns a reference to the stored value.
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares with a `[std::default\_sentinel\_t](../../iterator/default_sentinel_t "cpp/iterator/default sentinel t")` (public member function) |
operator==(std::ranges::basic\_istream\_view::*iterator*, std::default\_sentinel)
----------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const /*iterator*/& x, std::default_sentinel_t );
```
| | (since C++20) |
Compares an iterator with `std::default_sentinel_t`.
Returns true if `*this` does not have a parent `basic_istream_view`, or if an error has occurred on the underlying stream.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::basic_istream_view::*iterator*` is an associated class of the arguments.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | default constructor was provided as C++20 iteratorsmust be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along with the requirement |
cpp std::ranges::iota_view<W, Bound>::sentinel
std::ranges::iota\_view<W, Bound>::*sentinel*
=============================================
| | | |
| --- | --- | --- |
|
```
struct /*sentinel*/;
```
| | (since C++20) |
The return type of [`iota_view::end`](../iota_view "cpp/ranges/iota view"), used when the `iota_view` is bounded (i.e. `Bound` is not `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")`) and `Bound` and `W` are not the same type.
The name of this class (shown here as `/*sentinel*/`) is unspecified.
Typical implementation holds one data member of type `Bound` (shown here as `bound_`), typically a number.
### Member functions
std::ranges::iota\_view::*sentinel*::*sentinel*
------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( Bound bound );
```
| (2) | (since C++20) |
1) Value-initializes `bound_` via its default member initializer (`= Bound()`).
2) Initializes exposition-only data member `bound_` with `bound`.
### Non-member functions
In the following descriptions, `*value\_*` is an exposition-only data member of [`*iterator*`](iterator "cpp/ranges/iota view/iterator") from which its `operator*` copies.
operator==(std::ranges::iota\_view::*iterator*, std::ranges::iota\_view::*sentinel*)
-------------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x,
const /*sentinel*/& y );
```
| | (since C++20) |
Equivalent to: `return x.value_ == y.bound_;`.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `*sentinel*` is an associated class of the arguments.
operator-(std::ranges::iota\_view::*iterator*, std::ranges::iota\_view::*sentinel*)
------------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr std::iter_difference_t<W>
operator-(const /*iterator*/& x, const /*sentinel*/& y)
requires std::sized_sentinel_for<Bound, W>;
```
| (1) | (since C++20) |
|
```
friend constexpr std::iter_difference_t<W>
operator-(const /*sentinel*/& x, const /*iterator*/& y)
requires std::sized_sentinel_for<Bound, W>;
```
| (2) | (since C++20) |
1) Equivalent to `return x.value_ - y.bound_;`.
2) Equivalent to `return -(y.value_ - x.bound_);`. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `*sentinel*` is an associated class of the arguments.
cpp std::ranges::elements_view<V,N>::size std::ranges::elements\_view<V,N>::size
======================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::sized_range<V>;
```
| | (since C++20) |
|
```
constexpr auto size() const requires ranges::sized_range<const V>;
```
| | (since C++20) |
Returns the number of elements, i.e. `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base_)`, where `base_` is the underlying view.
### Parameters
(none).
### Return value
The number of elements.
### Example
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp std::ranges::elements_view<V,N>::sentinel
std::ranges::elements\_view<V,N>::*sentinel*
============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/; // exposition only
```
| | (since C++20) |
The return type of [`elements_view::end`](end "cpp/ranges/elements view/end") when the underlying view is not a [`common_range`](../common_range "cpp/ranges/common range").
The type `/*sentinel*/<true>` is returned by the const-qualified overload. The type `/*sentinel*/<false>` is returned by the non-const-qualified overload.
The name of this class template (shown here as `/*sentinel*/`) is unspecified.
Typical implementation holds only one data member: a sentinel `*end\_*` obtained from (possibly const-qualified) `V`.
### Member types
| Member type | Definition |
| --- | --- |
| `*Base*` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/elements view/sentinel/sentinel")
(C++20) | constructs a sentinel (public member function) |
| [base](sentinel/base "cpp/ranges/elements view/sentinel/base")
(C++20) | returns the underlying sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/elements view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`elements_view::begin`](begin "cpp/ranges/elements view/begin") (function) |
| [operator-](sentinel/operator- "cpp/ranges/elements view/sentinel/operator-")
(C++20) | computes the distance between a sentinel and an iterator returned from [`elements_view::begin`](begin "cpp/ranges/elements view/begin") (function) |
cpp std::ranges::elements_view<V,N>::base std::ranges::elements\_view<V,N>::base
======================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::elements_view<V,N>::iterator
std::ranges::elements\_view<V,N>::*iterator*
============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/;
```
| | (since C++20) |
The return type of [`elements_view::begin`](begin "cpp/ranges/elements view/begin"), and of [`elements_view::end`](end "cpp/ranges/elements view/end") when the underlying view is a [`common_range`](../common_range "cpp/ranges/common range").
The type `/*iterator*/<true>` is returned by the const-qualified overloads. The type `/*iterator*/<false>` is returned by the non-const-qualified overloads.
The name of this class template (shown here as `*iterator*`) is unspecified.
### Member types
| Member type | Definition |
| --- | --- |
| `*Base*` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
| `iterator_concept` | `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`random_access_range`](../random_access_range "cpp/ranges/random access range"), `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range"), `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`forward_range`](../forward_range "cpp/ranges/forward range"), `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise |
| `iterator_category` | Not defined if `*Base*` does not model [`forward_range`](../forward_range "cpp/ranges/forward range"). * Otherwise, if `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<N>(\*current_)` is an rvalue, the type is `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, let `C` be the type `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<std::iterator\_t<Base>>::iterator\_category`. Then if `C` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::random\_access\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`, the type is `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, the type is `C`.
|
| `value_type` | `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<[std::tuple\_element\_t](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<N, [ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>` |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` |
### Member objects
| Member name | Definition |
| --- | --- |
| `*current\_*` (private) | an object of type `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>`, the name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/elements view/iterator/iterator")
(C++20) | constructs an iterator (public member function) |
| [base](iterator/base "cpp/ranges/elements view/iterator/base")
(C++20) | returns the underlying iterator (public member function) |
| [operator\*](iterator/operator* "cpp/ranges/elements view/iterator/operator*")
(C++20) | accesses the `N`-th tuple element (public member function) |
| [operator[]](iterator/operator_at "cpp/ranges/elements view/iterator/operator at")
(C++20) | accesses an element by index (public member function) |
| [operator++operator++(int) operator--operator--(int)operator+=operator-=](iterator/operator_arith "cpp/ranges/elements view/iterator/operator arith")
(C++20) | advances or decrements the underlying iterator (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<operator>operator<=operator>=operator<=>](iterator/operator_cmp "cpp/ranges/elements view/iterator/operator cmp")
(C++20) | compares the underlying iterators (function) |
| [operator+operator-](iterator/operator_arith2 "cpp/ranges/elements view/iterator/operator arith2")
(C++20) | performs iterator arithmetic (function) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2259R1](https://wg21.link/P2259R1) | C++20 | member `iterator_category` is always defined | defined only if `*Base*` models [`forward_range`](../forward_range "cpp/ranges/forward range") |
| [LWG 3555](https://cplusplus.github.io/LWG/issue3555) | C++20 | the definition of `iterator_concept` ignores const | made to consider |
### See also
| |
| --- |
| |
| programming_docs |
cpp std::ranges::elements_view<V,N>::begin std::ranges::elements\_view<V,N>::begin
=======================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const requires ranges::range<const V>;
```
| (2) | (since C++20) |
Returns an [iterator](iterator "cpp/ranges/elements view/iterator") to the first element of the `elements_view`.
Let `base_` be the underlying view.
1) Equivalent to `return /\*iterator\*/<false>([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_));`.
2) Equivalent to `return /\*iterator\*/<true>([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_));`. ### Parameters
(none).
### Return value
Iterator to the first element.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/elements view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::elements_view<V,N>::elements_view std::ranges::elements\_view<V,N>::elements\_view
================================================
| | | |
| --- | --- | --- |
|
```
elements_view() requires std::default_initializable<V> = default;
```
| (1) | (since C++20) |
|
```
constexpr elements_view( V base );
```
| (2) | (since C++20) |
Constructs an `elements_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view. After construction, [`base()`](base "cpp/ranges/elements view/base") returns a copy of `V()`.
2) Initializes the underlying view with `std::move(r)`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | the underlying view |
### Example
```
#include <iostream>
#include <ranges>
#include <tuple>
#include <array>
using namespace std::literals;
int main()
{
const std::array<std::tuple<int, char, std::string>, 2> vt {
std::tuple{1, 'A', "α"s},
std::tuple{2, 'B', "β"s},
};
[[maybe_unused]]
auto empty = std::views::elements<0>;
auto ev0 = std::views::elements<0>(vt);
auto ev1 = std::views::elements<1>(vt);
auto ev2 = std::views::elements<2>(vt);
for (auto const& e: ev0) { std::cout << e << ' '; }
std::cout << '\n';
for (auto const& e: ev1) { std::cout << e << ' '; }
std::cout << '\n';
for (auto const& e: ev2) { std::cout << e << ' '; }
std::cout << '\n';
}
```
Output:
```
1 2
A B
α β
```
cpp std::ranges::elements_view<V,N>::end std::ranges::elements\_view<V,N>::end
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() requires (!__SimpleView<V> && !ranges::common_range<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto end() requires (!__SimpleView<V> && ranges::common_range<V>);
```
| (2) | (since C++20) |
|
```
constexpr auto end() const requires ranges::range<const V>;
```
| (3) | (since C++20) |
|
```
constexpr auto end() const requires ranges::common_range<const V>;
```
| (4) | (since C++20) |
Returns a [sentinel](sentinel "cpp/ranges/elements view/sentinel") or an [iterator](iterator "cpp/ranges/elements view/iterator") representing the end of the `elements_view`.
Let `base_` be the underlying view:
1) Equivalent to `return /\*sentinel\*/<false>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
2) Equivalent to `return /\*iterator\*/<false>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
3) Equivalent to `return /\*sentinel\*/<true>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
4) Equivalent to `return /\*iterator\*/<true>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`. ### Parameters
(none).
### Return value
1,3) sentinel which compares equal to the end iterator
2,4) iterator to the element following the last element ### Notes
`end()` returns an iterator if and only if the underlying view is a [`common_range`](../common_range "cpp/ranges/common range"): `elements_view<V,F>` models [`common_range`](../common_range "cpp/ranges/common range") whenever `V` does.
### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/elements view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::elements_view<V,F>::sentinel<Const>::sentinel
std::ranges::elements\_view<V,F>::*sentinel*<Const>::*sentinel*
===============================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( ranges::sentinel_t<Base> end );
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const && std::convertible_to<ranges::sentinel_t<V>,
ranges::sentinel_t<Base>>;
```
| (3) | (since C++20) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel.
2) Initializes the underlying sentinel with `end`.
3) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs the underlying sentinel. ### Parameters
| | | |
| --- | --- | --- |
| end | - | a sentinel representing the end of (possibly const-qualified) `V` |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp operator-(ranges::elements_view::sentinel)
operator-(ranges::elements\_view::*sentinel*)
=============================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires std::sized_sentinel_for<ranges::sentinel_t<Base>,
ranges::iterator_t</*maybe-const*/<OtherConst, V>>>
friend constexpr ranges::range_difference_t</*maybe-const*/<OtherConst, V>>
operator-( const /*iterator*/<OtherConst>& x, const /*sentinel*/& y );
```
| (1) | (since C++20) |
|
```
template< bool OtherConst >
requires std::sized_sentinel_for<ranges::sentinel_t<Base>,
ranges::iterator_t</*maybe-const*/<OtherConst, V>>>
friend constexpr ranges::range_difference_t</*maybe-const*/<OtherConst, V>>
operator-( const /*sentinel*/& y, const /*iterator*/<OtherConst>& x );
```
| (2) | (since C++20) |
Computes the distance between the underlying iterator of `x` and the underlying sentinel of `y`.
These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `elements_view::*sentinel*` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x | - | an [iterator](../iterator "cpp/ranges/elements view/iterator") |
| y | - | a sentinel |
### Return value
1) `x.base() - y.base()`
2) `y.base() - x.base()`
cpp std::ranges::elements_view<V,F>::sentinel<Const>::base std::ranges::elements\_view<V,F>::*sentinel*<Const>::base
=========================================================
| | | |
| --- | --- | --- |
|
```
constexpr ranges::sentinel_t<Base> base() const;
```
| | (since C++20) |
Returns the underlying sentinel.
### Parameters
(none).
### Return value
a copy of the underlying sentinel.
### Example
cpp operator==(ranges::elements_view::sentinel)
operator==(ranges::elements\_view::*sentinel*)
==============================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires std::sentinel_for<ranges::sentinel_t<Base>,
ranges::iterator_t</*maybe-const*/<OtherConst, V>>>
friend constexpr bool operator==( const /*iterator*/<OtherConst>& x,
const /*sentinel*/& y );
```
| | (since C++20) |
Compares the underlying iterator of `x` with the underlying sentinel of `y`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `elements_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../iterator "cpp/ranges/elements view/iterator") to compare |
| y | - | sentinel to compare |
### Return value
`x.base() == y.base()`.
### Example
cpp std::ranges::elements_view<V,F>::iterator<Const>::base std::ranges::elements\_view<V,F>::*iterator*<Const>::base
=========================================================
| | | |
| --- | --- | --- |
|
```
constexpr const ranges::iterator_t<Base>& base() const & noexcept;
```
| (1) | (since C++20) |
|
```
constexpr ranges::iterator_t<Base> base() &&;
```
| (2) | (since C++20) |
Returns the underlying iterator.
1) Returns a reference to the underlying iterator.
2) Move constructs the result from the underlying iterator. ### Parameters
(none).
### Return value
1) A reference to the underlying iterator.
1) An iterator move constructed from the underlying iterator. ### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3533](https://cplusplus.github.io/LWG/issue3533) | C++20 | the `const&` overload of `base` returns a copy of the underlying iterator | returns a reference |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the `const&` overload of `base` might not be noexcept | made noexcept |
cpp std::ranges::elements_view<V,F>::iterator<Const>::operator[] std::ranges::elements\_view<V,F>::*iterator*<Const>::operator[]
===============================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator[]( difference_type n ) const
requires ranges::random_access_range<Base>;
```
| | (since C++20) |
Returns the element at specified relative location.
Effectively returns `/*get-element*/(this->base() + n)`, where for an expression `e`, `/*get-element*/(e)` is.
* `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<N>(\*e)`, if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type,
* otherwise, `static\_cast<E>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<N>(\*e))`, where `E` is `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::tuple\_element\_t](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<N, [ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>`.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location. |
### Return value
the element at displacement `n` relative to the current location.
### Example
cpp std::ranges::elements_view<V,F>::iterator<Const>::operator* std::ranges::elements\_view<V,F>::*iterator*<Const>::operator\*
===============================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*() const;
```
| | (since C++20) |
Returns the element into `V` the underlying iterator points to.
Effectively returns `/*get-element*/(this->base())`, where for an expression `e`, `/*get-element*/(e)` is.
* `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<N>(\*e)`, if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type,
* otherwise, `static\_cast<E>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<N>(\*e))`, where `E` is `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::tuple\_element\_t](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<N, [ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>`.
### Parameters
(none).
### Return value
The current element.
### Notes
`operator->` is not provided.
### Example
cpp std::ranges::elements_view<V,F>::iterator<Const>::iterator
std::ranges::elements\_view<V,F>::*iterator*<Const>::*iterator*
===============================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/() requires std::default_initializable<ranges::iterator_t<Base>>
= default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*iterator*/( ranges::iterator_t<Base> current );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i ) requires Const &&
std::convertible_to<ranges::iterator_t<V>, ranges::iterator_t<Base>>;
```
| (3) | (since C++20) |
Construct an iterator.
1) [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying iterator `*current\_*` via its default member initializer (`= [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>()`).
2) Initializes the underlying iterator `*current\_*` with `std::move(current)`.
3) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Initializes the underlying iterator `*current\_*` with `std::move(i.current)`. ### Parameters
| | | |
| --- | --- | --- |
| current | - | an iterator into (possibly const-qualified) `V` |
| i | - | an `/*iterator*/<false>` |
### Example
cpp std::ranges::elements_view<V,F>::iterator<Const>::operator++,--,+=,-= std::ranges::elements\_view<V,F>::*iterator*<Const>::operator++,--,+=,-=
========================================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/ operator++( int )
requires ranges::forward_range<Base>;
```
| (3) | (since C++20) |
|
```
constexpr /*iterator*/& operator--()
requires ranges::bidirectional_range<Base>;
```
| (4) | (since C++20) |
|
```
constexpr /*iterator*/ operator--( int )
requires ranges::bidirectional_range<Base>;
```
| (5) | (since C++20) |
|
```
constexpr /*iterator*/& operator+=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (6) | (since C++20) |
|
```
constexpr /*iterator*/& operator-=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (7) | (since C++20) |
Increments or decrements the iterator.
Let `current_` be the underlying iterator.
1) Equivalent to `++current_; return *this;`
2) Equivalent to `++current_;`
3) Equivalent to `auto tmp = *this; ++*this; return tmp;`
4) Equivalent to `--current_; return *this;`
5) Equivalent to `auto tmp = *this; --*this; return tmp;`
6) Equivalent to `current_ += n; return *this;`
7) Equivalent to `current_ -= n; return *this;`
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
1,4,6,7) `*this`
2) (none)
3,5) a copy of `*this` that was made before the change
cpp operator==,<,>,<=,>=,<=>(ranges::elements_view::iterator)
operator==,<,>,<=,>=,<=>(ranges::elements\_view::*iterator*)
============================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires std::equality_comparable<ranges::iterator_t<Base>>;
```
| (1) | (since C++20) |
|
```
friend constexpr bool operator<( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (2) | (since C++20) |
|
```
friend constexpr bool operator>( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (3) | (since C++20) |
|
```
friend constexpr bool operator<=( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (4) | (since C++20) |
|
```
friend constexpr bool operator>=( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (5) | (since C++20) |
|
```
friend constexpr auto operator<=>( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base> &&
std::three_way_comparable<ranges::iterator_t<Base>>;
```
| (6) | (since C++20) |
Compares the underlying iterators.
1) Equivalent to `return x.base() == y.base();`.
2) Equivalent to `return x.base() < y.base();`.
3) Equivalent to `return y < x;`.
4) Equivalent to `return !(y < x);`.
5) Equivalent to `return !(x < y);`.
6) Equivalent to `return x.base() <=> y.base();`. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::elements_view::*iterator*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
Result of comparison.
cpp std::ranges::subrange<I,S,K>::size std::ranges::subrange<I,S,K>::size
==================================
| | | |
| --- | --- | --- |
|
```
constexpr /* see below */ size() const
requires (K == ranges::subrange_kind::sized);
```
| | (since C++20) |
Obtains the number of elements in the `subrange`.
The return type is the corresponding unsigned version of `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>`.
### Parameters
(none).
### Return value
`s_ - i_` explicitly converted to the return type, where `i_` and `s_` are the stored iterator and sentinel respectively, if the size is not stored.
Otherwise, the stored size.
### Notes
The size is stored into a `subrange` if and only if `K == ranges::subrange_kind::sized` but `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is not satisfied.
### Example
### See also
| | |
| --- | --- |
| [empty](empty "cpp/ranges/subrange/empty")
(C++20) | checks whether the `subrange` is empty (public member function) |
| [sizessize](../../iterator/size "cpp/iterator/size")
(C++17)(C++20) | returns the size of a container or array (function template) |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::subrange
deduction guides for `std::ranges::subrange`
============================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
subrange(I, S) -> subrange<I, S>;
```
| (1) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
subrange(I, S, /*make-unsigned-like-t*/<std::iter_difference_t<I>>) ->
subrange<I, S, ranges::subrange_kind::sized>;
```
| (2) | (since C++20) |
|
```
template< ranges::borrowed_range<R> >
subrange(R&&) ->
subrange<ranges::iterator_t<R>, ranges::sentinel_t<R>,
(ranges::sized_range<R> ||
std::sized_sentinel_for<ranges::sentinel_t<R>,
ranges::iterator_t<R>>) ?
ranges::subrange_kind::sized : ranges::subrange_kind::unsized>;
```
| (3) | (since C++20) |
|
```
template< ranges::borrowed_range<R> >
subrange(R&&, /*make-unsigned-like-t*/<ranges::range_difference_t<R>>) ->
subrange<ranges::iterator_t<R>, ranges::sentinel_t<R>,
ranges::subrange_kind::sized>;
```
| (4) | (since C++20) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `[std::ranges::subrange](../subrange "cpp/ranges/subrange")`.
1) Deduces the template arguments from the type of iterator and sentinel. The `subrange` is sized if `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is satisfied, as determined by the default template argument.
2) Deduces the template arguments from the type of iterator and sentinel, while the size of range is specified. The `subrange` is always sized.
3) Deduces the template arguments from the type of range. The `subrange` is sized if the size can be obtained from the range or its iterator and sentinel.
4) Deduces the template arguments from the type of range, while the size of range is specified. The `subrange` is always sized. The exposition-only alias template `*make-unsigned-like-t*` maps each [integer-like type](../../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable") to its corresponding unsigned version.
### Notes
While constructing the `subrange` object,
* for (1,2), the behavior is undefined if the iterator-sentinel pair does not denote a valid range,
* for (2,4), the behavior is undefined if the given size is not equal to the size of the range.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3404](https://cplusplus.github.io/LWG/issue3404) | C++20 | meaningless deduction guides from pair-like types were provided | removed |
| programming_docs |
cpp std::ranges::subrange<I,S,K>::advance std::ranges::subrange<I,S,K>::advance
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr subrange& advance( std::iter_difference_t<I> n );
```
| | (since C++20) |
If `n >= 0`, increments the stored iterator for `n` times, or until it is equal to the stored sentinel, whichever comes first. Otherwise, decrements the stored iterator for `-n` times.
The stored size, if any, is adjusted accordingly (increased by `-n` if `n < 0`, decreased by `*m*` otherwise, where `*m*` is the number of increments actually applied to the iterator).
The behavior is undefined if.
* `I` does not model [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") and `n < 0`, or
* the stored iterator is decremented after becoming a non-decrementable value.
### Parameters
| | | |
| --- | --- | --- |
| n | - | number of maximal increments of the iterator |
### Return value
`*this`.
### Complexity
Generally `min(n, [size()](size "cpp/ranges/subrange/size"))` increments or `-n` decrements on the iterator, when `n >= 0` or `n < 0` respectively.
Constant if `I` models [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), and either `n < 0` or `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is modeled.
### Notes
The stored size presents if and only if `K == ranges::subrange_kind::sized` but `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is not satisfied.
### Example
```
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <ranges>
void print(auto name, auto const sub) {
std::cout << name << ".size() == " << sub.size() << "; { ";
std::ranges::for_each(sub, [](int x) { std::cout << x << ' '; });
std::cout << "}\n";
};
int main()
{
std::array arr{1,2,3,4,5,6,7};
std::ranges::subrange sub{ std::next(arr.begin()), std::prev(arr.end()) };
print("1) sub", sub);
print("2) sub", sub.advance(3));
print("3) sub", sub.advance(-2));
}
```
Output:
```
1) sub.size() == 5; { 2 3 4 5 6 }
2) sub.size() == 2; { 5 6 }
3) sub.size() == 4; { 3 4 5 6 }
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3433](https://cplusplus.github.io/LWG/issue3433) | C++20 | the specification mishandled the cases when `n < 0` | corrected |
### See also
| | |
| --- | --- |
| [next](next "cpp/ranges/subrange/next")
(C++20) | obtains a copy of the `subrange` with its iterator advanced by a given distance (public member function) |
| [prev](prev "cpp/ranges/subrange/prev")
(C++20) | obtains a copy of the `subrange` with its iterator decremented by a given distance (public member function) |
| [advance](../../iterator/advance "cpp/iterator/advance") | advances an iterator by given distance (function template) |
| [ranges::advance](../../iterator/ranges/advance "cpp/iterator/ranges/advance")
(C++20) | advances an iterator by given distance or to a given bound (niebloid) |
cpp std::ranges::subrange<I,S,K>::subrange std::ranges::subrange<I,S,K>::subrange
======================================
| | | |
| --- | --- | --- |
|
```
subrange() requires std::default_initializable<I> = default;
```
| (1) | (since C++20) |
|
```
constexpr subrange( /*convertible-to-non-slicing*/<I> auto i, S s )
requires (!/*store-size*/);
```
| (2) | (since C++20) |
|
```
constexpr subrange( /*convertible-to-non-slicing*/<I> auto i, S s,
/*make-unsigned-like-t*/<std::iter_difference_t<I>> n )
requires (K == ranges::subrange_kind::sized);
```
| (3) | (since C++20) |
|
```
template< /*different-from*/<subrange> R >
requires ranges::borrowed_range<R> &&
/*convertible-to-non-slicing*/<ranges::iterator_t<R>, I> &&
std::convertible_to<ranges::sentinel_t<R>, S>
constexpr subrange( R&& r ) requires (!/*store-size*/ || ranges::sized_range<R>);
```
| (4) | (since C++20) |
|
```
template< ranges::borrowed_range R>
requires /*convertible-to-non-slicing*/<ranges::iterator_t<R>, I> &&
std::convertible_to<ranges::sentinel_t<R>, S>
constexpr subrange( R&& r, /*make-unsigned-like-t*/<std::iter_difference_t<I>> n )
requires (K == ranges::subrange_kind::sized)
: subrange{ranges::begin(r), ranges::end(r), n}
{}
```
| (5) | (since C++20) |
Constructs a `subrange`.
If `K == ranges::subrange\_kind::sized && <S, I>`, the size of the range is stored into the `subrange`, as if stored by a member subobject of type `/\*make-unsigned-like-t\*/<[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>>`, where `*make-unsigned-like-t*` is an exposition-only alias template that maps each [integer-like type](../../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable") to its corresponding unsigned version. Otherwise, the size is not stored. The constant `*store-size*` is `true` if the size is stored, `false` otherwise.
1) Default constructor. Value-initializes the stored iterator and sentinel as if by default member initializers `= I()` and `= S()`, respectively. If the size is stored, it is initialized with `0` as if by the default member initializer `= 0`.
2) Constructs a `subrange` from an iterator-sentinel pair. Initializes the stored iterator and sentinel with `std::move(i)` and `s` respectively. The behavior is undefined if `[i, s)` is not a valid range.
3) Constructs a `subrange` from an iterator-sentinel pair and a size hint. Initializes the stored iterator and sentinel with `std::move(i)` and `s` respectively. If the size is stored, it is initialized with `n`. The behavior is undefined if `[i, s)` is not a valid range, or `n` is not equal to `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(i, s)` explicitly converted to its type.
4) Constructs a `subrange` from a range. Equivalent to `subrange(r, static\_cast</\*make-unsigned-like-t\*/<[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>>>([ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(r)))` if the size is stored. Otherwise, equivalent to `subrange([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r), [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r))`.
5) Constructs a `subrange` from a range and a size hint. The behavior is undefined if `n` is not equal to `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r), [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r))` explicitly converted to its type. The exposition only concept `*different-from*` is modeled by types `T` and `U` if and only if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>` and `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` are different types.
The exposition only concept `*convertible-to-non-slicing*` is satisfied or modeled by `From` and `To` if and only if `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<From, To>` is satisfied or modeled respectively, and any of following conditions is satisfied:
* either `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<From>` or `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<To>` is not a pointer type,
* `[std::remove\_pointer\_t](http://en.cppreference.com/w/cpp/types/remove_pointer)<From>(\*)[]` is implicitly convertible to `[std::remove\_pointer\_t](http://en.cppreference.com/w/cpp/types/remove_pointer)<To>(\*)[]`, i.e., the conversion from `From` to `To` is at most a qualification conversion.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator that denotes the beginning of the range |
| s | - | sentinel that denotes the end of the range |
| r | - | range |
| n | - | size hint, must be equal to the size of the range |
### Notes
The exposition-only concept `*convertible-to-non-slicing*` forbids the conversion from the pointer to derived class to the pointer to base class.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3470](https://cplusplus.github.io/LWG/issue3470) | C++20 | `*convertible-to-non-slicing*` rejected some valid qualification conversions | made accepted |
| [P2393R1](https://wg21.link/P2393R1) | C++20 | implicit conversion to an integer-class type might be invalid | made explicit |
### Example
cpp std::ranges::subrange<I,S,K>::prev std::ranges::subrange<I,S,K>::prev
==================================
| | | |
| --- | --- | --- |
|
```
[[nodiscard]] constexpr subrange prev( std::iter_difference_t<I> n = 1 ) const
requires std::bidirectional_iterator<I>;
```
| | (since C++20) |
Obtains a `subrange` whose iterator is decremented by `n` times or incremented by `min(-n, [size()](size "cpp/ranges/subrange/size"))` times respect to that of `*this`, when `n >= 0` or `n < 0` respectively.
Equivalent to `auto tmp = *this; tmp.advance(-n); return tmp;`. The behavior is undefined if the iterator is decremented after being a non-decrementable value.
### Parameters
| | | |
| --- | --- | --- |
| n | - | number of minimal decrements of the iterator |
### Return value
A `subrange` whose iterator is decremented by `n` times or incremented by `min(-n, [size()](size "cpp/ranges/subrange/size"))` times respect to that of `*this`, when `n >= 0` or `n < 0` respectively.
### Complexity
Generally `n` decrements or `min(-n, [size()](size "cpp/ranges/subrange/size"))` increments on the iterator, when `n >= 0` or `n < 0` respectively.
Constant if `I` models [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), and either `n >= 0` or `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is modeled.
### Example
### See also
| | |
| --- | --- |
| [next](next "cpp/ranges/subrange/next")
(C++20) | obtains a copy of the `subrange` with its iterator advanced by a given distance (public member function) |
| [advance](advance "cpp/ranges/subrange/advance")
(C++20) | advances the iterator by given distance (public member function) |
| [prev](../../iterator/prev "cpp/iterator/prev")
(C++11) | decrement an iterator (function template) |
| [ranges::prev](../../iterator/ranges/prev "cpp/iterator/ranges/prev")
(C++20) | decrement an iterator by a given distance or to a bound (niebloid) |
cpp std::ranges::subrange<I,S,K>::next std::ranges::subrange<I,S,K>::next
==================================
| | | |
| --- | --- | --- |
|
```
[[nodiscard]] constexpr subrange next(std::iter_difference_t<I> n = 1) const&
requires std::forward_iterator<I>;
```
| (1) | (since C++20) |
|
```
[[nodiscard]] constexpr subrange next(std::iter_difference_t<I> n = 1) &&;
```
| (2) | (since C++20) |
1) Obtains a `subrange` whose iterator is incremented by `min(n, [size()](size "cpp/ranges/subrange/size"))` times or decremented by `-n` times respect to that of `*this`, when `n >= 0` or `n < 0` respectively. Equivalent to `auto tmp = *this; tmp.advance(n); return tmp;`.
2) Increments the stored iterator by `min(n, [size()](size "cpp/ranges/subrange/size"))` times or decremented it by `-n` times, when `n >= 0` or `n < 0` respectively, and then move-constructs the result from `*this`. Equivalent to `advance(n); return std::move(*this);`. The behavior is undefined if:
* `I` does not model [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") and `n < 0`, or
* the stored iterator is decremented after becoming a non-decrementable value.
### Parameter
| | | |
| --- | --- | --- |
| n | - | number of maximal increments of the iterator |
### Return value
A `subrange` whose iterator is incremented by `min(n, [size()](size "cpp/ranges/subrange/size"))` times or decremented by `-n` times respect to the original value of that of `*this`, when `n >= 0` or `n < 0` respectively.
### Complexity
Generally `min(n, [size()](size "cpp/ranges/subrange/size"))` increments or `-n` decrements on the iterator, when `n >= 0` or `n < 0` respectively.
Constant if `I` models [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), and either `n < 0` or `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>` is modeled.
### Notes
A call to (2) may leave `*this` in a valid but unspecified state, depending on the behavior of the move constructor of `I` and `S`.
### Example
### See also
| | |
| --- | --- |
| [prev](prev "cpp/ranges/subrange/prev")
(C++20) | obtains a copy of the `subrange` with its iterator decremented by a given distance (public member function) |
| [advance](advance "cpp/ranges/subrange/advance")
(C++20) | advances the iterator by given distance (public member function) |
| [next](../../iterator/next "cpp/iterator/next")
(C++11) | increment an iterator (function template) |
| [ranges::next](../../iterator/ranges/next "cpp/iterator/ranges/next")
(C++20) | increment an iterator by a given distance or to a bound (niebloid) |
cpp std::ranges::subrange<I,S,K>::operator PairLike std::ranges::subrange<I,S,K>::operator PairLike
===============================================
| | | |
| --- | --- | --- |
|
```
template< /*different-from*/<subrange> PairLike >
requires /*pair-like-convertible-from*/<PairLike, const I&, const S&>
constexpr operator PairLike() const;
```
| (1) | (since C++20) |
| Helper concepts | | |
|
```
template< class T >
concept /*pair-like*/ = // exposition only
!std::is_reference_v<T> && requires(T t) {
typename std::tuple_size<T>::type; // ensures std::tuple_size<T> is complete
requires std::derived_from<std::tuple_size<T>,
std::integral_constant<std::size_t, 2>>;
typename std::tuple_element_t<0, std::remove_const<T>>;
typename std::tuple_element_t<1, std::remove_const<T>>;
{ std::get<0>(t) } -> std::convertible_to<const std::tuple_element_t<0, T>&>;
{ std::get<1>(t) } -> std::convertible_to<const std::tuple_element_t<1, T>&>;
};
```
| (2) | (since C++20) |
|
```
template< class T, class U, class V >
concept /*pair-like-convertible-from*/ = // exposition only
!ranges::range<T> && /*pair-like*/<T> &&
std::constructible_from<T, U, V> &&
/*convertible-to-non-slicing*/<U, std::tuple_element_t<0, T>> &&
std::convertible_to<V, std::tuple_element_t<1, T>>;
```
| (3) | (since C++20) |
1) Converts `subrange` to a pair-like type (i.e. a type models `*pair-like*`, see below). Equivalent to `return PairLike(i_, s_);`, where `i_` and `s_` are the stored iterator and sentinel respectively. This conversion function has additional constraints imposed by `*pair-like-convertible*` (see below).
2) The exposition-only concept `*pair-like*` specifies a type is pair-like. Generally, an expression `e` of a pair-like type can be used for [structured binding](../../language/structured_binding "cpp/language/structured binding") (i.e. `auto const& [x, y] = e;` is generally well-formed). Like standard concepts, this concept is modeled if it is satisfied and all concepts it subsumes are modeled.
3) The exposition-only concept `*pair-like-convertible-from*` refines `*pair-like*`. It rejects [`range`](../range "cpp/ranges/range") types and requires that `U` and `V` are convertible to the first and second element type of `T` respectively, and the conversion from `U` (which will be replaced by `const I&`) to the first element type is non-slicing (see [`convertible-to-non-slicing`](subrange "cpp/ranges/subrange/subrange")). Like standard concepts, this concept is modeled if it is satisfied and all concepts it subsumes are modeled. The exposition only concept `*different-from*` is modeled by types `T` and `U` if and only if `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>` and `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>` are different types.
### Parameters
(none).
### Return value
A `PairLike` value direct-initialized with the stored iterator and sentinel.
### Notes
Following types in the standard library are pair-like:
* `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<T, U>`
* `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<T, U>`
* `[std::array](http://en.cppreference.com/w/cpp/container/array)<T, 2>`
* `std::[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<I, S, K>`
A program-defined type derived from one of these types can be a pair-like type, if.
* `std::tuple_size` and `std::tuple_element` are correctly specialized for it, and
* calls to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<0>` and `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<1>` for its value are well-formed.
Since `subrange` specializations are [`range`](../range "cpp/ranges/range") types, conversion to them are not performed via this conversion function.
`[std::array](../../container/array "cpp/container/array")` specializations cannot be converted from `subrange`, since they are [`range`](../range "cpp/ranges/range") types.
### Example
```
#include <iostream>
#include <ranges>
#include <string>
#include <utility>
using legacy_strview = std::pair<
std::string::const_iterator,
std::string::const_iterator
>;
void legacy_print(legacy_strview p)
{
for (; p.first != p.second; ++p.first)
std::cout << *p.first << ' ';
std::cout << '\n';
}
int main()
{
std::string dat{"ABCDE"};
for (auto v{ std::ranges::subrange{dat} }; v; v = {v.begin(), v.end() - 1}) {
/*...*/
legacy_print(legacy_strview{v});
}
}
```
Output:
```
A B C D E
A B C D
A B C
A B
A
```
cpp std::ranges::subrange<I,S,K>::empty std::ranges::subrange<I,S,K>::empty
===================================
| | | |
| --- | --- | --- |
|
```
constexpr bool empty() const;
```
| | (since C++20) |
Checks whether the `subrange` is empty, i.e. the stored iterator and sentinel compare equal.
### Parameters
(none).
### Return value
`true` if the stored iterator and sentinel compare equal, `false` otherwise.
### Example
### See also
| | |
| --- | --- |
| [size](size "cpp/ranges/subrange/size")
(C++20) | obtains the size of the `subrange` (public member function) |
| [empty](../../iterator/empty "cpp/iterator/empty")
(C++17) | checks whether the container is empty (function template) |
| [ranges::empty](../empty "cpp/ranges/empty")
(C++20) | checks whether a range is empty (customization point object) |
cpp std::ranges::get(std::ranges::subrange)
std::ranges::get(std::ranges::subrange)
=======================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< std::size_t N, class I, class S, ranges::subrange_kind K >
requires ((N == 0 && std::copyable<I>) || N == 1)
constexpr auto get( const ranges::subrange<I, S, K>& r );
```
| (1) | (since C++20) |
|
```
template< std::size_t N, class I, class S, ranges::subrange_kind K >
requires (N < 2)
constexpr auto get( ranges::subrange<I, S, K>&& r );
```
| (2) | (since C++20) |
|
```
namespace std { using ranges::get; }
```
| (3) | (since C++20) |
1) Obtains the iterator or sentinel from a `subrange` lvalue (or a const rvalue) when `N == 0` or `N == 1`, respectively. It is mainly provided for structured binding support.
2) Same as (1), except that it takes a non-const `subrange` rvalue.
3) (1-2) are imported into namespace `std`, which simplifies their usage and makes every `subrange` with a copyable iterator a pair-like type. ### Parameters
| | | |
| --- | --- | --- |
| r | - | a `subrange` |
### Return value
1) An iterator or sentinel copy constructed from the stored one when `N == 0` or `N == 1`, respectively.
2) Same as (1), except that the iterator is move constructed if `N == 0` and `I` does not satisfy [`copyable`](../../concepts/copyable "cpp/concepts/copyable"). ### Possible implementation
| |
| --- |
|
```
template<std::size_t N, class I, class S, std::ranges::subrange_kind K>
requires ((N == 0 && std::copyable<I>) || N == 1)
constexpr auto get(const std::ranges::subrange<I, S, K>& r)
{
if constexpr (N == 0)
return r.begin();
else
return r.end();
}
template<std::size_t N, class I, class S, std::ranges::subrange_kind K>
requires (N < 2)
constexpr auto get(std::ranges::subrange<I, S, K>&& r)
{
if constexpr (N == 0)
return r.begin(); // may perform move construction
else
return r.end();
}
```
|
### Example
```
#include <array>
#include <iostream>
#include <iterator>
#include <ranges>
int main()
{
std::array a{1, -2, 3, -4};
std::ranges::subrange sub_a{ std::next(a.begin()), std::prev(a.end()) };
std::cout << *std::ranges::get<0>(sub_a) << ' ' // == *(begin(a) + 1)
<< *std::get<1>(sub_a) << '\n'; // == *(end(a) - 1)
*std::get<0>(sub_a) = 42; // OK
// *std::get<2>(sub_a) = 13; // hard error: index can only be 0 or 1
}
```
Output:
```
-2 -4
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3589](https://cplusplus.github.io/LWG/issue3589) | C++20 | the overload for const lvalue was ill-formed if `N == 0`and `I` does not model [`copyable`](../../concepts/copyable "cpp/concepts/copyable") | it is removed from the overload set |
### See also
| | |
| --- | --- |
| [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer |
| [std::get(std::tuple)](../../utility/tuple/get "cpp/utility/tuple/get")
(C++11) | tuple accesses specified element (function template) |
| [std::get(std::pair)](../../utility/pair/get "cpp/utility/pair/get")
(C++11) | accesses an element of a `pair` (function template) |
| [std::get(std::array)](../../container/array/get "cpp/container/array/get")
(C++11) | accesses an element of an `array` (function template) |
| programming_docs |
cpp std::ranges::subrange<I,S,K>::begin std::ranges::subrange<I,S,K>::begin
===================================
| | | |
| --- | --- | --- |
|
```
constexpr I begin() const requires std::copyable<I>;
```
| (1) | (since C++20) |
|
```
[[nodiscard]] constexpr I begin() requires (!std::copyable<I>);
```
| (2) | (since C++20) |
Obtains the iterator to the first element of the `subrange`, or the end iterator if the view is empty.
![range-begin-end.svg]()
1) Returns a copy of the stored iterator if the iterator type is copyable.
2) Returns an iterator move-constructed from the stored iterator if the iterator type is not copyable. ### Parameters
(none).
### Return value
1) An iterator copy-constructed from the stored iterator.
2) An iterator move-constructed from the stored iterator. ### Notes
A call to (2) may leave the stored iterator in a valid but unspecified state, depending on the behavior of the move constructor of `I`.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/subrange/end")
(C++20) | obtains the sentinel (public member function) |
| [begincbegin](../../iterator/begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::subrange<I,S,K>::end std::ranges::subrange<I,S,K>::end
=================================
| | | |
| --- | --- | --- |
|
```
constexpr S end() const;
```
| | (since C++20) |
Returns the sentinel indicating the end of the `subrange`.
![range-begin-end.svg]()
### Parameters
(none).
### Return value
A sentinel copy-constructed from the stored sentinel.
### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/subrange/begin")
(C++20) | obtains the iterator (public member function) |
| [endcend](../../iterator/end "cpp/iterator/end")
(C++11)(C++14) | returns an iterator to the end of a container or array (function template) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::filter_view<V,Pred>::sentinel
std::ranges::filter\_view<V,Pred>::*sentinel*
=============================================
| | | |
| --- | --- | --- |
|
```
class /*sentinel*/;
```
| | (since C++20) |
The return type of [`filter_view::end`](../filter_view "cpp/ranges/filter view") when the underlying [`view`](../view "cpp/ranges/view") type (`V`) does not model [`common_range`](../common_range "cpp/ranges/common range").
The name `*sentinel*` is for exposition purposes only.
### Data members
Typical implementations of `*sentinel*` hold only one non-static data member: the sentinel of the underlying [`view`](../view "cpp/ranges/view") (shown here as `*end\_*` for exposition only).
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs a sentinel (public member function) |
| base
(C++20) | returns the underlying sentinel (public member function) |
std::ranges::filter\_view::*sentinel*::*sentinel*
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( filter_view& parent );
```
| (2) | (since C++20) |
1) Value-initializes `*end\_*` via its default member initializer (`= [ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>()`).
2) Initializes `*end\_*` with `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(parent.base\_)`.
std::ranges::filter\_view::*sentinel*::base
--------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr ranges::sentinel_t<V> base() const;
```
| | (since C++20) |
Equivalent to `return end_;`.
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the underlying iterator and the underlying sentinel (function) |
operator==(std::ranges::filter\_view::*iterator*, std::ranges::filter\_view::*sentinel*)
-----------------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x,
const /*sentinel*/& y );
```
| | (since C++20) |
Equivalent to `return x.current_ == y.end_;`, where `*current\_*` is the underlying iterator wrapped in [`filter_view::*iterator*`](iterator "cpp/ranges/filter view/iterator").
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::filter_view::*sentinel*` is an associated class of the arguments.
cpp std::ranges::filter_view<V,Pred>::iterator
std::ranges::filter\_view<V,Pred>::*iterator*
=============================================
| | | |
| --- | --- | --- |
|
```
class /*iterator*/;
```
| | (since C++20) |
The return type of [`filter_view::begin`](../filter_view "cpp/ranges/filter view"). The name `*iterator*` is for exposition purposes only.
This is a [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") if `V` models [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range"), a [`forward_iterator`](../../iterator/forward_iterator "cpp/iterator/forward iterator") if `V` models [`forward_range`](../forward_range "cpp/ranges/forward range"), and [`input_iterator`](../../iterator/input_iterator "cpp/iterator/input iterator") otherwise.
Modification of the element denoted by this iterator is permitted, but results in undefined behavior if the resulting value does not satisfy the filter's predicate.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_concept` | * `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `V` models [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range"),
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `V` models [`forward_iterator`](../../iterator/forward_iterator "cpp/iterator/forward iterator"),
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise.
|
| `iterator_category` | Defined if and only if `V` models [`forward_range`](../forward_range "cpp/ranges/forward range"). Let `C` be the type `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>::iterator\_category`.* `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `C` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::bidirectional\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`,
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `C` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::forward\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`,
* `C` otherwise.
|
| `value_type` | `[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` |
### Data members
Typical implementations of `*iterator*` hold two non-static data members:
* an iterator of type `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>` into the underlying [`view`](../view "cpp/ranges/view") (shown here as `*current\_*` for exposition only), and
* a pointer of type `[ranges::filter\_view](http://en.cppreference.com/w/cpp/ranges/filter_view)<V, Pred>\*` to the parent `filter_view` object (shown here as `*parent\_*` for exposition only).
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs an iterator (public member function) |
| base
(C++20) | returns the underlying iterator (public member function) |
| operator\*operator->
(C++20) | forwards to the underlying iterator (public member function) |
| operator++operator++(int)operator--operator--(int)
(C++20) | advances or decrements the iterator (public member function) |
std::ranges::filter\_view::*iterator*::*iterator*
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*iterator*/()
requires std::default_initializable<ranges::iterator_t<V>> = default;
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/( filter_view& parent,
ranges::iterator_t<V> current );
```
| (2) | (since C++20) |
1) Initializes `*current\_*` and `*parent\_*` with their default member initializers, which are `= [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>()` and `= nullptr` respectively.
2) Initializes `*current\_*` with `std::move(current)` and `*parent\_*` with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)`.
std::ranges::filter\_view::*iterator*::base
--------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr const ranges::iterator_t<V>& base() const & noexcept;
```
| (1) | (since C++20) |
|
```
constexpr ranges::iterator_t<V> base() &&;
```
| (2) | (since C++20) |
1) Equivalent to `return current_;`.
2) Equivalent to `return std::move(current_);`.
std::ranges::filter\_view::*iterator*::operator\*,->
-----------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr ranges::range_reference_t<V> operator*() const;
```
| (1) | (since C++20) |
|
```
constexpr ranges::iterator_t<V> operator->() const
requires /*has-arrow*/<ranges::iterator_t<V>> &&
std::copyable<ranges::iterator_t<V>>;
```
| (2) | (since C++20) |
1) Equivalent to `return *current_;`.
2) Equivalent to `return current_;`.
For a type `I`, `/*has-arrow*/<I>` is modeled or satisfied, if and only if `I` models or satisfies [`input_iterator`](../../iterator/input_iterator "cpp/iterator/input iterator") respectively, and either `I` is a pointer type or `requires(I i){ i.operator->(); }` is `true`.
std::ranges::filter\_view::*iterator*::operator++
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/ operator++( int )
requires ranges::forward_range<V>;
```
| (3) | (since C++20) |
1) Equivalent to
`current_ = [ranges::find\_if](http://en.cppreference.com/w/cpp/algorithm/ranges/find)(std::move(++current_), [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(parent_->base_),
[std::ref](http://en.cppreference.com/w/cpp/utility/functional/ref)(\*parent\_->pred\_));
return \*this;`.
2) Equivalent to `++*this;`.
3) Equivalent to `auto tmp = *this; ++*this; return tmp;`.
std::ranges::filter\_view::*iterator*::operator--
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator--()
requires ranges::bidirectional_range<V>;
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/ operator--( int )
requires ranges::bidirectional_range<V>;
```
| (2) | (since C++20) |
1) Equivalent to
`do
--current\_;
while ((\*parent\_->pred\_, \*current\_));
return \*this;`.
2) Equivalent to `auto tmp = *this; --*this; return tmp;`.
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the underlying iterators (function) |
| iter\_move
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| iter\_swap
(C++20) | swaps the objects pointed to by two underlying iterators (function) |
operator==(std::ranges::filter\_view::*iterator*)
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires std::equality_comparable<ranges::iterator_t<V>>;
```
| | (since C++20) |
Equivalent to `return x.current_ == y.current_;`.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::filter_view::*iterator*` is an associated class of the arguments.
iter\_move(std::ranges::filter\_view::*iterator*)
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr ranges::range_rvalue_reference_t<V>
iter_move( const /*iterator*/& i )
noexcept(noexcept(ranges::iter_move(i.current_)));
```
| | (since C++20) |
Equivalent to `return [ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.current\_);`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::filter_view::*iterator*` is an associated class of the arguments.
iter\_swap(std::ranges::filter\_view::*iterator*)
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr void iter_swap( const /*iterator*/& x, const /*iterator*/& y )
noexcept(noexcept(ranges::iter_swap(x.current_, y.current_)))
requires std::indirectly_swappable<ranges::iterator_t<V>>;
```
| | (since C++20) |
Equivalent to `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.current\_, y.current\_)`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::filter_view::*iterator*` is an associated class of the arguments.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2259R1](https://wg21.link/P2259R1) | C++20 | member type `iterator_category` was always defined | defined only if `V` is a [`forward_range`](../forward_range "cpp/ranges/forward range") |
| [LWG 3533](https://cplusplus.github.io/LWG/issue3533) | C++20 | the `const&` overload of `base` copied the underlying iterator | returns a reference to it |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the `const&` overload of `base` might not be noexcept | made noexcept |
cpp deduction guides for std::ranges::join_with_view
deduction guides for `std::ranges::join_with_view`
==================================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class R, class P >
join_with_view( R&&, P&& ) -> join_with_view<views::all_t<R>, views::all_t<P>>;
```
| (1) | (since C++23) |
|
```
template< class R >
join_with_view( R&&, ranges::range_value_t<ranges::range_reference_t<R>> )
-> join_with_view<views::all_t<R>,
ranges::single_view<
ranges::range_value_t<ranges::range_reference_t<R>>>;
```
| (2) | (since C++23) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `join_with_view` to allow deduction from a range and a delimiter.
1) The delimiter is a range of elements.
2) The delimiter is a single element. ### Example
cpp std::ranges::join_with_view<V,Pattern>::sentinel
std::ranges::join\_with\_view<V,Pattern>::*sentinel*
====================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/
```
| | (since C++23) |
The return type of [`join_with_view::end`](end "cpp/ranges/join with view/end") when either of the underlying ranges (`V` or `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>`) is not a [`common_range`](../common_range "cpp/ranges/common range"), or when the parent `join_with_view` is not a [`forward_range`](../forward_range "cpp/ranges/forward range").
If either `V` or `Pattern` is not a [simple view](../../ranges#Helper_concepts "cpp/ranges"), `Const` is true for sentinels returned from the const overloads, and false otherwise. If `V` and `Pattern` are simple views, `Const` is true.
The name of this class template (shown here as `/*sentinel*/`) is unspecified.
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/join with view/sentinel/sentinel")
(C++23) | constructs a sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/join with view/sentinel/operator cmp")
(C++23) | compares a sentinel with an iterator returned from [`join_with_view::begin`](begin "cpp/ranges/join with view/begin") (function) |
cpp std::ranges::join_with_view<V,Pattern>::base std::ranges::join\_with\_view<V,Pattern>::base
==============================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++23) |
|
```
constexpr V base() &&;
```
| (2) | (since C++23) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::join_with_view<V,Pattern>::iterator
std::ranges::join\_with\_view<V,Pattern>::*iterator*
====================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/
```
| | (since C++23) |
The return type of [`join_with_view::begin`](begin "cpp/ranges/join with view/begin"), and of [`join_with_view::end`](end "cpp/ranges/join with view/end") when both the outer range `V` and the inner range `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` satisfy [`common_range`](../common_range "cpp/ranges/common range") and the parent `join_with_view` is a [`forward_range`](../forward_range "cpp/ranges/forward range").
If either `V` or `Pattern` is not a [simple view](../../ranges#Helper_concepts "cpp/ranges"), `Const` is true for iterators returned from the const overloads, and false otherwise. If `V` and `Pattern` are simple views, `Const` is true if and only if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` is a reference.
The name of this class template (shown here as `/*iterator*/`) is unspecified.
### Member types
| Member type | Definition |
| --- | --- |
| `Parent` (private) | `const join_view<V>` if `Const` is `true`, otherwise `join_view<V>`. The name is for exposition only. |
| `Base` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only. |
| `InnerBase` (private) | `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>`. The name is for exposition only. |
| `PatternBase` (private) | `const Pattern` if `Const` is `true`, otherwise `Pattern`. The name is for exposition only. |
| `iterator_concept` | * `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
+ `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type,
+ `Base`, `InnerBase` and `PatternBase` each model [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range"), and
+ `InnerBase` and `PatternBase` each model [`common_range`](../common_range "cpp/ranges/common range");
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
+ `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type, and
+ `Base` and `InnerBase` each model [`forward_range`](../forward_range "cpp/ranges/forward range");
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise.
|
| `iterator_category` | Defined only if `iterator::iterator_concept` (see above) denotes `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`. Let `*OUTERC*` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>>::iterator\_category`, `*INNERC*` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<InnerBase>>::iterator\_category`, and `*PATTERNC*` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<PatternBase>>::iterator\_category`.* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
```
std::common_reference_t<ranges::range_reference_t<InnerBase>,
ranges::range_reference_t<PatternBase>>
```
is not an lvalue reference;* `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if:
+ `*OUTERC*`, `*INNERC*`, and `*PATTERNC*` each model `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::bidirectional\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>` and
+ `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` and `PatternBase` each model [`common_range`](../common_range "cpp/ranges/common range");
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `*OUTERC*`, `*INNERC*`, and `*PATTERNC*` each model `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::forward\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`;
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise.
|
| `value_type` | `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<InnerBase>, [ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<PatternBase>>` |
| `difference_type` |
```
std::common_type_t<ranges::range_difference_t<Base>,
ranges::range_difference_t<InnerBase>,
ranges::range_difference_t<PatternBase>>
```
|
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/join with view/iterator/iterator")
(C++23) | constructs an iterator (public member function) |
| [operator\*](iterator/operator* "cpp/ranges/join with view/iterator/operator*")
(C++23) | accesses the element (public member function) |
| [operator++operator++(int)operator--operator--(int)](iterator/operator_arith "cpp/ranges/join with view/iterator/operator arith")
(C++23) | advances or decrements the underlying iterators (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](iterator/operator_cmp "cpp/ranges/join with view/iterator/operator cmp")
(C++23) | compares the underlying iterators (function) |
| [iter\_move](iterator/iter_move "cpp/ranges/join with view/iterator/iter move")
(C++23) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](iterator/iter_swap "cpp/ranges/join with view/iterator/iter swap")
(C++23) | swaps the objects pointed to by two underlying iterators (function) |
| programming_docs |
cpp std::ranges::join_with_view<V,Pattern>::join_with_view std::ranges::join\_with\_view<V,Pattern>::join\_with\_view
==========================================================
| | | |
| --- | --- | --- |
|
```
join_with_view()
requires std::default_initializable<V> &&
std::default_initializable<Pattern> = default;
```
| (1) | (since C++23) |
|
```
constexpr join_with_view( V base, Pattern pattern );
```
| (2) | (since C++23) |
|
```
template< ranges::input_range R >
requires std::constructible_from<V, views::all_t<R>> &&
std::constructible_from<Pattern,
ranges::single_view<
ranges::range_value_t<ranges::range_reference_t<V>>>>
constexpr join_with_view( R&& r,
ranges::range_value_t<ranges::range_reference_t<V>> e );
```
| (3) | (since C++23) |
Constructs a `join_with_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and the pattern.
2) Initializes the underlying view with `std::move(base)` and the stored pattern with `std::move(pattern)`.
3) Initializes the underlying view with `[views::all](http://en.cppreference.com/w/cpp/ranges/all_view)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<R>(r))` and the stored pattern with `[views::single](http://en.cppreference.com/w/cpp/ranges/single_view)(std::move(e))`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | a view of ranges to be flattened |
| pattern | - | view to be used as the delimiter |
| e | - | element to be used as the delimiter |
### Example
cpp std::ranges::join_with_view<V,Pattern>::begin std::ranges::join\_with\_view<V,Pattern>::begin
===============================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| (1) | (since C++23) |
|
```
constexpr auto begin() const
requires ranges::input_range<const V> &&
ranges::forward_range<const Pattern> &&
std::is_reference_v<ranges::range_reference_t<const V>>;
```
| (2) | (since C++23) |
Returns an [iterator](iterator "cpp/ranges/join with view/iterator") to the first element of the `join_with_view`.
Let `base_` denote the underlying view:
1) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};` if `V` and `Pattern` each model [`__SimpleView`](../../ranges#Helper_concepts "cpp/ranges") and `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` is a reference type; otherwise equivalent to `return /\*iterator\*/<false>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`.
2) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`. ### Parameters
(none).
### Return value
An iterator to the first element of the `join_with_view`, as described above.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/join with view/end")
(C++23) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::join_with_view<V,Pattern>::end std::ranges::join\_with\_view<V,Pattern>::end
=============================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end();
```
| (1) | (since C++23) |
|
```
constexpr auto end() const
requires ranges::input_range<const V> &&
ranges::forward_range<const Pattern> &&
std::is_reference_v<ranges::range_reference_t<const V>>;
```
| (2) | (since C++23) |
Returns an [iterator](iterator "cpp/ranges/join with view/iterator") or a [sentinel](sentinel "cpp/ranges/join with view/sentinel") that compares equal to the end iterator of the `join_with_view`.
Let `base_` denote the underlying view:
1) Equivalent to:
```
if constexpr (ranges::forward_range<V> &&
std::is_reference_v<ranges::range_reference_t<V>> &&
ranges::forward_range<ranges::range_reference_t<V>> &&
ranges::common_range<V> &&
ranges::common_range<ranges::range_reference_t<V>>)
return /*iterator*/<__SimpleView<V> && __SimpleView<Pattern>>{*this, ranges::end(base_)};
else
return /*sentinel*/<__SimpleView<V> && __SimpleView<Pattern>>{*this};
```
2) Equivalent to:
```
if constexpr (ranges::forward_range<const V> &&
ranges::forward_range<ranges::range_reference_t<const V>> &&
ranges::common_range<const V> &&
ranges::common_range<ranges::range_reference_t<const V>>)
return /*iterator*/<true>{*this, ranges::end(base_)};
else
return /*sentinel*/<true>{*this};
```
### Parameters
(none).
### Return value
An iterator or sentinel representing the end of the `join_with_view`, as described above.
### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/join with view/begin")
(C++23) | returns an iterator to the beginning (public member function) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::join_with_view<V,Pattern>::sentinel<Const>::sentinel
std::ranges::join\_with\_view<V,Pattern>::*sentinel*<Const>::*sentinel*
=======================================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++23) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const &&
std::convertible_to<ranges::sentinel_t<V>, ranges::sentinel_t<const V>>;
```
| (2) | (since C++23) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel.
2) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs the underlying sentinel with the corresponding member of `i`. This type also has a private constructor which is used by `join_with_view::end`. This constructor is not accessible to users.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp operator==(ranges::join_with_view::iterator, ranges::join_with_view::sentinel) operator==(ranges::join\_with\_view::*iterator*, ranges::join\_with\_view::*sentinel*)
======================================================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/<Const>& x, const /*sentinel*/& y );
```
| | (since C++23) |
Compares the underlying iterator of `x` with the underlying sentinel of `y`. The comparison returns true if the underlying outer iterator stored in `x` is the end iterator.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_with_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../iterator "cpp/ranges/join with view/iterator") to compare |
| y | - | sentinel to compare |
### Return value
`x.outer_it_ == y.end_`, where `outer_it_` denotes the underlying outer iterator, `end_` denotes the underlying sentinel.
### Example
cpp iter_move(ranges::join_with_view::iterator) iter\_move(ranges::join\_with\_view::*iterator*)
================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr decltype(auto) iter_move( const /*iterator*/& i );
```
| | (since C++23) |
Returns the result of applying `[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)` to the stored inner iterator. The result is implicitly converted to:
```
std::common_reference_t<ranges::range_rvalue_reference_t<InnerBase>,
ranges::range_rvalue_reference_t<PatternBase>>
```
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_with_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator |
### Return value
The result of applying `[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)` to the stored inner iterator, implicitly converted to the return type.
cpp std::ranges::join_with_view<V,Pattern>::iterator<Const>::operator* std::ranges::join\_with\_view<V,Pattern>::*iterator*<Const>::operator\*
=======================================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*() const;
```
| | (since C++23) |
Returns the current element in the joined view.
The return type is:
```
std::common_reference_t<ranges::range_reference_t<InnerBase>,
ranges::range_reference_t<PatternBase>>
```
### Parameters
(none).
### Return value
The current element.
### Example
cpp std::ranges::join_with_view<V,Pattern>::iterator<Const>::iterator
std::ranges::join\_with\_view<V,Pattern>::*iterator*<Const>::*iterator*
=======================================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/() requires std::default_initializable<ranges::iterator_t<Base>> = default;
```
| (1) | (since C++23) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i )
requires Const &&
std::convertible_to<ranges::iterator_t<V>, ranges::iterator_t<Base>> &&
std::convertible_to<ranges::iterator_t<ranges::range_reference_t<V>>,
ranges::iterator_t<InnerBase>> &&
std::convertible_to<ranges::iterator_t<Pattern>, ranges::iterator_t<PatternBase>>;
```
| (2) | (since C++23) |
Construct an iterator.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying iterator to `Base` and the iterator to `PatternBase`, and initializes the pointer to parent `join_with_view` with `nullptr`.
2) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Move constructs corresponding members. This iterator also has a private constructor which is used by `join_with_view::begin` and `join_with_view::end`. This constructor is not accessible to users.
### Parameters
| | | |
| --- | --- | --- |
| i | - | an `/*iterator*/<false>` |
### Example
cpp std::ranges::join_with_view<V,Pattern>::iterator<Const>::operator++,-- std::ranges::join\_with\_view<V,Pattern>::*iterator*<Const>::operator++,--
==========================================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++23) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++23) |
|
```
constexpr /*iterator*/ operator++( int )
requires std::is_reference_v<InnerBase> &&
ranges::forward_range<Base> && ranges::forward_range<InnerBase>;
```
| (3) | (since C++23) |
|
```
constexpr /*iterator*/& operator--()
requires std::is_reference_v<InnerBase> &&
ranges::bidirectional_range<Base> &&
ranges::bidirectional_range<InnerBase> &&
ranges::common_range<InnerBase> &&
ranges::bidirectional_range<PatternBase> &&
ranges::common_range<PatternBase>;
```
| (4) | (since C++23) |
|
```
constexpr /*iterator*/ operator--( int )
requires std::is_reference_v<InnerBase> &&
ranges::bidirectional_range<Base> &&
ranges::bidirectional_range<InnerBase> &&
ranges::common_range<InnerBase> &&
ranges::bidirectional_range<PatternBase> &&
ranges::common_range<PatternBase>;
```
| (5) | (since C++23) |
Increments or decrements the iterator.
1) Increments the stored inner iterator. (The inner iterator may point to either `InnerBase` or `PatternBase`.) * If the incremented inner iterator reaches the end of the pattern range, it is destroyed, and an iterator to the beginning of the next inner range is constructed.
* If the incremented inner iterator reaches the end of the inner range, the outer iterator is incremented, and if the outer iterator is not the end iterator, the inner iterator is destroyed and an iterator to the beginning of the pattern range is constructed.
* The above steps may be repeated (e.g. if the pattern is empty), until either the inner range is not empty, or the outer iterator reaches the end.
2) Equivalent to `++*this;`
3) Equivalent to `auto tmp = *this; ++*this; return tmp;`
4) If the outer iterator is the end iterator, it is decremented. Then: * If the stored inner iterator refers to the beginning of the inner range, it is destroyed, and an iterator to the end of the pattern range is constructed.
* If the stored inner iterator refers to the beginning of the pattern range, it is destroyed, the outer iterator is decremented, and an iterator to end of the inner range is constructed.
* The above steps may be repeated (e.g. if the pattern is empty), until the inner range is not empty.
Finally, the inner iterator is decremented.
5) Equivalent to `auto tmp = *this; --*this; return tmp;`
If `InnerBase` is not a reference, the inner range is stored in the parent `join_with_view` for iteration. The inner range need not be movable.
If `InnerBase` is a reference, and the outer iterator reaches the end, the inner iterator points to the beginning of the pattern range.
### Parameters
(none).
### Return value
1,4) `*this`
3,5) a copy of `*this` that was made before the change
cpp iter_swap(ranges::join_with_view::iterator) iter\_swap(ranges::join\_with\_view::*iterator*)
================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr void iter_swap( const /*iterator*/& x, const /*iterator*/& y )
requires std::indirectly_swappable<ranges::iterator_t<InnerBase>,
ranges::iterator_t<PatternBase>>;
```
| | (since C++20) |
Applies `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)` to the stored inner iterators.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_with_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to the elements to swap |
### Return value
(none).
cpp operator==(ranges::join_with_view::iterator) operator==(ranges::join\_with\_view::*iterator*)
================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires std::is_reference_v<InnerBase> &&
std::equality_comparable<ranges::iterator_t<Base>> &&
std::equality_comparable<ranges::iterator_t<InnerBase>>;
```
| | (since C++23) |
Compares the underlying iterators. Two iterators are equal if their stored outer iterators and inner iterators are respectively equal.
The inner iterators may point into either `InnerBase` or `PatternBase`. They compare equal only if both point into `InnerBase` or both point into `PatternBase`, and in either case they have the same value.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::join_with_view::*iterator*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
result of comparison.
cpp std::ranges::transform_view<V,F>::size std::ranges::transform\_view<V,F>::size
=======================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::sized_range<V>;
```
| | (since C++20) |
|
```
constexpr auto size() const requires ranges::sized_range<const V>;
```
| | (since C++20) |
Returns the number of elements.
Returns `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base_)`, where `base_` is the underlying view.
### Parameters
(none).
### Return value
The number of elements.
### Notes
If `V` does not model [`forward_range`](../forward_range "cpp/ranges/forward range"), `size()` might not be well-defined after a call to `begin()`.
### Example
```
#include <iostream>
#include <ranges>
#include <string>
#include <cctype>
int main()
{
std::string s{"The length of this string is 42 characters"};
auto tv = std::ranges::transform_view{s, [](char c) -> char {
return std::toupper(c); }
};
for (auto x: tv) { std::cout << x; };
std::cout << "\nsize = " << tv.size() << '\n';
}
```
Output:
```
THE LENGTH OF THIS STRING IS 42 CHARACTERS
size = 42
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::transform_view
deduction guides for `std::ranges::transform_view`
==================================================
| | | |
| --- | --- | --- |
|
```
template< class R, class F >
transform_view( R&&, F ) -> transform_view<views::all_t<R>, F>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::ranges::transform\_view](../transform_view "cpp/ranges/transform view")` to allow deduction from [`range`](../range "cpp/ranges/range") and transformation function.
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `transform_view<R, F>`; otherwise, the deduced type is usually `transform_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>, F>`.
### Example
cpp std::ranges::transform_view<V,F>::sentinel
std::ranges::transform\_view<V,F>::*sentinel*
=============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/
```
| | (since C++20) |
The return type of [`transform_view::end`](end "cpp/ranges/transform view/end") when the underlying view is not a [`common_range`](../common_range "cpp/ranges/common range").
The type `/*sentinel*/<true>` is returned by the const-qualified overload. The type `/*sentinel*/<false>` is returned by the non-const-qualified overload.
The name of this class template (shown here as `/*sentinel*/`) is unspecified.
Typical implementation holds only one data member: a sentinel obtained from (possibly const-qualified) `V`.
### Member types
| Member type | Definition |
| --- | --- |
| `Parent` (private) | `const transform_view<V, F>` if `Const` is `true`, otherwise `transform_view<V, F>`. The name is for exposition only |
| `Base` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/transform view/sentinel/sentinel")
(C++20) | constructs a sentinel (public member function) |
| [base](sentinel/base "cpp/ranges/transform view/sentinel/base")
(C++20) | returns the underlying sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/transform view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`transform_view::begin`](begin "cpp/ranges/transform view/begin") (function) |
| [operator-](sentinel/operator- "cpp/ranges/transform view/sentinel/operator-")
(C++20) | computes the distance between a sentinel and an iterator returned from [`transform_view::begin`](begin "cpp/ranges/transform view/begin") (function) |
| programming_docs |
cpp std::ranges::transform_view<V,F>::base std::ranges::transform\_view<V,F>::base
=======================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::transform_view<V,F>::iterator
std::ranges::transform\_view<V,F>::*iterator*
=============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/
```
| | (since C++20) |
The return type of [`transform_view::begin`](begin "cpp/ranges/transform view/begin"), and of [`transform_view::end`](end "cpp/ranges/transform view/end") when the underlying view is a [`common_range`](../common_range "cpp/ranges/common range").
The type `/*iterator*/<true>` is returned by the const-qualified overloads. The type `/*iterator*/<false>` is returned by the non-const-qualified overloads.
The name of this class template (shown here as `*iterator*`) is unspecified.
Typical implementation holds two data members: an iterator into (possibly const-qualified) `V`, and a pointer to parent `transform_view`.
### Member types
| Member type | Definition |
| --- | --- |
| `*Parent*` (private) | `const [ranges::transform\_view](http://en.cppreference.com/w/cpp/ranges/transform_view)<V, F>` if `Const` is `true`, otherwise `[ranges::transform\_view](http://en.cppreference.com/w/cpp/ranges/transform_view)<V, F>`. The name is for exposition only. |
| `*Base*` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only. |
| `iterator_concept` | `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`random_access_range`](../random_access_range "cpp/ranges/random access range"), `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range"), `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `*Base*` models [`forward_range`](../forward_range "cpp/ranges/forward range"), `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise. |
| `iterator_category` | Not defined if `*Base*` does not model [`forward_range`](../forward_range "cpp/ranges/forward range").Otherwise, if `[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F&, [ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>` is not an lvalue reference, `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`. Else, let `C` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>>::iterator\_category`. If `C` is `[std::contiguous\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, the type is `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`; otherwise, the type is `C`. |
| `value_type` | `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F&, [ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>` |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/transform view/iterator/iterator")
(C++20) | constructs an iterator (public member function) |
| [base](iterator/base "cpp/ranges/transform view/iterator/base")
(C++20) | returns the underlying iterator (public member function) |
| [operator\*](iterator/operator* "cpp/ranges/transform view/iterator/operator*")
(C++20) | accesses the transformed element (public member function) |
| [operator[]](iterator/operator_at "cpp/ranges/transform view/iterator/operator at")
(C++20) | accesses an element by index (public member function) |
| [operator++operator++(int)operator--operator--(int)operator+=operator-=](iterator/operator_arith "cpp/ranges/transform view/iterator/operator arith")
(C++20) | advances or decrements the underlying iterator (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<operator>operator<=operator>=operator<=>](iterator/operator_cmp "cpp/ranges/transform view/iterator/operator cmp")
(C++20) | compares the underlying iterators (function) |
| [operator+operator-](iterator/operator_arith2 "cpp/ranges/transform view/iterator/operator arith2")
(C++20) | performs iterator arithmetic (function) |
| [iter\_move](iterator/iter_move "cpp/ranges/transform view/iterator/iter move")
(C++20) | obtains an rvalue reference to the transformed element (function) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2259R1](https://wg21.link/P2259R1) | C++20 | member `iterator_category` is always defined | defined only if `*Base*` models [`forward_range`](../forward_range "cpp/ranges/forward range") |
| [LWG 3555](https://cplusplus.github.io/LWG/issue3555) | C++20 | the definition of `iterator_concept` ignores const | made to consider |
cpp std::ranges::transform_view<V,F>::begin std::ranges::transform\_view<V,F>::begin
========================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/<false> begin();
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/<true> begin() const
requires ranges::range<const V> &&
std::regular_invocable<const F&, ranges::range_reference_t<const V>>;
```
| (2) | (since C++20) |
Returns an [iterator](iterator "cpp/ranges/transform view/iterator") to the first element of the `transform_view`.
1) Equivalent to `return /\*iterator\*/<false>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`, where `base_` is the underlying view.
2) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`, where `base_` is the underlying view. ### Parameters
(none).
### Return value
Iterator to the first element.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/transform view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::transform_view<V,F>::transform_view std::ranges::transform\_view<V,F>::transform\_view
==================================================
| | | |
| --- | --- | --- |
|
```
transform_view() requires std::default_initializable<V> &&
std::default_initializable<F> = default;
```
| (1) | (since C++20) |
|
```
constexpr transform_view( V base, F fun );
```
| (2) | (since C++20) |
Constructs a `transform_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and the transformation function.
2) Move constructs the underlying view from `base` and the transformation function from `fun`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | view |
| fun | - | transformation function |
### Example
Demonstrates π approximation using serial expansion of arc tangent of 1:
`atan(1) = π/4 ~ 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...`
```
#include <iomanip>
#include <iostream>
#include <numbers>
#include <ranges>
int main()
{
std::cout << std::setprecision(15) << std::fixed;
auto atan1term = std::ranges::views::transform(
[](int n) { return ((n % 2) ? -1 : 1) * 1.0 / (2 * n + 1); }
);
for (const int iterations : {1, 2, 3, 4, 5, 10, 100, 1000, 1'000'000}) {
double accum{0.0};
for (double term : std::ranges::views::iota(0, iterations) | atan1term) {
accum += term;
}
std::cout << "π ~ " << 4 * accum << " (iterations: " << iterations << ")\n";
}
std::cout << "π ~ " << std::numbers::pi << " (std::numbers::pi)\n";
}
```
Possible output:
```
π ~ 4.000000000000000 (iterations: 1)
π ~ 2.666666666666667 (iterations: 2)
π ~ 3.466666666666667 (iterations: 3)
π ~ 2.895238095238096 (iterations: 4)
π ~ 3.339682539682540 (iterations: 5)
π ~ 3.041839618929403 (iterations: 10)
π ~ 3.131592903558554 (iterations: 100)
π ~ 3.140592653839794 (iterations: 1000)
π ~ 3.141591653589774 (iterations: 1000000)
π ~ 3.141592653589793 (std::numbers::pi)
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | if `F` is not [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable"), the default constructorconstructs a `transform_view` which does not contain an `F` | the `transform_view` is alsonot [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") |
cpp std::ranges::transform_view<V,F>::end std::ranges::transform\_view<V,F>::end
======================================
| | | |
| --- | --- | --- |
|
```
constexpr /*sentinel*/<false> end();
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/<false> end() requires ranges::common_range<V>;
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/<true> end() const
requires ranges::range<const V> &&
std::regular_invocable<const F&, ranges::range_reference_t<const V>>;
```
| (3) | (since C++20) |
|
```
constexpr /*iterator*/<true> end() const
requires ranges::common_range<const V> &&
std::regular_invocable<const F&, ranges::range_reference_t<const V>>;
```
| (4) | (since C++20) |
Returns a [sentinel](sentinel "cpp/ranges/transform view/sentinel") or an [iterator](iterator "cpp/ranges/transform view/iterator") representing the end of the `transform_view`.
Let `base_` be the underlying view:
1) Equivalent to `return /\*sentinel\*/<false>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
2) Equivalent to `return /\*iterator\*/<false>{\*this, [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
3) Equivalent to `return /\*sentinel\*/<true>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`.
4) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)};`. ### Parameters
(none).
### Return value
1,3) sentinel which compares equal to the end iterator
2,4) iterator to the element following the last element ### Notes
`end()` returns an iterator if and only if the underlying view is a [`common_range`](../common_range "cpp/ranges/common range"): `transform_view<V,F>` models [`common_range`](../common_range "cpp/ranges/common range") whenever `V` does.
### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/transform view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::transform_view<V,F>::sentinel<Const>::sentinel
std::ranges::transform\_view<V,F>::*sentinel*<Const>::*sentinel*
================================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( ranges::sentinel_t<Base> end );
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const &&
std::convertible_to<ranges::sentinel_t<V>, ranges::sentinel_t<Base>>;
```
| (3) | (since C++20) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel.
2) Initializes the underlying sentinel with `end`.
3) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs corresponding members. ### Parameters
| | | |
| --- | --- | --- |
| end | - | a sentinel representing the end of (possibly const-qualified) `V` |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp operator-(ranges::transform_view::sentinel) operator-(ranges::transform\_view::*sentinel*)
==============================================
| | | |
| --- | --- | --- |
|
```
friend constexpr ranges::range_difference_t<Base>
operator-( const /*iterator*/<Const>& x, const /*sentinel*/& y )
requires std::sized_sentinel_for<ranges::sentinel_t<Base>, ranges::iterator_t<Base>>;
```
| (1) | (since C++20) |
|
```
friend constexpr ranges::range_difference_t<Base>
operator-( const /*sentinel*/& y, const /*iterator*/<Const>& x )
requires std::sized_sentinel_for<ranges::sentinel_t<Base>, ranges::iterator_t<Base>>;
```
| (2) | (since C++20) |
Computes the distance between the underlying iterator of `x` and the underlying sentinel of `y`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `transform_view::*sentinel*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x | - | an [iterator](../iterator "cpp/ranges/transform view/iterator") |
| y | - | a sentinel |
### Return value
Let `current_` denote the underlying iterator, `end_` denote the underlying sentinel.
1) `x.current_ - y.end_`
2) `y.end_ - x.current_`
cpp std::ranges::transform_view<V,F>::sentinel<Const>::base std::ranges::transform\_view<V,F>::*sentinel*<Const>::base
==========================================================
| | | |
| --- | --- | --- |
|
```
constexpr ranges::sentinel_t<Base> base() const;
```
| | (since C++20) |
Returns the underlying sentinel.
### Parameters
(none).
### Return value
a copy of the underlying sentinel.
### Example
cpp operator==(ranges::transform_view::sentinel) operator==(ranges::transform\_view::*sentinel*)
===============================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/<Const>& x, const /*sentinel*/& y );
```
| | (since C++20) |
Compares the underlying iterator of `x` with the underlying sentinel of `y`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `transform_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../iterator "cpp/ranges/transform view/iterator") to compare |
| y | - | sentinel to compare |
### Return value
`x.current_ == y.end_`, where `current_` denotes the underlying iterator, `end_` denotes the underlying sentinel.
### Example
cpp std::ranges::transform_view<V,F>::iterator<Const>::base std::ranges::transform\_view<V,F>::*iterator*<Const>::base
==========================================================
| | | |
| --- | --- | --- |
|
```
constexpr const ranges::iterator_t<Base>& base() const & noexcept;
```
| (1) | (since C++20) |
|
```
constexpr ranges::iterator_t<Base> base() &&;
```
| (2) | (since C++20) |
Returns the underlying iterator.
1) Returns a reference to the underlying iterator.
2) Move constructs the result from the underlying iterator. ### Parameters
(none).
### Return value
1) A reference to the underlying iterator.
2) An iterator move constructed from the underlying iterator. ### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ranges>
int main()
{
const auto v = { 0, 1, 2, 3, 4 };
auto x2 = [](int x) { return x << 1; };
std::ranges::transform_view tv{ v, x2 };
std::ostream_iterator<int> ostr{ std::cout, " " };
std::ranges::copy(v, ostr), std::cout << '\n';
std::ranges::copy(tv.base(), ostr), std::cout << '\n';
std::ranges::copy(tv, ostr), std::cout << '\n';
}
```
Output:
```
0 1 2 3 4
0 1 2 3 4
0 2 4 6 8
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3533](https://cplusplus.github.io/LWG/issue3533) | C++20 | the `const&` overload of `base` returns a copy of the underlying iterator | returns a reference |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the `const&` overload of `base` might not be noexcept | made noexcept |
cpp iter_move(ranges::transform_view::iterator) iter\_move(ranges::transform\_view::*iterator*)
===============================================
| | | |
| --- | --- | --- |
|
```
friend constexpr decltype(auto) iter_move( const /*iterator*/& i )
noexcept(/* see below */);
```
| | (since C++20) |
If `*i` is an lvalue reference, returns `std::move(*i)`; otherwise returns `*i`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `transform_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator |
### Return value
`std::move(*i)` if `*i` is an lvalue reference, otherwise `*i`.
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(\*i.parent\_->fun_, \*i.current\_)))`
where `*i.parent_->fun_` denotes the transformation function, `i.current_` denotes the underlying iterator.
cpp std::ranges::transform_view<V,F>::iterator<Const>::operator[] std::ranges::transform\_view<V,F>::*iterator*<Const>::operator[]
================================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator[]( difference_type n ) const
requires ranges::random_access_range<Base>;
```
| | (since C++20) |
Returns the element at specified relative location, after transformation.
Effectively returns `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(\*parent_->fun_, current_[n])`, where `*parent_->fun_` is the transformation function stored in the parent `transform_view`, and `current_` is the underlying iterator into `V`.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location. |
### Return value
the transformed element.
### Example
| programming_docs |
cpp std::ranges::transform_view<V,F>::iterator<Const>::operator* std::ranges::transform\_view<V,F>::*iterator*<Const>::operator\*
================================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*() const;
```
| | (since C++20) |
Returns the transformed element.
Effectively returns `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(\*parent_->fun_, \*current_)`, where `*parent_->fun_` is the transformation function stored in the parent `transform_view`, and `current_` is the underlying iterator into `V`.
### Parameters
(none).
### Return value
The transformed element.
### Notes
`operator->` is not provided.
The behavior is undefined if the pointer to parent `transform_view` is null (e.g. if `*this` is default constructed).
If `*current_` is a prvalue, its lifetime ends before this function returns. If the transformation function returns a reference or pointer to it, the result would dangle.
### Example
cpp std::ranges::transform_view<V,F>::iterator<Const>::iterator
std::ranges::transform\_view<V,F>::*iterator*<Const>::*iterator*
================================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/() requires std::default_initializable<ranges::iterator_t<Base>> = default;
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/( Parent& parent, ranges::iterator_t<Base> current );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i )
requires Const &&
std::convertible_to<ranges::iterator_t<V>, ranges::iterator_t<Base>>;
```
| (3) | (since C++20) |
Construct an iterator.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying iterator, and initializes the pointer to parent `transform_view` with `nullptr`.
2) Initializes the underlying iterator with `std::move(current)`, and the pointer to parent with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)`.
3) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Move constructs corresponding members. ### Parameters
| | | |
| --- | --- | --- |
| parent | - | a (possibly const-qualified) `[std::ranges::transform\_view](../../transform_view "cpp/ranges/transform view")` |
| current | - | an iterator into (possibly const-qualified) `V` |
| i | - | an `/*iterator*/<false>` |
### Example
cpp std::ranges::transform_view<V,F>::iterator<Const>::operator++,--,+=,-= std::ranges::transform\_view<V,F>::*iterator*<Const>::operator++,--,+=,-=
=========================================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/ operator++( int )
requires ranges::forward_range<Base>;
```
| (3) | (since C++20) |
|
```
constexpr /*iterator*/& operator--()
requires ranges::bidirectional_range<Base>;
```
| (4) | (since C++20) |
|
```
constexpr /*iterator*/ operator--( int )
requires ranges::bidirectional_range<Base>;
```
| (5) | (since C++20) |
|
```
constexpr /*iterator*/& operator+=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (6) | (since C++20) |
|
```
constexpr /*iterator*/& operator-=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (7) | (since C++20) |
Increments or decrements the iterator.
Let `current_` be the underlying iterator.
1) Equivalent to `++current_; return *this;`
2) Equivalent to `++current_;`
3) Equivalent to `auto tmp = *this; ++*this; return tmp;`
4) Equivalent to `--current_; return *this;`
5) Equivalent to `auto tmp = *this; --*this; return tmp;`
6) Equivalent to `current_ += n; return *this;`
7) Equivalent to `current_ -= n; return *this;`
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
1,4,6,7) `*this`
3,5) a copy of `*this` that was made before the change
cpp operator==,<,>,<=,>=,<=>(ranges::transform_view::iterator) operator==,<,>,<=,>=,<=>(ranges::transform\_view::*iterator*)
=============================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires std::equality_comparable<ranges::iterator_t<Base>>;
```
| (1) | (since C++20) |
|
```
friend constexpr bool operator<( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (2) | (since C++20) |
|
```
friend constexpr bool operator>( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (3) | (since C++20) |
|
```
friend constexpr bool operator<=( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (4) | (since C++20) |
|
```
friend constexpr bool operator>=( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base>;
```
| (5) | (since C++20) |
|
```
friend constexpr auto operator<=>( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base> &&
std::three_way_comparable<ranges::iterator_t<Base>>;
```
| (6) | (since C++20) |
Compares the underlying iterators.
1) Equivalent to `return x.current_ == y.current_;`, where `current_` is the underlying iterator.
2) Equivalent to `return x.current_ < y.current_;`, where `current_` is the underlying iterator.
3) Equivalent to `return y < x;`
4) Equivalent to `return !(y < x);`
5) Equivalent to `return !(x < y);`
6) Equivalent to `return x.current_ <=> y.current_;`, where `current_` is the underlying iterator. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::transform_view::*iterator*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
result of comparison.
cpp std::ranges::take_view<V>::size std::ranges::take\_view<V>::size
================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::sized_range<V>;
```
| (1) | (since C++20) |
|
```
constexpr auto size() const requires ranges::sized_range<const V>;
```
| (2) | (since C++20) |
Returns the number of elements, which is the smaller of the count passed to the constructor and the size of the underlying view.
Let `base_` be the underlying view, `count_` be the number passed to the constructor (`0` if default constructed). Equivalent to.
```
auto n = ranges::size(base_);
return ranges::min(n, static_cast<decltype(n)>(count_));
```
### Parameters
(none).
### Return value
The number of elements.
### Example
```
#include <ranges>
#include <iostream>
int main()
{
constexpr int arr[] {1, 2, 3};
for (int i = 0; i != 6; ++i) {
const auto tv = std::ranges::take_view{arr, i};
std::cout << tv.size() << ' ';
}
}
```
Output:
```
0 1 2 3 3 3
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::take_view
deduction guides for `std::ranges::take_view`
=============================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class R >
take_view( R&&, ranges::range_difference_t<R> ) -> take_view<views::all_t<R>>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::ranges::take\_view](../take_view "cpp/ranges/take view")` to allow deduction from [`range`](../range "cpp/ranges/range") and number of elements.
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `[ranges::take\_view](http://en.cppreference.com/w/cpp/ranges/take_view)<R>`; otherwise, the deduced type is usually `[ranges::take\_view](http://en.cppreference.com/w/cpp/ranges/take_view)<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
### Defect Reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3447](https://cplusplus.github.io/LWG/issue3447) | C++20 | the template parameter `R` is constrained with [`range`](../range "cpp/ranges/range") | `R` is unconstrained(but [`range_difference_t`](../iterator_t "cpp/ranges/iterator t") requires [`range`](../range "cpp/ranges/range")) |
cpp std::ranges::take_view<V>::sentinel
std::ranges::take\_view<V>::*sentinel*
======================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/
```
| | (since C++20) |
The return type of [`take_view::end`](end "cpp/ranges/take view/end") when the underlying view is not a [`sized_range`](../sized_range "cpp/ranges/sized range").
The type `/*sentinel*/<true>` is returned by the const-qualified overload. The type `/*sentinel*/<false>` is returned by the non-const-qualified overload.
The name of this class template (shown here as `/*sentinel*/`) is unspecified.
Typical implementation holds only one data member: a sentinel obtained from (possibly const-qualified) `V`.
### Member types
| Member type | Definition |
| --- | --- |
| `*Base*`(private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/take view/sentinel/sentinel")
(C++20) | constructs a sentinel (public member function) |
| [base](sentinel/base "cpp/ranges/take view/sentinel/base")
(C++20) | returns the underlying sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/take view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`take_view::begin`](begin "cpp/ranges/take view/begin") (function) |
cpp std::ranges::take_view<V>::base std::ranges::take\_view<V>::base
================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::take_view<V>::take_view std::ranges::take\_view<V>::take\_view
======================================
| | | |
| --- | --- | --- |
|
```
take_view() requires std::default_initializable<V> = default;
```
| (1) | (since C++20) |
|
```
constexpr take_view( V base, ranges::range_difference_t<V> count );
```
| (2) | (since C++20) |
Constructs a `take_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and initializes the count to 0. After construction, [`base()`](base "cpp/ranges/take view/base") returns a copy of `V()` and [`size()`](size "cpp/ranges/take view/size") returns `0`.
2) Initializes the underlying view with `std::move(base)` and the count with `count`. After construction, [`base()`](base "cpp/ranges/take view/base") returns a copy of `base` and [`size()`](size "cpp/ranges/take view/size") returns the smaller of `count` and `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base)`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | the underlying view |
| count | - | number of elements to take |
### Example
Prints first `n` prime numbers that are generated using [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes "enwiki:Sieve of Eratosthenes") method.
```
#include <bit>
#include <bitset>
#include <iomanip>
#include <iostream>
#include <limits>
#include <ranges>
constexpr unsigned clog2(auto x) // ~ ⌈ log₂(x) ⌉
{
return std::numeric_limits<decltype(x)>::digits - std::countl_zero(x);
}
template <unsigned Primes> struct Sieve
{
bool operator()(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0 || bits.test(n / 2))
return false;
for (int i{n}, j{3}, k{}; (k = i * j) < size; j += 2)
bits.set(k / 2);
return true;
}
static constexpr int prime_numbers = Primes;
// a(n) ~= n*(log(n) + log(log(n)));
static constexpr int size = Primes*(clog2(Primes) + clog2(clog2(Primes)));
// Keep only odd numbers; 0 means it is a prime
private: std::bitset<size / 2 + 1> bits;
};
int main()
{
Sieve<100> sieve{};
auto primes_gen = std::views::iota(1)
| std::views::filter(sieve);
auto primes = std::ranges::take_view{ primes_gen, sieve.prime_numbers };
for (int n{1}; auto prime : primes) {
std::cout << prime << (n++ % 10 ? ' ' : '\n');
}
std::cout
<< "\n" "sieve.prime_numbers: " << sieve.prime_numbers
<< "\n" "sieve.size: " << sieve.size
<< "\n" "sizeof(sieve): " << sizeof sieve << " bytes\n";
}
```
Output:
```
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
sieve.prime_numbers: 100
sieve.size: 1000
sizeof(sieve): 64 bytes
```
cpp std::ranges::take_view<V>::begin std::ranges::take\_view<V>::begin
=================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const requires ranges::range<const V>;
```
| (2) | (since C++20) |
Returns an iterator to the first element of the `take_view`.
1) Returns a `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)` or a `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>`.
2) Returns a `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)` or a `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const V>`. Overload (1) does not participate in overload resolution if `V` is a [simple view](../../ranges#Helper_concepts "cpp/ranges") (that is, if `V` and `const V` are views with the same iterator and sentinel types).
### Parameters
(none).
### Return value
The result depends on the concepts satisfied by possible const-qualified underlying view type `*Base\_*`, which is `V` (for overload (1)) or `const V` (for overload (2)).
Let `*base\_*` be the underlying view, `*count\_*` be the number passed to the constructor (`0` if default initialized).
| The underlying view satisfies ... | [`random_access_range`](../random_access_range "cpp/ranges/random access range") |
| --- | --- |
| yes | no |
| [`sized_range`](../sized_range "cpp/ranges/sized range") | yes | `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)` | `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_), [ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base\_>(this->size())).` |
| no | `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_), count_)` |
### Example
```
#include <ranges>
#include <iostream>
#include <string_view>
using namespace std::literals;
int main()
{
static constexpr auto sv = {"∀x"sv, "∃y"sv, "ε"sv, "δ"sv};
std::cout << *std::ranges::take_view(sv, 8).begin() << '\n';
}
```
Output:
```
∀x
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2393R1](https://wg21.link/P2393R1) | C++20 | implicit conversions between signed and unsigned integer-class types might fail | made explicit |
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/take view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [counted\_iterator](../../iterator/counted_iterator "cpp/iterator/counted iterator")
(C++20) | iterator adaptor that tracks the distance to the end of the range (class template) |
| [operator==](sentinel/operator_cmp "cpp/ranges/take view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from **`take_view::begin`** (function) |
cpp std::ranges::take_view<V>::end std::ranges::take\_view<V>::end
===============================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto end() const requires ranges::range<const V>;
```
| (2) | (since C++20) |
Returns a sentinel or an iterator representing the end of the `take_view`. The end of the `take_view` is either one past the `count`-th element in the underlying range, or the end of the underlying range if the latter has less than `count` elements.
1) Returns a `take_view::/*sentinel*/<false>`, a `[std::default\_sentinel\_t](http://en.cppreference.com/w/cpp/iterator/default_sentinel_t)`, or a `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>`.
2) Returns a `take_view::/*sentinel*/<true>`, a `[std::default\_sentinel\_t](http://en.cppreference.com/w/cpp/iterator/default_sentinel_t)`, or a `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const V>`. Overload (1) does not participate in overload resolution if `V` is a [simple view](../../ranges#Helper_concepts "cpp/ranges") (that is, if `V` and `const V` are views with the same iterator and sentinel types).
### Parameters
(none).
### Return value
The result depends on the concepts satisfied by possible const-qualified underlying view type `*Base\_*`, that is `V` (for overload (1)) or `const V` (for overload (2)).
Let `base_` be the underlying view.
| The underlying view satisfies ... | [`random_access_range`](../random_access_range "cpp/ranges/random access range") |
| --- | --- |
| yes | no |
| [`sized_range`](../sized_range "cpp/ranges/sized range") | yes | `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_) + [ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base\_>(this->size()).` | `[std::default\_sentinel](http://en.cppreference.com/w/cpp/iterator/default_sentinel)` |
| no | 1) `/\*sentinel\*/<false>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)}` 2) `/\*sentinel\*/<true>{[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)}` |
### Example
```
#include <list>
#include <ranges>
#include <iterator>
#include <iostream>
#include <type_traits>
int main() {
const auto list1 = { 3, 1, 4, 1, 5 };
const auto seq1 = list1 | std::views::take(4);
static_assert(std::ranges::sized_range<decltype(seq1)> and
std::ranges::random_access_range<decltype(seq1)> and
std::is_same_v<decltype(seq1.end()), decltype(list1.end())>);
for (auto it = seq1.begin(); it != seq1.end(); std::cout << *it++ << ' '){ }
std::cout << '\n';
std::list list2 = { 2, 7, 1, 8, 2 };
const auto seq2 = list2 | std::views::take(4);
static_assert(std::ranges::sized_range<decltype(seq2)> and
not std::ranges::random_access_range<decltype(seq2)> and
std::is_same_v<decltype(seq2.end()), std::default_sentinel_t>);
for (auto it = seq2.begin(); it != std::default_sentinel; std::cout << *it++ << ' '){ }
std::cout << '\n';
}
```
Output:
```
3 1 4 1
2 7 1 8
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2393R1](https://wg21.link/P2393R1) | C++20 | implicit conversions between signed and unsigned integer-class types might fail | made explicit |
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/take view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [counted\_iterator](../../iterator/counted_iterator "cpp/iterator/counted iterator")
(C++20) | iterator adaptor that tracks the distance to the end of the range (class template) |
| [operator==](sentinel/operator_cmp "cpp/ranges/take view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`take_view::begin`](begin "cpp/ranges/take view/begin") (function) |
| programming_docs |
cpp std::ranges::take_view<V>::sentinel<Const>::sentinel
std::ranges::take\_view<V>::*sentinel*<Const>::*sentinel*
=========================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( ranges::sentinel_t<Base> end );
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> s )
requires Const &&
std::convertible_to<ranges::sentinel_t<V>, ranges::sentinel_t<Base>>;
```
| (3) | (since C++20) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel.
2) Initializes the underlying sentinel with `end`.
3) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs corresponding members. ### Parameters
| | | |
| --- | --- | --- |
| end | - | a sentinel representing the end of (possibly const-qualified) `V` |
| s | - | a `/*sentinel*/<false>` |
### Example
cpp std::ranges::take_view<V>::sentinel<Const>::base std::ranges::take\_view<V>::*sentinel*<Const>::base
===================================================
| | | |
| --- | --- | --- |
|
```
constexpr ranges::sentinel_t<Base> base() const;
```
| | (since C++20) |
Returns the underlying sentinel.
### Parameters
(none).
### Return value
a copy of the underlying sentinel.
### Example
cpp operator==(std::ranges::take_view::sentinel<Const>)
operator==(std::ranges::take\_view::*sentinel*<Const>)
======================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool
operator==( const std::counted_iterator<ranges::iterator_t<Base>>& y,
const /*sentinel*/& x );
```
| (1) | (since C++20) |
|
```
template< bool OtherC = !Const >
requires std::sentinel_for<ranges::sentinel_t<Base>,
ranges::iterator_t</*add-const-if*/<OtherC, V>>>
friend constexpr bool operator==( const std::counted_iterator<ranges::iterator_t<
/*add-const-if*/<OtherC, V>>>& y,
const /*sentinel*/& x );
```
| (2) | (since C++20) |
Compares a `take_view::/*sentinel*/` with a `[std::counted\_iterator](../../../iterator/counted_iterator "cpp/iterator/counted iterator")` (typically obtained from a call to [`take_view::begin`](../begin "cpp/ranges/take view/begin")).
Returns `true` if `y` points past the N-th element (where N is the number passed to the [constructor of `take_view`](../take_view "cpp/ranges/take view/take view")), or if end of underlying view is reached.
The exposition-only alias template `*add-const-if*` is defined as `template<bool C, class T> using /\*add-const-if\*/ = [std::conditional\_t](http://en.cppreference.com/w/cpp/types/conditional)<C, const T, T>;`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::take_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| y | - | `[std::counted\_iterator](../../../iterator/counted_iterator "cpp/iterator/counted iterator")` to compare |
| x | - | sentinel to compare |
### Return value
`y.count() == 0 || y.base() == x.end_`, where `*end\_*` denotes the underlying sentinel.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3449](https://cplusplus.github.io/LWG/issue3449) | C++20 | comparison between the iterator and the sentinel ofdifferently const-qualified `take_view` was unsupported | made supported when possible |
cpp std::ranges::drop_view<V>::size std::ranges::drop\_view<V>::size
================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::sized_range<V>;
```
| (1) | (since C++20) |
|
```
constexpr auto size() const requires ranges::sized_range<const V>;
```
| (2) | (since C++20) |
Returns the number of elements.
Let `*base\_*` be the underlying view, `*count\_*` be the stored count (usually the number passed to the constructor, or `0` if `*this` is default constructed). Equivalent to.
```
const auto s = ranges::size(base_);
const auto c = static_cast<decltype(s)>(count_);
return s < c ? 0 : s - c;
```
### Parameters
(none).
### Return value
The number of elements.
### Example
```
#include <array>
#include <ranges>
int main()
{
constexpr std::array a{42, 43, 44};
static_assert(std::ranges::drop_view{std::views::all(a), 0}.size() == 3);
static_assert(std::ranges::drop_view{std::views::all(a), 1}.size() == 2);
static_assert(std::ranges::drop_view{std::views::all(a), 2}.size() == 1);
static_assert(std::ranges::drop_view{std::views::all(a), 3}.size() == 0);
static_assert(std::ranges::drop_view{std::views::all(a), 4}.size() == 0);
}
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::drop_view
deduction guides for `std::ranges::drop_view`
=============================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class R >
drop_view( R&&, ranges::range_difference_t<R> ) -> drop_view<views::all_t<R>>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::ranges::drop\_view](../drop_view "cpp/ranges/drop view")` to allow deduction from [`range`](../range "cpp/ranges/range") and number of elements.
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `drop_view<R>`; otherwise, the deduced type is usually `drop_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
cpp std::ranges::drop_view<V>::base std::ranges::drop\_view<V>::base
================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::drop_view<V>::drop_view std::ranges::drop\_view<V>::drop\_view
======================================
| | | |
| --- | --- | --- |
|
```
drop_view() requires std::default_initializable<V> = default;
```
| (1) | (since C++20) |
|
```
constexpr drop_view( V base, ranges::range_difference_t<V> count );
```
| (2) | (since C++20) |
Constructs a `drop_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and initializes the count to `0`. After construction, [`base()`](base "cpp/ranges/drop view/base") returns a copy of `V()` and [`size()`](size "cpp/ranges/drop view/size") equals to the size of the underlying view.
2) Initializes the underlying view with `std::move(base)` and the count with `count`. After construction, [`base()`](base "cpp/ranges/drop view/base") returns a copy of `base` and [`size()`](size "cpp/ranges/drop view/size") returns `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(base) - count` if the size of `base` is not less than `count`, or `0` otherwise. ### Parameters
| | | |
| --- | --- | --- |
| base | - | the underlying view |
| count | - | number of elements to skip. |
### Example
```
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <ranges>
int main()
{
constexpr std::array hi{ 'H','e','l','l','o',',',' ','C','+','+','2','0' };
std::ranges::for_each(hi, [](const char c){ std::cout << c; });
std::cout << '\n';
constexpr auto n = std::distance(hi.cbegin(), std::ranges::find(hi, 'C'));
auto cxx = std::ranges::drop_view{ hi, n };
std::ranges::for_each(cxx, [](const char c){ std::cout << c; });
std::cout << '\n';
}
```
Output:
```
Hello, C++20
C++20
```
cpp std::ranges::drop_view<V>::begin std::ranges::drop\_view<V>::begin
=================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin()
requires (!(__SimpleView<V> &&
ranges::random_access_range<const V> && ranges::sized_range<const V>));
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const
requires ranges::random_access_range<const V> && ranges::sized_range<const V>;
```
| (2) | (since C++20) |
Returns an iterator to the first element of the `drop_view`, that is, an iterator to the *N*-th element of the underlying view, or to the end of the underlying view if it has less than *N* elements.
If `V` is not a [`random_access_range`](../random_access_range "cpp/ranges/random access range") or a [`sized_range`](../sized_range "cpp/ranges/sized range"), in order to provide the amortized constant time complexity required by the [`range`](../range "cpp/ranges/range") concept, the overload (1) caches the result within the `drop_view` object for use on subsequent calls.
### Parameters
(none).
### Return value
`[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_), count_, [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_))`, where `base_` is the underlying view, and `count_` is the number of elements to skip.
### Example
```
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <ranges>
int main()
{
std::array hi{ 'H','e','l','l','o',',',' ','C','+','+','2','0','!' };
std::ranges::for_each(hi, [](const char c){ std::cout << c; });
std::cout << '\n';
const auto c = std::distance(hi.begin(), std::ranges::find(hi, 'C'));
auto cxx = std::ranges::drop_view{ hi, c };
std::cout << "*drop_view::begin() == '" << *cxx.begin() << "'\n";
// *cxx.begin() = 'c'; // undefined: 'views' are to be used as observers
for (char c : cxx) { std::cout << c; }
std::cout << '\n';
}
```
Output:
```
Hello, C++20!
*drop_view::begin() == 'C'
C++20!
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3482](https://cplusplus.github.io/LWG/issue3482) | C++20 | the const overload can be called with unsized ranges | the const overload requires `sized_range` |
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/drop view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::drop_view<V>::end std::ranges::drop\_view<V>::end
===============================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto end() const requires ranges::range<const V>;
```
| (2) | (since C++20) |
Returns a sentinel or an iterator representing the end of the `drop_view`.
Effectively returns `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_)`, where `base_` is the underlying view.
### Parameters
(none).
### Return value
a sentinel or an iterator representing the end of the view.
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ranges>
int main()
{
constexpr char url[]{ "https://cppreference.com" };
const auto p = std::distance(std::ranges::begin(url), std::ranges::find(url, '/'));
auto site = std::ranges::drop_view{ url, p + 2 }; // drop the prefix "https://"
for (auto it = site.begin(); it != site.end(); ++it) {
std::cout << *it; // ^^^
}
std::cout << '\n';
}
```
Output:
```
cppreference.com
```
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/drop view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp deduction guides for std::ranges::split_view
deduction guides for `std::ranges::split_view`
==============================================
| | | |
| --- | --- | --- |
|
```
template< class R, class P >
split_view( R&&, P&& )
-> split_view<ranges::all_t<R>, ranges::all_t<P>>;
```
| (1) | (since C++20) |
|
```
template< ranges::input_range R >
split_view( R&&, ranges::range_value_t<R> )
-> split_view<ranges::all_t<R>, ranges::single_view<ranges::range_value_t<R>>>;
```
| (2) | (since C++20) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `split_view` to allow deduction from a range and a delimiter.
1) The delimiter is a range of elements.
2) The delimiter is a single element. ### Example
```
#include <ranges>
#include <string_view>
#include <type_traits>
using std::operator""sv;
int main() {
std::ranges::split_view w1{"a::b::c"sv, "::"sv};
static_assert(std::is_same_v<
decltype(w1),
std::ranges::split_view<std::string_view, std::string_view>>);
std::ranges::split_view w2{"x,y,z"sv, ','};
static_assert(std::is_same_v<
decltype(w2),
std::ranges::split_view<std::string_view, std::ranges::single_view<char>>>);
}
```
cpp std::ranges::split_view<V,Pattern>::sentinel
std::ranges::split\_view<V,Pattern>::*sentinel*
===============================================
| | | |
| --- | --- | --- |
|
```
class /*sentinel*/; // exposition only
```
| | (since C++20) |
The return type of [`split_view::end`](../split_view "cpp/ranges/split view") when the underlying [`view`](../view "cpp/ranges/view") type (`V`) does not models [`common_range`](../common_range "cpp/ranges/common range").
The name `*sentinel*` is for exposition purposes only.
### Data members
Typical implementations of `*sentinel*` hold only one non-static data member: an object of type `[ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>` that is the sentinel of the underlying [`view`](../view "cpp/ranges/view") (shown here as `*end\_*` for exposition only).
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs a sentinel (public member function) |
std::ranges::split\_view::*sentinel*::*sentinel*
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( ranges::split_view& parent );
```
| (2) | (since C++20) |
1) Value-initializes `*end\_*` via its default member initializer (`= [ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>()`).
2) Initializes `*end\_*` with `ranges::end(parent.base_)`.
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the underlying iterator and the underlying sentinel (function) |
operator==(std::ranges::split\_view::*iterator*, std::ranges::split\_view::*sentinel*)
---------------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x,
const /*sentinel*/& y );
```
| | (since C++20) |
Equivalent to `return x.cur_ == y.end_ && !x.trailing_empty_;`.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*sentinel*` is an associated class of the arguments.
cpp std::ranges::split_view<V,Pattern>::split_view std::ranges::split\_view<V,Pattern>::split\_view
================================================
| | | |
| --- | --- | --- |
|
```
split_view()
requires std::default_initializable<V> &&
std::default_initializable<Pattern> = default;
```
| (1) | (since C++20) |
|
```
constexpr split_view( V base, Pattern pattern );
```
| (2) | (since C++20) |
|
```
template< ranges::forward_range R >
requires std::constructible_from<V, views::all_t<R>> &&
std::constructible_from<Pattern,
ranges::single_view<ranges::range_value_t<R>>>
constexpr split_view( R&& r, ranges::range_value_t<R> e );
```
| (3) | (since C++20) |
Constructs a `split_view`.
Let `base_` be the underlying view and `pattern_` be the delimiter.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the `base_` and the `pattern_` with their default member initializers respectively.
2) Initializes the `base_` with `std::move(base)` and the `pattern_` with `std::move(pattern)`.
3) Initializes the `base_` with `[views::all](http://en.cppreference.com/w/cpp/ranges/all_view)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<R>(r))` and the `pattern_` with `[ranges::single\_view](http://en.cppreference.com/w/cpp/ranges/single_view){std::move(e)}`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | the view (to be split) |
| pattern | - | view to be used as the delimiter |
| e | - | element to be used as the delimiter |
### Example
A link to check the code: [wandbox](https://wandbox.org/permlink/THTOcFa0bQuZDCbf).
```
#include <string_view>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <ranges>
#include <vector>
#include <array>
int main()
{
{
auto view = std::views::iota(1, 20)
| std::views::transform([](int x) { return x % 5; });
auto splitts = std::views::split(view, 0); // (2)
for (const auto& split : splitts) {
std::cout << "{ ";
std::ranges::copy(split, std::ostream_iterator<int>(std::cout, " "));
std::cout << "} ";
}
}
std::cout << '\n';
{
const std::vector nums{ 1, -1, -1, 2, 3, -1, -1, 4, 5, 6 };
const std::array delim{ -1, -1 };
auto splitter = std::views::split(nums, delim); // (3)
for (const auto& split : splitter) {
std::cout << "{ ";
std::ranges::copy(split, std::ostream_iterator<int>(std::cout, " "));
std::cout << "} ";
}
}
std::cout << '\n';
{
constexpr std::string_view JupiterMoons{"Callisto, Europa, Ganymede, Io, and 75 more"};
constexpr std::string_view delim{", "};
std::ranges::split_view moons_extractor{ JupiterMoons, delim }; // (3)
for (const std::string_view moon : moons_extractor) {
std::cout << std::quoted(moon) << ' ';
}
}
}
```
Output:
```
{ 1 2 3 4 } { 1 2 3 4 } { 1 2 3 4 } { 1 2 3 4 }
{ 1 } { 2 3 } { 4 5 6 }
"Callisto" "Europa" "Ganymede" "Io" "and 75 more"
```
### See also
| | |
| --- | --- |
| [(constructor)](../lazy_split_view/lazy_split_view "cpp/ranges/lazy split view/lazy split view")
(C++20) | constructs a `lazy_split_view` (public member function of `std::ranges::lazy_split_view<V,Pattern>`) |
| programming_docs |
cpp std::ranges::split_view<V,Pattern>::base std::ranges::split\_view<V,Pattern>::base
=========================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view `*base\_*`.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
1) A copy of the underlying view.
2) A view move-constructed from the underlying view. ### Example
A link to check the code: [wandbox](https://wandbox.org/permlink/N6JPR5rAU6tmAYwE).
```
#include <iostream>
#include <iomanip>
#include <ranges>
#include <string_view>
int main()
{
constexpr std::string_view keywords{ "this throw true try typedef typeid" };
std::ranges::split_view split_view{ keywords, ' ' };
std::cout << "base() = " << std::quoted( split_view.base() ) << "\n"
"substrings: ";
for (std::string_view split: split_view)
std::cout << quoted(split) << ' ';
}
```
Output:
```
base() = "this throw true try typedef typeid"
substrings: "this" "throw" "true" "try" "typedef" "typeid"
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3590](https://cplusplus.github.io/LWG/issue3590) | C++20 | the `const&` overload additionally required validity of copy-assignment | constraints relaxed |
### See also
| | |
| --- | --- |
| [base](../lazy_split_view/base "cpp/ranges/lazy split view/base")
(C++20) | returns a copy of the underlying (adapted) view (public member function of `std::ranges::lazy_split_view<V,Pattern>`) |
cpp std::ranges::split_view<V,Pattern>::find_next std::ranges::split\_view<V,Pattern>::find\_next
===============================================
| | | |
| --- | --- | --- |
|
```
constexpr ranges::subrange<ranges::iterator_t<V>>
find_next( ranges::iterator_t<V> it ); // exposition only
```
| | (since C++20) |
Searches for the next occurrence of pattern in the underlying view. This function is for exposition only and its name is not normative.
Equivalent to:
```
auto [b, e] = ranges::search(ranges::subrange(it, ranges::end(base_)), pattern_);
if (b != ranges::end(base_) && ranges::empty(pattern_)) {
++b;
++e;
}
return {b, e};
```
### Parameters
| | | |
| --- | --- | --- |
| it | - | an iterator to the position at which to start the search |
### Return value
A subrange that represents the next position of the pattern, if it was found. An empty subrange otherwise.
cpp std::ranges::split_view<V,Pattern>::iterator
std::ranges::split\_view<V,Pattern>::*iterator*
===============================================
| | | |
| --- | --- | --- |
|
```
class /*iterator*/; // exposition only
```
| | (since C++20) |
The return type of [`split_view::begin`](../split_view "cpp/ranges/split view"). The name `*iterator*` is for exposition purposes only.
This is a [`forward_iterator`](../../iterator/forward_iterator "cpp/iterator/forward iterator"), so it is expected that `V` models at least [`forward_range`](../forward_range "cpp/ranges/forward range").
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_concept` | `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` |
| `iterator_category` | `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` |
| `value_type` | `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>` |
| `difference_type` | `[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` |
### Data members
Typical implementations of `*iterator*` hold four non-static data members:
* a pointer of type `[ranges::split\_view](http://en.cppreference.com/w/cpp/ranges/split_view)<V, Pattern>\*` to the parent `[split\_view](../split_view "cpp/ranges/split view")` object (shown here as `*parent\_*` for exposition only),
* an iterator of type `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>` (shown here as `*cur\_*` for exposition only) into the underlying [`view`](../view "cpp/ranges/view"); `*cur\_*` points to the begin of a current subrange,
* a subrange of type `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>` (shown here as `*next\_*` for exposition only) to the position of the pattern next to the current subrange, and
* a boolean flag (shown here as `*trailing\_empty\_*` for exposition only) that indicates whether an empty trailing subrange (if any) was reached.
### Member functions
| | |
| --- | --- |
| (constructor)
(C++20) | constructs an iterator (public member function) |
| base
(C++20) | returns the underlying iterator (public member function) |
| operator\*
(C++20) | returns the current subrange (public member function) |
| operator++operator++(int)
(C++20) | advances the iterator (public member function) |
std::ranges::split\_view::*iterator*::*iterator*
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*iterator*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/( split_view& parent, ranges::iterator_t<V> current,
ranges::subrange<ranges::iterator_t<V>> next );
```
| (2) | (since C++20) |
1) Value-initializes non-static data members with their default member initializers, that is * `[ranges::split\_view](http://en.cppreference.com/w/cpp/ranges/split_view)\* parent_ = nullptr;`,
* `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V> cur_ = [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>();`,
* `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>> next_ = [ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>>();`, and
* `bool trailing_empty_ = false;`.
2) Initializes non-static data members: * `[ranges::split\_view](http://en.cppreference.com/w/cpp/ranges/split_view)\* parent_ = [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent);`,
* `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V> cur_ = std::move(current);`,
* `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>> next_ = std::move(next);`, and
* `bool trailing_empty_ = false;`.
std::ranges::split\_view::*iterator*::base
-------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr const ranges::iterator_t<V> base() const;
```
| | (since C++20) |
Equivalent to `return cur_;`.
std::ranges::split\_view::*iterator*::operator\*
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr ranges::range_reference_t<V> operator*() const;
```
| | (since C++20) |
Equivalent to `return {cur_, next_.begin()};`.
std::ranges::split\_view::*iterator*::operator++
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++20) |
1) Equivalent to
`cur_ = next_.begin();
if (cur\_ != [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(parent\_->base\_)) {
cur\_ = next\_.end();
if (cur\_ == [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(parent\_->base\_)) {
trailing\_empty\_ = true;
next\_ = {cur\_, cur\_};
} else {
next\_ = parent\_->find\_next(cur\_);
}
} else {
trailing\_empty\_ = false;
}
return \*this;`.
2) Equivalent to `auto tmp = *this; ++*this; return tmp;`.
### Non-member functions
| | |
| --- | --- |
| operator==
(C++20) | compares the underlying iterators (function) |
operator==(std::ranges::split\_view::*iterator*, std::ranges::split\_view::*iterator*)
---------------------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y );
```
| | (since C++20) |
Equivalent to `return x.cur_ == y.cur_ && x.trailing_empty_ == y.trailing_empty_;`.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::ranges::split_view::*iterator*` is an associated class of the arguments.
cpp std::ranges::split_view<V,Pattern>::begin std::ranges::split\_view<V,Pattern>::begin
==========================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/ begin();
```
| | (since C++20) |
Returns an [`iterator`](iterator "cpp/ranges/split view/iterator") to the first found subrange.
In order to provide the amortized constant time complexity required by the [`range`](../range "cpp/ranges/range") concept, this function caches the result within the `split_view` for use on subsequent calls. Equivalent to.
```
constexpr /*iterator*/ begin() {
if (!cached_begin_.has_value())
cached_begin_ = this->find_next(ranges::begin(base_));
return { *this, ranges::begin(base_), cached_begin_.value() };
}
```
Exposition only data members [`base_`](../split_view#Data_members "cpp/ranges/split view") and [`cached_begin_`](../split_view#Data_members "cpp/ranges/split view") are described [here](../split_view#Data_members "cpp/ranges/split view").
### Parameters
(none).
### Return value
An [`iterator`](iterator "cpp/ranges/split view/iterator").
### Complexity
Amortized \(\scriptsize \mathcal{O}(1)\)O(1).
### Example
A link to check the code: [wandbox](https://wandbox.org/permlink/6VPjGp3sH1G9Qr2S).
```
#include <iostream>
#include <iomanip>
#include <ranges>
#include <string_view>
int main()
{
constexpr std::string_view sentence{ "Keep..moving..forward.." };
constexpr std::string_view delim{ ".." };
std::ranges::split_view words{ sentence, delim };
std::cout << "begin(): " << std::quoted( std::string_view{*words.begin()} )
<< "\nSubstrings: ";
for (std::string_view word: words)
std::cout << std::quoted(word) << ' ';
std::ranges::split_view letters{ sentence, std::string_view{""} };
std::cout << "\nbegin(): " << std::quoted( std::string_view{*letters.begin()} )
<< "\nLetters: ";
for (std::string_view letter: letters)
std::cout << std::quoted(letter, '\'') << ' ';
}
```
Output:
```
begin(): "Keep"
Substrings: "Keep" "moving" "forward" ""
begin(): "K"
Letters: 'K' 'e' 'e' 'p' '.' '.' 'm' 'o' 'v' 'i' 'n' 'g' '.' '.' 'f' 'o' 'r' 'w' 'a' 'r' 'd' '.' '.'
```
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/split view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [begin](../lazy_split_view/begin "cpp/ranges/lazy split view/begin")
(C++20) | returns an iterator to the beginning (public member function of `std::ranges::lazy_split_view<V,Pattern>`) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::split_view<V,Pattern>::end std::ranges::split\_view<V,Pattern>::end
========================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() const;
```
| | (since C++20) |
Returns an [`iterator`](iterator "cpp/ranges/split view/iterator") or a [`sentinel`](sentinel "cpp/ranges/split view/sentinel") representing the end of the resulting subrange.
Equivalent to:
```
constexpr auto end() {
if constexpr (ranges::common_range<V>) {
return /*iterator*/{ *this, ranges::end(base_), {} };
} else {
return /*sentinel*/{ *this };
}
}
```
### Parameters
(none).
### Return value
An [`iterator`](iterator "cpp/ranges/split view/iterator") or a [`sentinel`](sentinel "cpp/ranges/split view/sentinel").
### Example
```
#include <iostream>
#include <ranges>
#include <string_view>
int main()
{
constexpr std::string_view keywords{ "bitand bitor bool break" };
std::ranges::split_view kw{ keywords, ' ' };
const auto count = std::ranges::distance(kw.begin(), kw.end());
std::cout << "Words count: " << count << '\n';
}
```
Output:
```
Words count: 4
```
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/split view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [end](../lazy_split_view/end "cpp/ranges/lazy split view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function of `std::ranges::lazy_split_view<V,Pattern>`) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp deduction guides for std::ranges::join_view
deduction guides for `std::ranges::join_view`
=============================================
| | | |
| --- | --- | --- |
|
```
template<class R>
explicit join_view(R&&) -> join_view<views::all_t<R>>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `std::ranges::join_view` to allow deduction from [`range`](../range "cpp/ranges/range").
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `join_view<R>`; otherwise, the deduced type is usually `join_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
cpp std::ranges::join_view<V>::sentinel
std::ranges::join\_view<V>::*sentinel*
======================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/
```
| | (since C++20) |
The return type of [`join_view::end`](end "cpp/ranges/join view/end") when either of the underlying ranges (`V` or `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>`) is not a [`common_range`](../common_range "cpp/ranges/common range"), or when the parent `join_view` is not a [`forward_range`](../forward_range "cpp/ranges/forward range").
If `V` is not a [simple view](../../ranges#Helper_concepts "cpp/ranges"), `Const` is true for sentinels returned from the const overloads, and false otherwise. If `V` is a simple view, `Const` is true.
The name of this class template (shown here as `/*sentinel*/`) is unspecified.
Typical implementation holds only one data member: a sentinel `end_` obtained from (possibly const-qualified) `V`.
### Member types
| Member type | Definition |
| --- | --- |
| `Parent` (private) | `const [ranges::join\_view](http://en.cppreference.com/w/cpp/ranges/join_view)<V>` if `Const` is `true`, otherwise `[ranges::join\_view](http://en.cppreference.com/w/cpp/ranges/join_view)<V>`. The name is for exposition only |
| `Base` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/join view/sentinel/sentinel")
(C++20) | constructs a sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/join view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`join_view::begin`](begin "cpp/ranges/join view/begin") (function) |
cpp std::ranges::join_view<V>::base std::ranges::join\_view<V>::base
================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::join_view<V>::join_view std::ranges::join\_view<V>::join\_view
======================================
| | | |
| --- | --- | --- |
|
```
join_view() requires std::default_initializable<V> = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit join_view( V base );
```
| (2) | (since C++20) |
Constructs a `join_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view. After construction, [`base()`](base "cpp/ranges/join view/base") returns a copy of `V()`.
2) Initializes the underlying view with `std::move(base)`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | a view of ranges to be flattened |
### Example
cpp std::ranges::join_view<V>::iterator
std::ranges::join\_view<V>::*iterator*
======================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/
```
| | (since C++20) |
The return type of [`join_view::begin`](begin "cpp/ranges/join view/begin"), and of [`join_view::end`](end "cpp/ranges/join view/end") when both the outer range `V` and the inner range `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` satisfy [`common_range`](../common_range "cpp/ranges/common range") and the parent `join_view` is a [`forward_range`](../forward_range "cpp/ranges/forward range").
If `V` is not a [simple view](../../ranges#Helper_concepts "cpp/ranges") (e.g. if `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const V>` is invalid or different from `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<V>`), `Const` is true for iterators returned from the const overloads, and false otherwise. If `V` is a simple view, `Const` is true if and only if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` is a reference.
The name of this class template (shown here as `/*iterator*/`) is unspecified.
### Member types
| Member type | Definition |
| --- | --- |
| `Parent` (private) | `const join_view<V>` if `Const` is `true`, otherwise `join_view<V>`. The name is for exposition only. |
| `Base` (private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only. |
| `OuterIter` (private) | `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>`. The name is for exposition only. |
| `InnerIter` (private) | `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>`. The name is for exposition only. |
| `iterator_concept` | * `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type, and `Base` and `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` each model [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range");
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` is a reference type, and `Base` and `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>` each model [`forward_range`](../forward_range "cpp/ranges/forward range");
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise.
|
| `iterator_category` | Defined only if `iterator::iterator_concept` (see above) denotes `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`. Let `*OUTERC*` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>>::iterator\_category`, and let `*INNERC*` be `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>::iterator\_category`.* `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `*OUTERC*` and `*INNERC*` each model `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::bidirectional\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`;
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if `*OUTERC*` and `*INNERC*` each model `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::forward\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`;
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise.
|
| `value_type` | `[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>` |
| `difference_type` | `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>, [ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>>` |
### Member objects
| Member name | Definition |
| --- | --- |
| `*outer\_*` (private) | an object of type `OuterIter`. The name is for exposition only. |
| `*inner\_*` (private) | an object of type `InnerIter`. The name is for exposition only. |
| `*parent\_*` (private) | an object of type `Parent`. The name is for exposition only. |
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/join view/iterator/iterator")
(C++20) | constructs an iterator (public member function) |
| [operator\*operator->](iterator/operator* "cpp/ranges/join view/iterator/operator*")
(C++20) | accesses the element (public member function) |
| [operator++operator++(int)operator--operator--(int)](iterator/operator_arith "cpp/ranges/join view/iterator/operator arith")
(C++20) | advances or decrements the underlying iterators (public member function) |
| [*satisfy*](iterator/satisfy "cpp/ranges/join view/iterator/satisfy")
(C++20) | skips over empty inner ranges; the name is for exposition only (exposition-only member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](iterator/operator_cmp "cpp/ranges/join view/iterator/operator cmp")
(C++20) | compares the underlying iterators (function) |
| [iter\_move](iterator/iter_move "cpp/ranges/join view/iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](iterator/iter_swap "cpp/ranges/join view/iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function) |
| programming_docs |
cpp std::ranges::join_view<V>::begin std::ranges::join\_view<V>::begin
=================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const
requires ranges::input_range<const V> &&
std::is_reference_v<ranges::range_reference_t<const V>>;
```
| (2) | (since C++20) |
Returns an [iterator](iterator "cpp/ranges/join view/iterator") to the first element of the `join_view`. Given `base_` is the underlying view,
1) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};` if `__SimpleView<V>` is satisfied and `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` is reference type. Otherwise, equivalent to `return /\*iterator\*/<false>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`.
2) Equivalent to `return /\*iterator\*/<true>{\*this, [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)};`. ### Parameters
(none).
### Return value
Iterator to the first element.
### Notes
When `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<V>` is not a reference type, that is, deferencing an iterator of `V` returns a prvalue temporary, the `join_view` is only an [`input_range`](../input_range "cpp/ranges/input range"), in which case only single-pass iteration is supported, and repeated calls to `begin()` may not give meaningful results.
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/join view/end")
(C++20) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::join_view<V>::end std::ranges::join\_view<V>::end
===============================
| | | |
| --- | --- | --- |
|
```
constexpr auto end();
```
| (1) | (since C++20) |
|
```
constexpr auto end() const
requires ranges::input_range<const V> &&
std::is_reference_v<ranges::range_reference_t<const V>>;
```
| (2) | (since C++20) |
Returns a [sentinel](sentinel "cpp/ranges/join view/sentinel") or an [iterator](iterator "cpp/ranges/join view/iterator") representing the end of the `join_view`.
Let `base_` be the underlying view:
1) Equivalent to
```
if constexpr (ranges::forward_range<V> &&
std::is_reference_v<ranges::range_reference_t<V>> &&
ranges::forward_range<ranges::range_reference_t<V>> &&
ranges::common_range<V> &&
ranges::common_range<ranges::range_reference_t<V>>)
return /*iterator*/<__SimpleView<V>>{*this, ranges::end(base_)};
else
return /*sentinel*/<__SimpleView<V>>{*this};
```
2) Equivalent to
```
if constexpr (ranges::forward_range<const V> &&
std::is_reference_v<ranges::range_reference_t<const V>> &&
ranges::forward_range<ranges::range_reference_t<const V>> &&
ranges::common_range<const V> &&
ranges::common_range<ranges::range_reference_t<const V>>)
return /*iterator*/<true>{*this, ranges::end(base_)};
else
return /*sentinel*/<true>{*this};
```
### Parameters
(none).
### Return value
1) sentinel which compares equal to the end iterator.
2) iterator to the element following the last element. ### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/join view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::join_view<V>::sentinel<Const>::sentinel
std::ranges::join\_view<V>::*sentinel*<Const>::*sentinel*
=========================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( Parent& parent );
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const &&
std::convertible_to<ranges::sentinel_t<V>, ranges::sentinel_t<Base>>;
```
| (3) | (since C++20) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel.
2) Initializes the underlying sentinel `end_` with `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(parent.base\_)`.
3) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs the underlying sentinel `end_` with `std::move(i.end_)`. ### Parameters
| | | |
| --- | --- | --- |
| parent | - | a (possibly const-qualified) `[ranges::join\_view](../../join_view "cpp/ranges/join view")` |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp operator==(ranges::join_view::iterator, ranges::join_view::sentinel) operator==(ranges::join\_view::*iterator*, ranges::join\_view::*sentinel*)
==========================================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/<Const>& x, const /*sentinel*/& y );
```
| | (since C++20) |
Compares the underlying iterator of `x` with the underlying sentinel of `y`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../iterator "cpp/ranges/join view/iterator") to compare |
| y | - | sentinel to compare |
### Return value
`x.current_ == y.end_`, where `current_` denotes the underlying iterator, `end_` denotes the underlying sentinel.
### Example
cpp iter_move(ranges::join_view::iterator) iter\_move(ranges::join\_view::*iterator*)
==========================================
| | | |
| --- | --- | --- |
|
```
friend constexpr decltype(auto) iter_move( const /*iterator*/& i )
noexcept( /*see below*/ );
```
| | (since C++20) |
Casts the result of dereferencing the underlying iterator `i.inner_` to its associated rvalue reference type.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator |
### Return value
Equivalent to: `[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.inner\_)`.
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept([ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.inner\_)))`
### See also
| | |
| --- | --- |
| [iter\_move](../../../iterator/ranges/iter_move "cpp/iterator/ranges/iter move")
(C++20) | casts the result of dereferencing an object to its associated rvalue reference type (customization point object) |
cpp std::ranges::join_view<V>::iterator<Const>::iterator
std::ranges::join\_view<V>::*iterator*<Const>::*iterator*
=========================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/() requires std::default_initializable<OuterIter> &&
std::default_initializable<InnerIter> = default;
```
| (1) | (since C++20) |
|
```
constexpr /*iterator*/( Parent& parent, OuterIter outer );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i )
requires Const &&
std::convertible_to<ranges::iterator_t<V>, OuterIter> &&
std::convertible_to<ranges::iterator_t<InnerRng>, InnerIter>;
```
| (3) | (since C++20) |
Construct an iterator.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying iterators, and initializes the pointer to parent `[ranges::join\_view](../../join_view "cpp/ranges/join view")` with `nullptr`.
2) Initializes the underlying `*outer\_*` iterator with `std::move(outer)`, and the pointer to parent `*parent\_*` with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)`; then calls [`satisfy()`](satisfy "cpp/ranges/join view/iterator/satisfy").
3) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Move constructs the underlying iterators `*outer\_*` with `std::move(i.outer_)`, `*inner\_*` with `std::move(i.inner_)`, and underlying pointer to parent `*parent\_*` with `i.parent_`. ### Parameters
| | | |
| --- | --- | --- |
| parent | - | a (possibly const-qualified) `[ranges::join\_view](../../join_view "cpp/ranges/join view")` |
| outer | - | an iterator into (possibly const-qualified) `[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Base>` |
| i | - | an `/*iterator*/<false>` |
### Example
cpp std::ranges::join_view<V>::iterator<Const>::operator++,-- std::ranges::join\_view<V>::*iterator*<Const>::operator++,--
============================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++20) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++20) |
|
```
constexpr /*iterator*/ operator++( int )
requires /*ref-is-glvalue*/ && ranges::forward_range<Base> &&
ranges::forward_range<ranges::range_reference_t<Base>>;
```
| (3) | (since C++20) |
|
```
constexpr iterator& operator--()
requires /*ref-is-glvalue*/ && ranges::bidirectional_range<Base> &&
ranges::bidirectional_range<ranges::range_reference_t<Base>> &&
ranges::common_range<ranges::range_reference_t<Base>>;
```
| (4) | (since C++20) |
|
```
constexpr /*iterator*/ operator--( int )
requires /*ref-is-glvalue*/ && ranges::bidirectional_range<Base> &&
ranges::bidirectional_range<ranges::range_reference_t<Base>> &&
ranges::common_range<ranges::range_reference_t<Base>>;
```
| (5) | (since C++20) |
Increments or decrements the underlying iterator.
Let `inner_` and `outer_` be the underlying iterators, and `parent_` be the pointer to parent `[ranges::join\_view](../../join_view "cpp/ranges/join view")`, the constant `/*ref-is-glvalue*/` be `[std::is\_reference\_v](http://en.cppreference.com/w/cpp/types/is_reference)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>`.
1) Let `/*inner-range*/` be: * `*outer_`, if `/*ref-is-glvalue*/ == true`;
* `*parent_->inner_` otherwise.
Equivalent to:
```
auto&& inner_rng = /*inner-range*/;
if (++inner_ == ranges::end(inner_rng)) {
++outer_;
satisfy();
}
return *this;
```
2) Equivalent to: `++*this`.
3) Equivalent to:
```
auto tmp = *this;
++*this;
return tmp;
```
4) Equivalent to:
```
if (outer_ == ranges::end(parent_->base_))
inner_ = ranges::end(*--outer_);
while (inner_ == ranges::begin(*outer_))
inner_ = ranges::end(*--outer_);
--inner_;
return *this;
```
5) Equivalent to:
```
auto tmp = *this;
--*this;
return tmp;
```
### Parameters
(none).
### Return value
1,4) `*this`
2) (none)
3,5) a copy of `*this` that was made before the change
cpp std::ranges::join_view<V>::iterator<Const>::satisfy std::ranges::join\_view<V>::*iterator*<Const>::satisfy
======================================================
| | | |
| --- | --- | --- |
|
```
private: constexpr void satisfy(); // exposition only
```
| | (since C++20) |
Skips over empty inner ranges and initializes the underlying iterator `inner_`.
Let the constant `/*ref-is-glvalue*/` be `[std::is\_reference\_v](http://en.cppreference.com/w/cpp/types/is_reference)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>`. The function body is equivalent to.
```
auto update_inner = [this](const ranges::iterator_t<Base>& x) -> auto&& {
if constexpr (/*ref-is-glvalue*/) // *x is a reference
return *x;
else
return parent_->inner_./*emplace-deref*/(x);
};
for (; outer_ != ranges::end(parent_->base_); ++outer_) {
auto&& inner = update_inner(outer_);
inner_ = ranges::begin(inner);
if (inner_ != ranges::end(inner))
return;
}
if constexpr (/*ref-is-glvalue*/)
inner_ = InnerIter();
```
### Parameters
(none).
### Return value
(none).
cpp iter_swap(ranges::join_view::iterator) iter\_swap(ranges::join\_view::*iterator*)
==========================================
| | | |
| --- | --- | --- |
|
```
friend constexpr void iter_swap( const /*iterator*/& x, const /*iterator*/& y )
noexcept( /*see below*/ )
requires std::indirectly_swappable<InnerIter>;
```
| | (since C++20) |
Swaps the objects pointed to by two underlying iterators (denoted as `inner_`).
Equivalent to: `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.inner\_, y.inner\_);`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `join_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators |
### Return value
(none).
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept([ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.inner\_, y.inner\_)))`
### See also
| | |
| --- | --- |
| [iter\_swap](../../../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
| [iter\_swap](../../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
cpp operator==(ranges::join_view::iterator, ranges::join_view::iterator) operator==(ranges::join\_view::*iterator*, ranges::join\_view::*iterator*)
==========================================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires
/*ref-is-glvalue*/ &&
std::equality_comparable<ranges::iterator_t<Base>> &&
std::equality_comparable<ranges::iterator_t<ranges::range_reference_t<Base>>>;
```
| | (since C++20) |
Compares the underlying iterators.
Equivalent to: `return (x.outer_ == y.outer_) and (x.inner_ == y.inner_);`, where `outer_` and `inner_` are the underlying iterators. The constant `/*ref-is-glvalue*/` in the requires-clause is equal to `[std::is\_reference\_v](http://en.cppreference.com/w/cpp/types/is_reference)<[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Base>>`.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::join_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
Result of comparison.
### Example
cpp std::ranges::view_interface<D>::size std::ranges::view\_interface<D>::size
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size() requires ranges::forward_range<D> &&
std::sized_sentinel_for<ranges::sentinel_t<D>,
ranges::iterator_t<D>>;
```
| (1) | (since C++20) |
|
```
constexpr auto size() const requires ranges::forward_range<const D> &&
std::sized_sentinel_for<ranges::sentinel_t<const D>,
ranges::iterator_t<const D>>;
```
| (2) | (since C++20) |
The default implementation of `size()` member function obtains the size of the range by calculating the difference between the sentinel and the beginning iterator.
1) Let `derived` be `static_cast<D&>(*this)`. Equivalent to `return [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(derived) - [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(derived);`.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
The difference between the sentinel and the beginning iterator of the value of the derived type.
### Notes
Following derived types may use the default implementation of `size()`:
* `[std::ranges::drop\_while\_view](../drop_while_view "cpp/ranges/drop while view")`
Following types are derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` and do not declare their own `size()` member function, but they cannot use the default implementation, because their iterator and sentinel types never satisfy [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for"):
* `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`
* `[std::ranges::filter\_view](../filter_view "cpp/ranges/filter view")`
* `[std::ranges::join\_view](../join_view "cpp/ranges/join view")`
* `std::ranges::lazy_split_view`
* `[std::ranges::split\_view](../split_view "cpp/ranges/split view")`
* `[std::ranges::take\_while\_view](../take_while_view "cpp/ranges/take while view")`
### See also
| | |
| --- | --- |
| [sizessize](../../iterator/size "cpp/iterator/size")
(C++17)(C++20) | returns the size of a container or array (function template) |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp std::ranges::view_interface<D>::operator[] std::ranges::view\_interface<D>::operator[]
===========================================
| | | |
| --- | --- | --- |
|
```
template<ranges::random_access_range R = D>
constexpr decltype(auto) operator[]( ranges::range_difference_t<R> n );
```
| (1) | (since C++20) |
|
```
template<ranges::random_access_range R = const D>
constexpr decltype(auto) operator[]( ranges::range_difference_t<R> n ) const;
```
| (2) | (since C++20) |
The default implementation of `operator[]` member function obtains the element at the specified offset relative to the beginning iterator, reusing the `operator[]` of the iterator type.
1) Let `derived` be `static_cast<D&>(*this)`. Equivalent to `return [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(derived)[n];`.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | position of the element to return |
### Return value
The element at offset `n` relative to the beginning iterator.
### Notes
In C++20, no type derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` in the standard library provides their own `operator[]` member function.
However, following derived types cannot use the default implementations, as they never satisfy [`random_access_range`](../random_access_range "cpp/ranges/random access range"):
* `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`
* `[std::ranges::filter\_view](../filter_view "cpp/ranges/filter view")`
* `[std::ranges::join\_view](../join_view "cpp/ranges/join view")`
* `std::ranges::lazy_split_view`
* `[std::ranges::split\_view](../split_view "cpp/ranges/split view")`
The inherited `operator[]` member function is available for `[std::ranges::empty\_view](../empty_view "cpp/ranges/empty view")`, but a call to it always results in undefined behavior.
### Example
| programming_docs |
cpp std::ranges::view_interface<D>::back std::ranges::view\_interface<D>::back
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) back()
requires ranges::bidirectional_range<D> && ranges::common_range<D>;
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) back() const
requires ranges::bidirectional_range<const D> && ranges::common_range<const D>;
```
| (2) | (since C++20) |
The default implementation of `back()` member function returns the last element in the view of the derived type. Whether the element is returned by value or by reference depends on the `operator*` of the iterator type.
1) Let `derived` be `static_cast<D&>(*this)`. Equivalent to `return \*[ranges::prev](http://en.cppreference.com/w/cpp/iterator/ranges/prev)([ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(derived));`. The behavior is undefined if [`empty()`](empty "cpp/ranges/view interface/empty") is `true` (i.e. the beginning iterator compares equal to the sentinel), even if the iterator obtained in the same way is dereferenceable.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
The last element in the view.
### Notes
In C++20, no type derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` in the standard library provides their own `back()` member function.
However, following derived types cannot use the default implementations, as they never satisfy neither [`bidirectional_range`](../bidirectional_range "cpp/ranges/bidirectional range") nor [`common_range`](../common_range "cpp/ranges/common range"):
* `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`
* `std::ranges::lazy_split_view`
* `[std::ranges::split\_view](../split_view "cpp/ranges/split view")`
* `[std::ranges::take\_while\_view](../take_while_view "cpp/ranges/take while view")`
The inherited `back()` member function is available for `[std::ranges::empty\_view](../empty_view "cpp/ranges/empty view")`, but a call to it always results in undefined behavior.
### Example
### See also
| | |
| --- | --- |
| [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin")
(C++14) | returns a reverse iterator to the beginning of a container or array (function template) |
| [ranges::rbegin](../rbegin "cpp/ranges/rbegin")
(C++20) | returns a reverse iterator to a range (customization point object) |
| [ranges::crbegin](../crbegin "cpp/ranges/crbegin")
(C++20) | returns a reverse iterator to a read-only range (customization point object) |
cpp std::ranges::view_interface<D>::operator bool std::ranges::view\_interface<D>::operator bool
==============================================
| | | |
| --- | --- | --- |
|
```
explicit constexpr operator bool() requires /* see below */;
```
| (1) | (since C++20) |
|
```
explicit constexpr operator bool() const requires /* see below */;
```
| (2) | (since C++20) |
The default implementation of `operator bool` member function checks whether the view is non-empty. It makes the derived type [contextually convertible to `bool`](../../language/implicit_conversion#Contextual_conversions "cpp/language/implicit conversion").
1) Let `derived` be `static_cast<D&>(*this)`. The expression in the requires-clause is equal to `requires { [ranges::empty](http://en.cppreference.com/w/cpp/ranges/empty)(derived); }`, and the function body is equivalent to `return (derived);`.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
`false` if the value of the derived type is empty (determined by `[std::ranges::empty](../empty "cpp/ranges/empty")`), `true` otherwise.
### Notes
In C++20, no type derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` in the standard library provides their own `operator bool`. Almost all of these types use the default implementation.
A notable exception is `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`. For its iterator type never satisfies [`forward_iterator`](../../iterator/forward_iterator "cpp/iterator/forward iterator"), the view cannot use the inherited `operator bool`.
### Example
```
#include <array>
#include <iostream>
#include <ranges>
int main() {
const std::array ints {0, 1, 2, 3, 4};
auto odds = ints | std::views::filter([](int i) { return 0 != i % 2; });
auto negs = ints | std::views::filter([](int i) { return i < 0; });
std::cout << std::boolalpha
<< "Has odd numbers: " << (!!odds) << ' ' << '\n'
<< "Has negative numbers: " << (!!negs) << ' ' << '\n';
}
```
Output:
```
Has odd numbers: true
Has negative numbers: false
```
### See also
| | |
| --- | --- |
| [ranges::empty](../empty "cpp/ranges/empty")
(C++20) | checks whether a range is empty (customization point object) |
| [empty](empty "cpp/ranges/view interface/empty")
(C++20) | Returns whether the derived view is empty. Provided if it satisfies [`sized_range`](../sized_range "cpp/ranges/sized range") or [`forward_range`](../forward_range "cpp/ranges/forward range"). (public member function) |
| [empty](../../iterator/empty "cpp/iterator/empty")
(C++17) | checks whether the container is empty (function template) |
cpp std::ranges::view_interface<D>::data std::ranges::view\_interface<D>::data
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr auto data()
requires std::contiguous_iterator<ranges::iterator_t<D>>;
```
| (1) | (since C++20) |
|
```
constexpr auto data() const
requires ranges::range<const D> &&
std::contiguous_iterator<ranges::iterator_t<const D>>;
```
| (2) | (since C++20) |
The default implementation of `data()` member function obtains the address denoted by the beginning iterator via `std::to_address`, which is also the lowest address of the contiguous storage (implied by [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator")) referenced by the view of the derived type when the view is not empty.
1) Let `derived` be `static_cast<D&>(*this)`. Equivalent to `return [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(derived));`.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
The address denoted by the beginning iterator.
### Notes
Following derived types may use the default implementation of `data()`:
* `[std::ranges::common\_view](../common_view "cpp/ranges/common view")`
* `[std::ranges::drop\_view](../drop_view "cpp/ranges/drop view")`
* `[std::ranges::drop\_while\_view](../drop_while_view "cpp/ranges/drop while view")`
* `[std::ranges::ref\_view](../ref_view "cpp/ranges/ref view")`
* `[std::ranges::subrange](../subrange "cpp/ranges/subrange")`
* `[std::ranges::take\_view](../take_view "cpp/ranges/take view")`
* `[std::ranges::take\_while\_view](../take_while_view "cpp/ranges/take while view")`
Following types are derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` and do not declare their own `data()` member function, but they cannot use the default implementation, because their iterator types never satisfy [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"):
* `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`
* `[std::ranges::elements\_view](../elements_view "cpp/ranges/elements view")`
* `[std::ranges::filter\_view](../filter_view "cpp/ranges/filter view")`
* `[std::ranges::iota\_view](../iota_view "cpp/ranges/iota view")`
* `[std::ranges::join\_view](../join_view "cpp/ranges/join view")`
* `std::ranges::lazy_split_view`
* `[std::ranges::reverse\_view](../reverse_view "cpp/ranges/reverse view")`
* `[std::ranges::split\_view](../split_view "cpp/ranges/split view")`
* `[std::ranges::transform\_view](../transform_view "cpp/ranges/transform view")`
### Example
```
#include <array>
#include <iostream>
#include <ranges>
#include <string_view>
int main() {
constexpr std::string_view str { "Hello, C++20!" };
std::cout << (str | std::views::drop(7)).data() << '\n';
constexpr static std::array a { 1,2,3,4,5 };
constexpr auto v { a | std::views::take(3) };
static_assert( &a[0] == v.data() );
}
```
Output:
```
C++20!
```
### See also
| | |
| --- | --- |
| [data](../../iterator/data "cpp/iterator/data")
(C++17) | obtains the pointer to the underlying array (function template) |
| [ranges::data](../data "cpp/ranges/data")
(C++20) | obtains a pointer to the beginning of a contiguous range (customization point object) |
| [ranges::cdata](../cdata "cpp/ranges/cdata")
(C++20) | obtains a pointer to the beginning of a read-only contiguous range (customization point object) |
| [to\_address](../../memory/to_address "cpp/memory/to address")
(C++20) | obtains a raw pointer from a pointer-like type (function template) |
cpp std::ranges::view_interface<D>::front std::ranges::view\_interface<D>::front
======================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) front()
requires ranges::forward_range<D>;
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) front() const
requires ranges::forward_range<const D>;
```
| (2) | (since C++20) |
The default implementation of `front()` member function returns the first element in the view of the derived type. Whether the element is returned by value or by reference depends on the `operator*` of the iterator type.
1) Let `derived` be `static_cast<D&>(*this)`. Equivalent to `return \*[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(derived);`. The behavior is undefined if [`empty()`](empty "cpp/ranges/view interface/empty") is `true` (i.e. the beginning iterator compares equal to the sentinel), even if the iterator obtained in the same way is dereferenceable.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
The first element in the view.
### Notes
In C++20, no type derived from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` in the standard library provides their own `front()` member function. Almost all of these types use the default implementation.
A notable exception is `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")`. For it never satisfies [`forward_range`](../forward_range "cpp/ranges/forward range"), the view cannot use the inherited `front()`.
The inherited `front()` member function is available for `[std::ranges::empty\_view](../empty_view "cpp/ranges/empty view")` , but a call to it always results in undefined behavior.
### Example
### See also
| | |
| --- | --- |
| [begincbegin](../../iterator/begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::cbegin](../cbegin "cpp/ranges/cbegin")
(C++20) | returns an iterator to the beginning of a read-only range (customization point object) |
cpp std::ranges::view_interface<D>::empty std::ranges::view\_interface<D>::empty
======================================
| | | |
| --- | --- | --- |
|
```
constexpr bool empty()
requires ranges::sized_range<D> || ranges::forward_range<D>;
```
| (1) | (since C++20) |
|
```
constexpr bool empty() const
requires ranges::sized_range<const D> || ranges::forward_range<const D>;
```
| (2) | (since C++20) |
The default implementation of `empty()` member function checks whether the object of the derived type's size is `0` (if valid), or whether the beginning iterator and the sentinel compare equal.
1) Let `derived` be a reference bound to `static_cast<D&>(*this)`. Equivalent to `return [ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(derived) == 0;` if `D` satisfies [`sized_range`](../sized_range "cpp/ranges/sized range"). Otherwise, equivalent to `return [ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(derived) == [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(derived);`.
2) Same as (1), except that `derived` is `static_cast<const D&>(*this)`. ### Parameters
(none).
### Return value
`true` if the size of the object of the derived type is `0` (if `D` satisfies `[std::ranges::sized\_range](../sized_range "cpp/ranges/sized range")`), or its beginning iterator and the sentinel compare equal, `false` otherwise.
### Notes
Following derived types may use the default implementation of `empty`:
* `[std::ranges::common\_view](../common_view "cpp/ranges/common view")`
* `[std::ranges::drop\_view](../drop_view "cpp/ranges/drop view")`
* `[std::ranges::drop\_while\_view](../drop_while_view "cpp/ranges/drop while view")`
* `[std::ranges::elements\_view](../elements_view "cpp/ranges/elements view")`
* `[std::ranges::filter\_view](../filter_view "cpp/ranges/filter view")`
* `[std::ranges::iota\_view](../iota_view "cpp/ranges/iota view")`
* `[std::ranges::join\_view](../join_view "cpp/ranges/join view")`
* `std::ranges::lazy_split_view`
* `[std::ranges::reverse\_view](../reverse_view "cpp/ranges/reverse view")`
* `[std::ranges::single\_view](../single_view "cpp/ranges/single view")`
* `[std::ranges::split\_view](../split_view "cpp/ranges/split view")`
* `[std::ranges::take\_view](../take_view "cpp/ranges/take view")`
* `[std::ranges::take\_while\_view](../take_while_view "cpp/ranges/take while view")`
* `[std::ranges::transform\_view](../transform_view "cpp/ranges/transform view")`
Although `[std::ranges::basic\_istream\_view](../basic_istream_view "cpp/ranges/basic istream view")` inherits from `[std::ranges::view\_interface](../view_interface "cpp/ranges/view interface")` and does not declare the `empty()` member function, it cannot use the default implementation, because it never satisfies neither `[std::ranges::sized\_range](../sized_range "cpp/ranges/sized range")` nor `[std::ranges::forward\_range](../forward_range "cpp/ranges/forward range")`.
### Example
```
#include <array>
#include <ranges>
int main() {
constexpr std::array a {0, 1, 2, 3, 4};
static_assert( ! std::ranges::single_view(a).empty() );
static_assert( (a | std::views::take(0)).empty() );
static_assert( ! (a | std::views::take(2)).empty() );
static_assert( (a | std::views::drop(9)).empty() );
static_assert( ! (a | std::views::drop(2)).empty() );
static_assert( std::views::iota(0,0).empty() );
static_assert( ! std::views::iota(0).empty() );
}
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3715](https://cplusplus.github.io/LWG/issue3715) | C++20 | `empty()` only supported [`forward_range`](../forward_range "cpp/ranges/forward range") types | [`sized_range`](../sized_range "cpp/ranges/sized range")-only types are also supported |
### See also
| | |
| --- | --- |
| [empty](../../iterator/empty "cpp/iterator/empty")
(C++17) | checks whether the container is empty (function template) |
| [ranges::empty](../empty "cpp/ranges/empty")
(C++20) | checks whether a range is empty (customization point object) |
cpp std::ranges::zip_transform_view<F,Views...>::size std::ranges::zip\_transform\_view<F,Views...>::size
===================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size()
requires ranges::sized_range</*InnerView*/>;
```
| (1) | (since C++23) |
|
```
constexpr auto size() const
requires ranges::sized_range<const /*InnerView*/>
```
| (2) | (since C++23) |
Returns the number of elements in the `zip_transform_view`. Provided only if each underlying (adapted) range satisfies [`sized_range`](../sized_range "cpp/ranges/sized range").
1,2) Equivalent to: `return zip_.size();`. ### Parameters
(none).
### Return value
The number of elements, which is the minimum size among all sizes of adapted [`view`s](../view "cpp/ranges/view").
### Example
```
#include <algorithm>
#include <cassert>
#include <deque>
#include <forward_list>
#include <functional>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
auto x = std::vector{1, 2, 3, 4, 5};
auto y = std::deque<short>{10, 20, 30};
auto z = std::forward_list{100., 200.};
auto v1 = std::views::zip_transform(std::plus, x, y);
assert(v1.size() == std::min(x.size(), y.size()));
assert(v1.size() == 3);
for (int i : v1) std::cout << i << '\n';
[[maybe_unused]] auto v2 = std::views::zip_transform(std::plus, x, z);
// auto sz = v2.size(); // Error, v2 does not have size():
static_assert(not std::ranges::sized_range<decltype(z)>);
}
```
Output:
```
11 22 33
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::zip_transform_view
deduction guides for `std::ranges::zip_transform_view`
======================================================
| | | |
| --- | --- | --- |
|
```
template< class F, class... Rs >
zip_transform_view( F, Rs&&... ) -> zip_transform_view<F, views::all_t<Rs>...>;
```
| | (since C++23) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `std::ranges::zip_transform_view` to allow deduction from transformation function and [`range`s](../range "cpp/ranges/range").
### Example
cpp std::ranges::zip_transform_view<F,Views...>::sentinel
std::ranges::zip\_transform\_view<F,Views...>::*sentinel*
=========================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/; // exposition only
```
| | (since C++23) |
The return type of [`zip_transform_view::end`](end "cpp/ranges/zip transform view/end") when the underlying view is not a [`common_range`](../common_range "cpp/ranges/common range"). The name of this class template (shown here as `*sentinel*`) is unspecified.
The type `/*sentinel*/<true>` or `/*sentinel*/<false>` treats the underlying view as const-qualified or non-const-qualified respectively.
### Data members
Typical implementation of `*sentinel*` holds only one non-static data member `*inner\_*` of type [`*zentinel*<Const>`](../zip_transform_view#Member_types "cpp/ranges/zip transform view"). The name `*inner\_*` is for exposition purposes only.
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/zip transform view/sentinel/sentinel")
(C++23) | constructs a sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/zip transform view/sentinel/operator cmp")
(C++23) | compares a sentinel with an iterator returned from [`zip_transform_view::begin`](begin "cpp/ranges/zip transform view/begin") (function) |
| [operator-](sentinel/operator- "cpp/ranges/zip transform view/sentinel/operator-")
(C++23) | computes the distance between a sentinel and an iterator returned from [`zip_transform_view::begin`](begin "cpp/ranges/zip transform view/begin") (function) |
| programming_docs |
cpp std::ranges::zip_transform_view<F,Views...>::zip_transform_view std::ranges::zip\_transform\_view<F,Views...>::zip\_transform\_view
===================================================================
| | | |
| --- | --- | --- |
|
```
zip_transform_view() = default;
```
| (1) | (since C++23) |
|
```
constexpr zip_transform_view( F fun, Views... views );
```
| (2) | (since C++23) |
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the stored invocable object and all adapted [`view`](../view "cpp/ranges/view") objects.
The default constructor is deleted if.
* `F` does not satisfy [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable"), or
* `[std::is\_default\_constructible\_v](../../types/is_default_constructible "cpp/types/is default constructible")` is `false` for at least one type in `Views...`.
2) Move constructs the stored invocable object from `fun` and every adapted [`view`](../view "cpp/ranges/view") object from the corresponding view in `views...`. ### Parameters
| | | |
| --- | --- | --- |
| f | - | invocable object used for generation of elements of `zip_transform_view` |
| views | - | view objects to adapt |
### Example
cpp std::ranges::zip_transform_view<F,Views...>::iterator
std::ranges::zip\_transform\_view<F,Views...>::*iterator*
=========================================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/; // exposition only
```
| | (since C++23) |
The iterator type of a possibly const-qualified `zip_transform_view`, returned by [`zip_transform_view::begin`](begin "cpp/ranges/zip transform view/begin") and in certain cases by [`zip_transform_view::end`](end "cpp/ranges/zip transform view/end"). The name of this class template (shown here as `*iterator*`) is unspecified.
The type `/*iterator*/<true>` or `/*iterator*/<false>` treats the underlying views as const-qualified or non-const-qualified respectively.
### Member types
| Member type | Definition |
| --- | --- |
| `*Parent*` (private) | [`zip_transform_view`](../zip_transform_view "cpp/ranges/zip transform view") if `Const` is `false`, `const zip_transform_view` otherwise. The name is for exposition only. |
| `*Base*` (private) | [`*InnerView*`](../zip_transform_view#Member_types "cpp/ranges/zip transform view") if `Const` is `false`, `const InnerView` otherwise. The name is for exposition only. |
| `iterator_category` | Let `/*maybe-const*/<Const, F>&` denote `const F&` if `Const` is `true`, `F&` otherwise. Let `/*maybe-const*/<Const, Views>` denote `const Views` if `Const` is `true`, `Views` otherwise.
Let `/*POT*/` denote the pack of types `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<std::iterator\_t< /\*maybe-const\*/<Const, Views>>>::iterator\_category...`
If `/*Base*/` models [`forward_range`](../forward_range "cpp/ranges/forward range"), then `iterator_category` denotes:* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
`[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)</\*maybe-const\*/<Const, F>&, [ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)</\*maybe-const\*/<Const, Views>>...>` is not an lvalue reference.* Otherwise,
* `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
`([std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)</\*POT\*/, [std::random\_access\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)> && ...)` is `true`.* Otherwise, `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
`([std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)</\*POT\*/, [std::bidirectional\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)> && ...)` is `true`.* Otherwise, `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`, if
`([std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)</\*POT\*/, [std::forward\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)> && ...)` is `true`.* Otherwise, `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`.
Not present if `/*Base*/` does not model [`forward_range`](../forward_range "cpp/ranges/forward range"). |
| `iterator_concept` | `/*ziperator*/<Const>::iterator_concept` |
| `value_type` | Let `/*RREF*/` be `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Views>...`, and `/*CRREF*/` be `[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<const Views>...`. Then:* `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<F&, /\*RREF\*/>>` if `Const` is `false`,
* `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<[std::invoke\_result\_t](http://en.cppreference.com/w/cpp/types/result_of)<const F&, /\*CRREF\*/>>` otherwise.
|
| `difference_type` | `range::range_difference_t</*Base*/>` |
### Data members
Typical implementations of `*iterator*` hold two non-static data members:
* a pointer `*parent\_*` of type [`*Parent*`](#Member_types) to the parent object
* an iterator `*inner\_*` of type [`*ziperator<Const>*`](../zip_transform_view#Member_types "cpp/ranges/zip transform view").
These names are for exposition purposes only.
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/zip transform view/iterator/iterator")
(C++23) | constructs an iterator (public member function) |
| [operator\*](iterator/operator* "cpp/ranges/zip transform view/iterator/operator*")
(C++23) | obtains the result of applying the invocable object to the underlying poined-to elements (public member function) |
| [operator[]](iterator/operator_at "cpp/ranges/zip transform view/iterator/operator at")
(C++23) | obtains the result of applying the invocable object to the underlying elements at given offset (public member function) |
| [operator++operator++(int)operator--operator--(int)operator+=operator-=](iterator/operator_arith "cpp/ranges/zip transform view/iterator/operator arith")
(C++23) | advances or decrements the underlying iterators (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<operator>operator<=operator>=operator<=>](iterator/operator_cmp "cpp/ranges/zip transform view/iterator/operator cmp")
(C++23) | compares the underlying iterators (function) |
| [operator+operator-](iterator/operator_arith2 "cpp/ranges/zip transform view/iterator/operator arith2")
(C++23) | performs iterator arithmetic on underlying iterators (function) |
cpp std::ranges::zip_transform_view<F,Views...>::begin std::ranges::zip\_transform\_view<F,Views...>::begin
====================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin();
```
| (1) | (since C++23) |
|
```
constexpr auto begin() const
requires ranges::range<const ranges::zip_view<Views...>>;
```
| (2) | (since C++23) |
Obtains the beginning iterator of `zip_transform_view`.
1) Equivalent to `return /*iterator*/<false>(*this, zip_.begin());`.
2) Equivalent to `return /*iterator*/<true>(*this, zip_.begin());`. ### Parameters
(none).
### Return value
[Iterator](iterator "cpp/ranges/zip transform view/iterator") to the first element.
### Notes
`[ranges::range](http://en.cppreference.com/w/cpp/ranges/range)<const ranges::zip\_view<Views...>>` is modeled if and only if for every type `Vi` in `Views...`, `const Vi` models [`range`](../range "cpp/ranges/range").
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/zip transform view/end")
(C++23) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::zip_transform_view<F,Views...>::end std::ranges::zip\_transform\_view<F,Views...>::end
==================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end();
```
| (1) | (since C++23) |
|
```
constexpr auto end() const
requires ranges::range<const /*InnerView*/> &&
std::regular_invocable<const F&,
ranges::range_reference_t<const Views>...>;
```
| (2) | (since C++23) |
Returns an [iterator](iterator "cpp/ranges/zip transform view/iterator") or a [sentinel](sentinel "cpp/ranges/zip transform view/sentinel") that compares equal to the end iterator of the [`zip_transform_view`](../zip_transform_view "cpp/ranges/zip transform view").
Let `zip_` denote the underlying tuple of views:
1) Equivalent to:
`if constexpr ([ranges::common\_range](http://en.cppreference.com/w/cpp/ranges/common_range)</\*InnerView\*/>)
return /\*iterator\*/<false>(\*this, zip\_.end());
else
.
return /\*sentinel\*/<false>(zip_.end());`
2) Equivalent to:
`if constexpr ([ranges::common\_range](http://en.cppreference.com/w/cpp/ranges/common_range)<const /\*InnerView\*/>)
return /\*iterator\*/<true>(\*this, zip\_.end());
else
.
return /\*sentinel\*/<true>(zip_.end());`
### Parameters
(none).
### Return value
An iterator or sentinel representing the end of the `zip_transform_view`, as described above.
### Example
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/zip transform view/begin")
(C++23) | returns an iterator to the beginning (public member function) |
| [ranges::end](../end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
cpp std::ranges::zip_transform_view<F,Views...>::sentinel<Const>::sentinel
std::ranges::zip\_transform\_view<F,Views...>::*sentinel*<Const>::*sentinel*
============================================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++23) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const &&
std::convertible_to</*zentinel*/<false>, /*zentinel*/<Const>>;
```
| (2) | (since C++23) |
|
```
constexpr explicit /*sentinel*/( /*zentinel*/<Const> inner ); // exposition only
```
| (3) | (since C++23) |
Constructs a sentinel.
1) Default constructor. [Default-initializes](../../../language/default_initialization "cpp/language/default initialization") the underlying tuple of sentinels [`*inner\_*`](../sentinel#Data_members "cpp/ranges/zip transform view/sentinel").
2) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs the underlying object `*inner\_*` with `std::move(i.inner_)`.
3) [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying object `*inner\_*` with `inner`. This constructor is not accessible to users. ### Parameters
| | | |
| --- | --- | --- |
| i | - | a `/*sentinel*/<false>` |
| inner | - | an object of type [`*zentinel<Const>*`](../sentinel#Data_members "cpp/ranges/zip transform view/sentinel") |
### Example
cpp operator-(ranges::zip_transform_view::sentinel)
operator-(ranges::zip\_transform\_view::*sentinel*)
===================================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires std::sized_sentinel_for</*zentinel*/<Const>, /*ziperator*/<OtherConst>>
friend constexpr ranges::range_difference_t</*maybe-const*/<OtherConst, /*InnerView*/>>
operator-( const /*iterator*/<OtherConst>& x, const /*sentinel*/& y );
```
| (1) | (since C++23) |
|
```
template< bool OtherConst >
requires std::sized_sentinel_for</*zentinel*/<Const>, /*ziperator*/<OtherConst>>
friend constexpr ranges::range_difference_t</*maybe-const*/<OtherConst, /*InnerView*/>>
operator-( const /*sentinel*/& y, const /*iterator*/<OtherConst>& x );
```
| (2) | (since C++23) |
Computes the distance between the underlying iterator of `x` and the underlying sentinel of `y`.
These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_transform_view::*sentinel*` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x | - | an [iterator](../iterator "cpp/ranges/zip transform view/iterator") |
| y | - | a [sentinel](../sentinel "cpp/ranges/zip transform view/sentinel") |
### Return value
Let `*inner\_*` denote the underlying iterator or sentinel respectively.
1) `x.inner_ - y.inner_`
2) `y.inner_ - x.inner_`
cpp operator==(ranges::zip_transform_view::sentinel) operator==(ranges::zip\_transform\_view::*sentinel*)
====================================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires std::sentinel_for</*zentinel*/<Const>, /*ziperator*/<OtherConst>>
friend constexpr bool operator==( const /*iterator*/<OtherConst>& x,
const /*sentinel*/& y );
```
| | (since C++23) |
Compares the underlying iterator of `x` with the underlying sentinel of `y`.
This function template is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_transform_view::*sentinel*` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../../zip_transform_view#Nested_classes "cpp/ranges/zip transform view") to compare |
| y | - | [sentinel](../../zip_transform_view#Nested_classes "cpp/ranges/zip transform view") to compare |
### Return value
`x.inner_ == y.inner_`, where `*inner\_*` denotes the underlying iterator or sentinel respectively.
### Example
cpp std::ranges::zip_transform_view<F,Views...>::iterator<Const>::operator[] std::ranges::zip\_transform\_view<F,Views...>::*iterator*<Const>::operator[]
============================================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator[]( difference_type n ) const
requires ranges::random_access_range<Base>;
```
| | (since C++23) |
Returns the element at specified relative location, after transformation.
Equivalent to.
```
return
std::apply
(
[&]<class... Is>(const Is&... iters) -> decltype(auto)
{
return std::invoke(*parent_->fun_, iters[std::iter_difference_t<Is>(n)]...);
},
inner_.current_
);
```
where `*parent_->fun_` is the transformation function of type `F` stored in the parent `ranges::zip_transform_view`, and `*current\_*` is the underlying tuple of iterators into `Views...`.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location. |
### Return value
The element which is the result of transformation (mapping).
### Notes
The behavior is undefined if the `*parent\_*` pointer to parent `ranges::zip_transform_view` is null (e.g. if `*this` is default constructed).
### Example
cpp std::ranges::zip_transform_view<F,Views...>::iterator<Const>::operator* std::ranges::zip\_transform\_view<F,Views...>::*iterator*<Const>::operator\*
============================================================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*() const
noexcept(/* see description */);
```
| | (since C++23) |
Returns the transformed element obtained by application of the invocable object of type `F` to the underlying poined-to elements.
Equivalent to.
```
return
std::apply
(
[&](auto const&... iters) -> decltype(auto)
{
return std::invoke(*parent_->fun_, *iters...);
},
inner_.current_
);
```
where `*parent_->fun_` is the transformation function stored in the parent `ranges::zip_transform_view`, and `*current\_*` is the underlying tuple of iterators into `Views...`.
### Parameters
(none).
### Return value
The element which is the result of transformation (mapping).
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(\*parent_->fun_, \*[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<INTS>(inner_.current\_)...))`
where `*INTS*` is the pack of integers `0, 1, ..., (sizeof...(Views)-1)`. ### Notes
`operator->` is not provided.
The behavior is undefined if the `*parent\_*` pointer to parent `ranges::zip_transform_view` is null (e.g. if `*this` is default constructed).
### Example
cpp std::ranges::zip_transform_view<F,Views...>::iterator<Const>::iterator
std::ranges::zip\_transform\_view<F,Views...>::*iterator*<Const>::*iterator*
============================================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/iterator() = default;
```
| (1) | (since C++23) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i )
requires Const &&
std::convertible_to</*ziperator*/<false>, /*ziperator*/<Const>>;
```
| (2) | (since C++23) |
|
```
// exposition only
constexpr /*iterator*/( Parent& parent, /*ziperator*/<Const> inner );
```
| (3) | (since C++23) |
Construct an iterator.
1) Default constructor. [Default-initializes](../../../language/default_initialization "cpp/language/default initialization") the underlying iterators, and [value-initializes](../../../language/value_initialization "cpp/language/value initialization") the pointer to parent `ranges::zip_transform_view` with `nullptr`.
2) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Move constructs the underlying pointer to parent `*parent\_*` with `i.parent_` and `*inner\_*` with `std::move(i.inner_)`.
3) Initializes the pointer to parent `*parent\_*` with `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(parent)`, and the underlying `*inner\_*` iterator with `std::move(inner)`. This constructor is not accessible to users. ### Parameters
| | | |
| --- | --- | --- |
| i | - | an `/*iterator*/<false>` |
| parent | - | a (possibly const-qualified) `ranges::zip_transform_view` |
| inner | - | an iterator of type [`*ziperator*<Const>`](../../zip_transform_view#Member_types "cpp/ranges/zip transform view") |
### Example
cpp std::ranges::zip_transform_view<F,Views...>::iterator<Const>::operator++,--,+=,-= std::ranges::zip\_transform\_view<F,Views...>::*iterator*<Const>::operator++,--,+=,-=
=====================================================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++23) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++23) |
|
```
constexpr /*iterator*/ operator++( int )
requires ranges::forward_range<Base>;
```
| (3) | (since C++23) |
|
```
constexpr /*iterator*/& operator--()
requires ranges::bidirectional_range<Base>;
```
| (4) | (since C++23) |
|
```
constexpr /*iterator*/ operator--( int )
requires ranges::bidirectional_range<Base>;
```
| (5) | (since C++23) |
|
```
constexpr /*iterator*/& operator+=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (6) | (since C++23) |
|
```
constexpr /*iterator*/& operator-=( difference_type n )
requires ranges::random_access_range<Base>;
```
| (7) | (since C++23) |
Increments or decrements the underlying [`*inner\_*`](../iterator#Data_members "cpp/ranges/zip transform view/iterator") iterator.
Equivalent to:
1) `++inner_; return *this;`
2) `++*this;`
3) `auto tmp = *this; ++*this; return tmp;`
4) `--inner_; return *this;`
5) `auto tmp = *this; --*this; return tmp;`
6) `inner_ += n; return *this;`
7) `inner_ -= n; return *this;`
[`*Base*`](../iterator#Member_types "cpp/ranges/zip transform view/iterator") is exposition-only member-type of the [`iterator`](../iterator "cpp/ranges/zip transform view/iterator") class template.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
1,4,6,7) `*this`
2) (none)
3,5) a copy of `*this` that was made before the change ### Example
| programming_docs |
cpp operator==,<,>,<=,>=,<=>(ranges::zip_transform_view::iterator) operator==,<,>,<=,>=,<=>(ranges::zip\_transform\_view::*iterator*)
==================================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires std::equality_comparable</*ziperator*/<Const>>;
```
| (1) | (since C++23) |
|
```
friend constexpr bool operator<(const /*iterator*/& x, const /*iterator*/& y)
requires ranges::random_access_range<Base>;
```
| (2) | (since C++23) |
|
```
friend constexpr bool operator>(const /*iterator*/& x, const /*iterator*/& y)
requires ranges::random_access_range<Base>;
```
| (3) | (since C++23) |
|
```
friend constexpr bool operator<=(const /*iterator*/& x, const /*iterator*/& y)
requires ranges::random_access_range<Base>;
```
| (4) | (since C++23) |
|
```
friend constexpr bool operator>=(const /*iterator*/& x, const /*iterator*/& y)
requires ranges::random_access_range<Base>;
```
| (5) | (since C++23) |
|
```
friend constexpr auto operator<=>(const /*iterator*/& x, const /*iterator*/& y)
requires ranges::random_access_range<Base> &&
std::three_way_comparable</*ziperator*/<Const>>;
```
| (6) | (since C++23) |
Compares the underlying iterators. Let [`*inner\_*`](../iterator#Data_members "cpp/ranges/zip transform view/iterator") denote the underlying iterator.
Equivalent to:
1) `return x.inner_ == y.inner_;`
2) `return x.inner_ < y.inner_;`
3) `return x.inner_ > y.inner_;`
4) `return x.inner_ <= y.inner_;`
5) `return x.inner_ >= y.inner_;`
6) `return x.inner_ <=> y.inner_;`
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::zip_transform_view::*iterator*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
The result of comparison.
cpp std::ranges::take_while_view<V,Pred>::take_while_view std::ranges::take\_while\_view<V,Pred>::take\_while\_view
=========================================================
| | | |
| --- | --- | --- |
|
```
take_while_view() requires std::default_initializable<V> &&
std::default_initializable<Pred> = default;
```
| (1) | (since C++20) |
|
```
constexpr take_while_view( V base, Pred pred );
```
| (2) | (since C++20) |
Constructs a `take_while_view`.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying view and the predicate.
2) Move constructs the underlying view from `base` and the predicate from `pred`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | underlying view |
| fun | - | predicate |
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | if `Pred` is not [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable"), the default constructorconstructs a `take_while_view` which does not contain an `Pred` | the `take_while_view` is alsonot [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") |
cpp deduction guides for std::ranges::take_while_view
deduction guides for `std::ranges::take_while_view`
===================================================
| Defined in header `[<ranges>](../../header/ranges "cpp/header/ranges")` | | |
| --- | --- | --- |
|
```
template< class R, class Pred >
take_while_view( R&&, Pred ) -> take_while_view<views::all_t<R>, Pred>;
```
| | (since C++20) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::ranges::take\_while\_view](../take_while_view "cpp/ranges/take while view")` to allow deduction from [`range`](../range "cpp/ranges/range") and predicate.
If `R` is a [`view`](../view "cpp/ranges/view"), the deduced type is `take_while_view<R>`; otherwise, the deduced type is usually `take_while_view<[ranges::ref\_view](http://en.cppreference.com/w/cpp/ranges/ref_view)<R>>`.
### Example
cpp std::ranges::take_while_view<V,Pred>::sentinel
std::ranges::take\_while\_view<V,Pred>::*sentinel*
==================================================
| | | |
| --- | --- | --- |
|
```
template<bool Const>
class /*sentinel*/; // exposition only
```
| | (since C++20) |
The return type of [`take_while_view::end`](end "cpp/ranges/take while view/end").
The type `/*sentinel*/<true>` is returned by the const-qualified overload. The type `/*sentinel*/<false>` is returned by the non-const-qualified overload.
The name of this class template (shown here as `*sentinel*`) is unspecified.
Typical implementation holds two data members: a sentinel that represents the end of the underlying view, and a pointer to the predicate.
### Member types
| Member type | Definition |
| --- | --- |
| `*Base*`(private) | `const V` if `Const` is `true`, otherwise `V`. The name is for exposition only |
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/take while view/sentinel/sentinel")
(C++20) | constructs a sentinel (public member function) |
| [base](sentinel/base "cpp/ranges/take while view/sentinel/base")
(C++20) | returns the underlying sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/take while view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`take_while_view::begin`](begin "cpp/ranges/take while view/begin") (function) |
cpp std::ranges::take_while_view<V,Pred>::base std::ranges::take\_while\_view<V,Pred>::base
============================================
| | | |
| --- | --- | --- |
|
```
constexpr V base() const& requires std::copy_constructible<V>;
```
| (1) | (since C++20) |
|
```
constexpr V base() &&;
```
| (2) | (since C++20) |
Returns a copy of the underlying view.
1) Copy constructs the result from the underlying view.
2) Move constructs the result from the underlying view. ### Parameters
(none).
### Return value
A copy of the underlying view.
### Example
cpp std::ranges::take_while_view<V,Pred>::begin std::ranges::take\_while\_view<V,Pred>::begin
=============================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto begin() const requires
ranges::range<const V> &&
std::indirect_unary_predicate<const Pred, ranges::iterator_t<const V>>;
```
| (2) | (since C++20) |
Returns an iterator to the first element of the view. Effectively calls `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)` on the underlying view.
Overload (1) does not participate in overload resolution if `V` is a [simple view](../../ranges#Helper_concepts "cpp/ranges") (that is, if `V` and `const V` are views with the same iterator and sentinel types).
### Parameters
(none).
### Return value
`[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(base_)`, where `*base\_*` is the underlying view.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3450](https://cplusplus.github.io/LWG/issue3450) | C++20 | the `const` overload might return an iterator non-comparable to the sentinel | constrained |
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/take while view/end")
(C++20) | returns a sentinel representing the end (public member function) |
| [operator==](sentinel/operator_cmp "cpp/ranges/take while view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from **`take_while_view::begin`** (function) |
cpp std::ranges::take_while_view<V,Pred>::pred std::ranges::take\_while\_view<V,Pred>::pred
============================================
| | | |
| --- | --- | --- |
|
```
constexpr const Pred& pred() const;
```
| | (since C++20) |
Returns a reference to the stored predicate.
If `*this` does not store a predicate (e.g. an exception is thrown on the assignment to `*this`, which copy-constructs or move-constructs a `Pred`), the behavior is undefined.
### Parameters
(none).
### Return value
a reference to the stored predicate.
### Example
cpp std::ranges::take_while_view<V,Pred>::end std::ranges::take\_while\_view<V,Pred>::end
===========================================
| | | |
| --- | --- | --- |
|
```
constexpr auto end() requires (!__SimpleView<V>);
```
| (1) | (since C++20) |
|
```
constexpr auto end() const requires
ranges::range<const V> &&
std::indirect_unary_predicate<const Pred, ranges::iterator_t<const V>>;
```
| (2) | (since C++20) |
Returns a [sentinel](sentinel "cpp/ranges/take while view/sentinel") representing the end of the view.
1) Effectively returns `/\*sentinel\*/<false>([ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_), [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(pred()))`, where `*base\_*` denotes the underlying view.
2) Effectively returns `/\*sentinel\*/<true>([ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(base_), [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(pred()))`, where `*base\_*` denotes the underlying view. Overload (1) does not participate in overload resolution if `V` is a [simple view](../../ranges#Helper_concepts "cpp/ranges") (that is, if `V` and `const V` are views with the same iterator and sentinel types).
### Parameters
(none).
### Return value
[sentinel](sentinel "cpp/ranges/take while view/sentinel") representing the end of the view.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3450](https://cplusplus.github.io/LWG/issue3450) | C++20 | the `const` overload might return a sentinel non-comparable to the iterator | constrained |
### See also
| | |
| --- | --- |
| [begin](begin "cpp/ranges/take while view/begin")
(C++20) | returns an iterator to the beginning (public member function) |
| [operator==](sentinel/operator_cmp "cpp/ranges/take while view/sentinel/operator cmp")
(C++20) | compares a sentinel with an iterator returned from [`take_while_view::begin`](begin "cpp/ranges/take while view/begin") (function) |
cpp std::ranges::take_while_view<V,Pred>::sentinel<Const>::sentinel
std::ranges::take\_while\_view<V,Pred>::*sentinel*<Const>::*sentinel*
=====================================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++20) |
|
```
constexpr explicit /*sentinel*/( ranges::sentinel_t<Base> end, const Pred* pred );
```
| (2) | (since C++20) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> s )
requires Const &&
std::convertible_to<ranges::sentinel_t<V>, ranges::sentinel_t<Base>>;
```
| (3) | (since C++20) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying sentinel and the pointer to predicate.
2) Initializes the underlying sentinel with `end` and the pointer to predicate with `pred`.
3) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Copy constructs corresponding members. ### Parameters
| | | |
| --- | --- | --- |
| end | - | a sentinel representing the end of (possibly const-qualified) `V` |
| pred | - | a pointer to predicate |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp std::ranges::take_while_view<V,Pred>::sentinel<Const>::base std::ranges::take\_while\_view<V,Pred>::*sentinel*<Const>::base
===============================================================
| | | |
| --- | --- | --- |
|
```
constexpr ranges::sentinel_t<Base> base() const;
```
| | (since C++20) |
Returns the underlying sentinel.
### Parameters
(none).
### Return value
a copy of the underlying sentinel.
### Example
cpp operator==(ranges::take_while_view::sentinel)
operator==(ranges::take\_while\_view::*sentinel*)
=================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const ranges::iterator_t<Base>& x,
const /*sentinel*/& y );
```
| | (since C++20) |
Compares a `take_while_view::/*sentinel*/` with an iterator into (possibly const-qualified) view `V`. The iterator is typically obtained from a call to [`take_while_view::begin`](../begin "cpp/ranges/take while view/begin").
Returns `true` if `x` compares equal to the underlying sentinel of `y` (i.e. [`y.base()`](base "cpp/ranges/take while view/sentinel/base")), or if the predicate returns `false` when applied to `*x`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `take_while_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | iterator to compare |
| y | - | sentinel to compare |
### Return value
`y.end\_ == x || (\*y.pred\_, \*x)`, where `*end\_*` denotes the stored sentinel and `*pred\_*` denotes the stored pointer to predicate.
### Example
cpp std::ranges::zip_view<Views...>::size std::ranges::zip\_view<Views...>::size
======================================
| | | |
| --- | --- | --- |
|
```
constexpr auto size()
requires (ranges::sized_range<Views> && ...);
```
| (1) | (since C++23) |
|
```
constexpr auto size() const
requires (ranges::sized_range<const Views> && ...);
```
| (2) | (since C++23) |
Returns the number of elements in the [`zip_view`](../zip_view "cpp/ranges/zip view"). Provided only if each underlying (adapted) range satisfies [`sized_range`](../sized_range "cpp/ranges/sized range").
Equivalent to:
```
return std::apply(
[](auto... sizes) {
using CT = /*make-unsigned-like-t*/<std::common_type_t<decltype(sizes)...>>;
return ranges::min({CT(sizes)...});
},
/*tuple-transform*/(ranges::size, views_)
);
```
### Parameters
(none).
### Return value
The number of elements, which is the minimum size among all sizes of adapted [`view`s](../view "cpp/ranges/view").
### Example
Can be tested on [Compiler Explorer site](https://godbolt.org/z/8bM3GeK6d).
```
#include <algorithm>
#include <cassert>
#include <deque>
#include <forward_list>
#include <ranges>
#include <vector>
int main()
{
auto x = std::vector{1, 2, 3, 4, 5};
auto y = std::deque{'a', 'b', 'c'};
auto z = std::forward_list{1., 2.};
auto v1 = std::views::zip(x, y);
assert(v1.size() == std::min(x.size(), y.size()));
assert(v1.size() == 3);
[[maybe_unused]] auto v2 = std::views::zip(x, z);
// auto sz = v2.size(); // Error, v2 does not have size():
static_assert(not std::ranges::sized_range<decltype(z)>);
}
```
### See also
| | |
| --- | --- |
| [ranges::size](../size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp deduction guides for std::ranges::zip_view
deduction guides for `std::ranges::zip_view`
============================================
| | | |
| --- | --- | --- |
|
```
template< class... Rs >
zip_view( Rs&&... ) -> zip_view<views::all_t<Rs>...>;
```
| | (since C++23) |
The [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `std::ranges::zip_view` to allow deduction from [`range`s](../range "cpp/ranges/range").
### Example
cpp std::ranges::zip_view<Views...>::sentinel
std::ranges::zip\_view<Views...>::*sentinel*
============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*sentinel*/; // exposition only
```
| | (since C++23) |
The return type of [`zip_view::end`](end "cpp/ranges/zip view/end") when the underlying view is not a [`common_range`](../common_range "cpp/ranges/common range"). The name of this class template (shown here as `*sentinel*`) is unspecified.
The type `/*sentinel*/<true>` or `/*sentinel*/<false>` treats the underlying view as const-qualified or non-const-qualified respectively.
### Data members
Typical implementation of `*sentinel*` holds only one non-static data member:
* `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Views>...>` if `Const` is `false`, or
* `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const Views>...>` if `Const` is `true`.
### Member functions
| | |
| --- | --- |
| [(constructor)](sentinel/sentinel "cpp/ranges/zip view/sentinel/sentinel")
(C++23) | constructs a sentinel (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](sentinel/operator_cmp "cpp/ranges/zip view/sentinel/operator cmp")
(C++23) | compares a sentinel with an iterator returned from [`zip_view::begin`](begin "cpp/ranges/zip view/begin") (function) |
| [operator-](sentinel/operator- "cpp/ranges/zip view/sentinel/operator-")
(C++23) | computes the distance between a sentinel and an iterator returned from [`zip_view::begin`](begin "cpp/ranges/zip view/begin") (function) |
cpp std::ranges::zip_view<Views...>::zip_view std::ranges::zip\_view<Views...>::zip\_view
===========================================
| | | |
| --- | --- | --- |
|
```
zip_view() = default;
```
| (1) | (since C++23) |
|
```
constexpr zip_view( Views... views );
```
| (2) | (since C++23) |
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") all adapted [`view`](../view "cpp/ranges/view") objects.
The default constructor is deleted if `[std::is\_default\_constructible\_v](../../types/is_default_constructible "cpp/types/is default constructible")` is `false` for at least one type in `Views...`.
2) Move constructs every adapted [`view`](../view "cpp/ranges/view") object from the corresponding view in `views...`. ### Parameters
| | | |
| --- | --- | --- |
| views | - | view objects to adapt |
### Example
| programming_docs |
cpp std::ranges::zip_view<Views...>::iterator
std::ranges::zip\_view<Views...>::*iterator*
============================================
| | | |
| --- | --- | --- |
|
```
template< bool Const >
class /*iterator*/; // exposition only
```
| (1) | (since C++23) |
| Helper concepts | | |
|
```
template< bool C, class... Views >
concept /*all-forward*/ = // exposition only
(ranges::forward_range<std::conditional_t<C, const Views, Views>> && ...);
```
| (2) | (since C++23) |
|
```
template< bool C, class... Views >
concept /*all-bidirectional*/ = // exposition only
(ranges::bidirectional_range<std::conditional_t<C, const Views, Views>> && ...);
```
| (3) | (since C++23) |
|
```
template< bool C, class... Views >
concept /*all-random-access*/ = // exposition only
(ranges::random_access_range<std::conditional_t<C, const Views, Views>> && ...);
```
| (4) | (since C++23) |
The iterator type of a possibly const-qualified `zip_view`, returned by [`zip_view::begin`](begin "cpp/ranges/zip view/begin") and in certain cases by [`zip_view::end`](end "cpp/ranges/zip view/end"). The name of this class template (shown here as `*iterator*`) is unspecified.
The type `/*iterator*/<true>` or `/*iterator*/<false>` treats the underlying views as const-qualified or non-const-qualified respectively.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_concept` | * `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `/*all-random-access*/<Const, Views...>` is `true`, otherwise
* `[std::bidirectional\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `/*all-bidirectional*/<Const, Views...>` is `true`, otherwise
* `[std::forward\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `/*all-forward*/<Const, Views...>` is `true`, otherwise
* `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")`
|
| `iterator_category` | * `[std::input\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` if `/*all-forward*/<Const, Views...>` is `true`,
* not defined otherwise
|
| `value_type` | If `sizeof...(Views)` is equal to 2: * `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Views>...>` if `Const` is `false`,
* `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<const Views>...>` otherwise.
Otherwise,* `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Views>...>` if `Const` is `false`,
* `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<const Views>...>` otherwise.
|
| `difference_type` | * `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<Views>...>` if `Const` is `false`,
* `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<[ranges::range\_difference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<const Views>...>` otherwise.
|
### Data members
Typical implementations of `*iterator*` hold only one non-static data member: a `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<Views>...>` or `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<const Views>...>` when `Const` is `false` or `true` respectively.
For the purpose of exposition, the underlying iterators in that `[std::tuple](../../utility/tuple "cpp/utility/tuple")` are shown as `*is\_*...` here.
### Member functions
| | |
| --- | --- |
| [(constructor)](iterator/iterator "cpp/ranges/zip view/iterator/iterator")
(C++23) | constructs an iterator (public member function) |
| [operator\*](iterator/operator* "cpp/ranges/zip view/iterator/operator*")
(C++23) | obtains a tuple-like value that consists of underlying pointed-to elements (public member function) |
| [operator[]](iterator/operator_at "cpp/ranges/zip view/iterator/operator at")
(C++23) | obtains a tuple-like value that consists of underlying elements at given offset (public member function) |
| [operator++operator++(int) operator--operator--(int)operator+=operator-=](iterator/operator_arith "cpp/ranges/zip view/iterator/operator arith")
(C++23) | advances or decrements the underlying iterators (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<operator>operator<=operator>=operator<=>](iterator/operator_cmp "cpp/ranges/zip view/iterator/operator cmp")
(C++23) | compares the underlying iterators (function) |
| [operator+operator-](iterator/operator_arith2 "cpp/ranges/zip view/iterator/operator arith2")
(C++23) | performs iterator arithmetic on underlying iterators (function) |
| [iter\_move](iterator/iter_move "cpp/ranges/zip view/iterator/iter move")
(C++23) | obtains a tuple-like value that denotes underlying pointed-to elements to be moved (function) |
| [iter\_swap](iterator/iter_swap "cpp/ranges/zip view/iterator/iter swap")
(C++23) | swaps underlying pointed-to elements (function) |
cpp std::ranges::zip_view<Views...>::begin std::ranges::zip\_view<Views...>::begin
=======================================
| | | |
| --- | --- | --- |
|
```
constexpr auto begin()
requires (!(/*simple-view*/<Views> && ...));
```
| (1) | (since C++23) |
|
```
constexpr auto begin() const
requires (ranges::range<const Views> && ...);
```
| (2) | (since C++23) |
Obtains the beginning iterator of `zip_view`.
1) Equivalent to `return /\*iterator\*/<false>(/\*tuple-transform\*/([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin), views_));`.
2) Equivalent to `return /\*iterator\*/<true>(/\*tuple-transform\*/([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin), views_));`. ### Parameters
(none).
### Return value
[Iterator](iterator "cpp/ranges/zip view/iterator") to the first element.
### Notes
`[ranges::range](http://en.cppreference.com/w/cpp/ranges/range)<const ranges::zip\_view<Views...>>` is modeled if and only if for every type `Vi` in `Views...`, `const Vi` models [`range`](../range "cpp/ranges/range").
### Example
### See also
| | |
| --- | --- |
| [end](end "cpp/ranges/zip view/end")
(C++23) | returns an iterator or a sentinel to the end (public member function) |
| [ranges::begin](../begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
cpp std::ranges::zip_view<Views...>::sentinel<Const>::sentinel
std::ranges::zip\_view<Views...>::*sentinel*<Const>::*sentinel*
===============================================================
| | | |
| --- | --- | --- |
|
```
/*sentinel*/() = default;
```
| (1) | (since C++23) |
|
```
constexpr /*sentinel*/( /*sentinel*/<!Const> i )
requires Const &&
(std::convertible_to<
ranges::sentinel_t<Views>,
ranges::sentinel_t</*maybe-const*/<Const, Views>>> && ...);
```
| (2) | (since C++23) |
Constructs a sentinel.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying tuple of sentinels `*end\_*`.
2) Conversion from `/*sentinel*/<false>` to `/*sentinel*/<true>`. Move constructs the underlying tuple of sentinels `*end\_*` with `std::move(i.end_)`. The name `*sentinel*` is for exposition purposes only.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a `/*sentinel*/<false>` |
### Example
cpp operator-(ranges::zip_view::sentinel) operator-(ranges::zip\_view::*sentinel*)
========================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires (std::sized_sentinel_for<
ranges::sentinel_t</*maybe-const*/<Const, Views>>,
ranges::iterator_t</*maybe-const*/<OtherConst, Views>>> && ...)
friend constexpr
std::common_type_t<ranges::range_difference_t</*maybe-const*/<OtherConst, Views>>...>
operator-( const iterator<OtherConst>& x, const sentinel& y );
```
| (1) | (since C++23) |
|
```
template< bool OtherConst >
requires (std::sized_sentinel_for<
ranges::sentinel_t</*maybe-const*/<Const, Views>>,
ranges::iterator_t</*maybe-const*/<OtherConst, Views>>> && ...)
friend constexpr
std::common_type_t<ranges::range_difference_t</*maybe-const*/<OtherConst, Views>>...>
operator-( const sentinel& y, const iterator<OtherConst>& x );
```
| (2) | (since C++23) |
Computes the minimal distance between the underlying tuple of iterators of `x` and the underlying tuple of sentinels of `y`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_view::*sentinel*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x | - | an [iterator](../iterator "cpp/ranges/zip view/iterator") |
| y | - | a [sentinel](../sentinel "cpp/ranges/zip view/sentinel") |
### Return value
Let `*current\_*` denote the underlying tuple of iterators of `x`, and `*end\_*` denote the underlying tuple of sentinels of `y`.
Let `*DIST*(x, y, i)` be a distance calculated by expression equivalent to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.current\_) - [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(y.end\_)` for some integer `i`.
1) the value with the smallest absolute value among `*DIST*(x, y, i)` of all `i` in range `0 ≤ i < sizeof...(Views)`
2) `-(x - y)`. ### Example
```
#include <cassert>
#include <ranges>
#include <vector>
#include <deque>
#include <list>
int main() {
auto x = std::vector{1, 2, 3, 4};
auto y = std::deque{'a', 'b', 'c'};
auto z = {1.1, 2.2};
auto w = std::list{1, 2, 3};
auto p = std::views::zip(x, y, z);
assert(p.begin() - p.end() == +2);
assert(p.end() - p.begin() == -2);
[[maybe_unused]]
auto q = std::views::zip(x, y, w);
// The following code fires a compile-time error because std::list::iterator
// does not support operator- that is needed to calculate the distance:
// auto e = q.begin() - q.end();
}
```
cpp operator==(ranges::zip_view::iterator, ranges::zip_view::sentinel) operator==(ranges::zip\_view::*iterator*, ranges::zip\_view::*sentinel*)
========================================================================
| | | |
| --- | --- | --- |
|
```
template< bool OtherConst >
requires (std::sentinel_for<
ranges::sentinel_t</*maybe-const*/<Const, Views>>,
ranges::iterator_t</*maybe-const*/<OtherConst, Views>>> && ...)
friend constexpr bool operator==( const /*iterator*/<OtherConst>& x,
const /*sentinel*/& y );
```
| | (since C++23) |
Compares the underlying tuple of iterators of `x` with the underlying tuple of sentinels of `y`.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_view::*sentinel*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | [iterator](../iterator "cpp/ranges/zip view/iterator") to compare |
| y | - | [sentinel](../sentinel "cpp/ranges/zip view/sentinel") to compare |
### Return value
Let `x.current_` denote the underlying tuple of iterators, and `y.end_` denote the underlying tuple of sentinels.
Returns.
* `true` if at least one underlying iterator, obtained by expression equivalent to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.current\_)`, evaluates equal (using an appropriate `operator==`) to some underlying sentinel, obtained by expression equivalent to `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(y.end\_)`, for some index `i` in ranges `0 <= i < sizeof...(Views)`,
* `false` otherwise.
### Example
cpp iter_move(ranges::zip_view::iterator) iter\_move(ranges::zip\_view::*iterator*)
=========================================
| | | |
| --- | --- | --- |
|
```
friend constexpr auto iter_move( const iterator& i ) noexcept(/* see below */);
```
| | (since C++23) |
Equivalent to: `return /\*tuple-transform\*/([ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move), i.current\_);`, where `*current\_*` denotes the underlying tuple-like object that holds iterators to elements of adapted views.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator |
### Return value
`std::move(*i)` if `*i` is an lvalue reference, otherwise `*i`.
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(
(
noexcept(
[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(declval<const [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)</\*maybe-const\*/<Const, Views>>&>())
) && ...
)
&&
(
[std::is\_nothrow\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<
[ranges::range\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)</\*maybe-const\*/<Const, Views>>
> && ...
)
.
)`
cpp std::ranges::zip_view<Views...>::iterator<Const>::operator[] std::ranges::zip\_view<Views...>::*iterator*<Const>::operator[]
===============================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto operator[]( difference_type n ) const
requires /*all-random-access*/<Const, Views...>;
```
| | (since C++23) |
Obtains a tuple-like value (that is a `[std::pair](../../../utility/pair "cpp/utility/pair")` or `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, depending on the number of adapted views) that consists of underlying pointed-to elements at given offset relative to current location.
Equivalent to:
```
return /*tuple-transform*/([&]<class I>(I& i) -> decltype(auto) {
return i[iter_difference_t<I>(n)];
}, current_);
```
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
The obtained tuple-like element.
### Example
cpp std::ranges::zip_view<Views...>::iterator<Const>::operator* std::ranges::zip\_view<Views...>::*iterator*<Const>::operator\*
===============================================================
| | | |
| --- | --- | --- |
|
```
constexpr auto operator*() const;
```
| | (since C++23) |
Returns a tuple-like value (that is a `[std::pair](../../../utility/pair "cpp/utility/pair")` or `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, depending on the number of adapted views) that consists of underlying pointed-to elements.
Let `*current\_*` denote the underlying tuple-like object that holds iterators to elements of adapted views. Equivalent to:
```
return /*tuple-transform*/([](auto& i) -> decltype(auto) { return *i; }, current_);
```
### Parameters
(none).
### Return value
The current tuple-like element.
### Notes
`operator->` is not provided.
### Example
cpp std::ranges::zip_view<Views...>::iterator<Const>::iterator
std::ranges::zip\_view<Views...>::*iterator*<Const>::*iterator*
===============================================================
| | | |
| --- | --- | --- |
|
```
/*iterator*/() = default;
```
| (1) | (since C++23) |
|
```
constexpr /*iterator*/( /*iterator*/<!Const> i )
requires Const &&
(std::convertible_to<ranges::iterator_t<Views>,
ranges::iterator_t</*maybe-const*/<Const, Views>>> && ...);
```
| (2) | (since C++23) |
Construct an iterator.
1) Default constructor. [Value-initializes](../../../language/value_initialization "cpp/language/value initialization") the underlying tuple of iterators to their default values.
2) Conversion from `/*iterator*/<false>` to `/*iterator*/<true>`. Move constructs the underlying tuple of iterators `*current\_*` with `std::move(i.current)`. This iterator also has a private constructor which is used by `zip_view::begin` and `zip_view::end`. This constructor is not accessible to users.
### Parameters
| | | |
| --- | --- | --- |
| i | - | an `/*iterator*/<false>` |
### Example
cpp std::ranges::zip_view<Views...>::iterator<Const>::operator++,--,+=,-= std::ranges::zip\_view<Views...>::*iterator*<Const>::operator++,--,+=,-=
========================================================================
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++23) |
|
```
constexpr void operator++( int );
```
| (2) | (since C++23) |
|
```
constexpr /*iterator*/ operator++( int )
requires requires /*all-forward*/<Const, Views...>;
```
| (3) | (since C++23) |
|
```
constexpr /*iterator*/& operator--()
requires /*all-bidirectional*/<Const, Views...>;
```
| (4) | (since C++23) |
|
```
constexpr /*iterator*/ operator--( int )
requires /*all-bidirectional*/<Const, Views...>;
```
| (5) | (since C++23) |
|
```
constexpr /*iterator*/& operator+=( difference_type n )
requires /*all-random-access*/<Const, Views...>;
```
| (6) | (since C++23) |
|
```
constexpr /*iterator*/& operator-=( difference_type n )
requires /*all-random-access*/<Const, Views...>;
```
| (7) | (since C++23) |
Increments or decrements each of the underlying `*is\_...*` iterators in the underlying tuple-like object `*current\_*`.
1) Equivalent to `/*tuple-for-each*/([](auto& i) { ++i; }, current_); return *this;`
2) Equivalent to `++*this;`
3) Equivalent to `auto tmp = *this; ++*this; return tmp;`
4) Equivalent to `/*tuple-for-each*/([](auto& i) { --i; }, current_); return *this;`
5) Equivalent to `auto tmp = *this; --*this; return tmp;`
6) Equivalent to `/*tuple-for-each*/([&]<class I>(I& i) { i += iter_difference_t<I>(x); }, current_); return *this;`
7) Equivalent to `/*tuple-for-each*/([&]<class I>(I& i) { i -= iter_difference_t<I>(x); }, current_); return *this;`
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
1,4,6,7) `*this`
2) (none)
3,5) a copy of `*this` that was made before the change ### Example
cpp iter_swap(ranges::zip_view::iterator) iter\_swap(ranges::zip\_view::*iterator*)
=========================================
| | | |
| --- | --- | --- |
|
```
friend constexpr void iter_swap( const /*iterator*/& x, const /*iterator*/& y )
noexcept(/* see below */)
requires (std::indirectly_swappable<ranges::iterator_t<
/*maybe-const*/<Const, Views>>> && ...);
```
| | (since C++23) |
Performs `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.current\_), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(y.current\_))` for every integer `i` in `[0, sizeof...(Views))`, where `*current\_*` denotes the underlying tuple-like object that holds iterators to elements of adapted views.
This function is not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `zip_view::*iterator*<Const>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to the elements to swap |
### Return value
(none).
### Exceptions
[`noexcept`](../../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(
(noexcept([ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(
declval<const [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)</\*maybe-const\*/<Const, Views>>&>(),
declval.
<const [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)</\*maybe-const\*/<Const, Views>>&>())) &&...))`
| programming_docs |
cpp operator==,<,>,<=,>=,<=>(ranges::zip_view::iterator) operator==,<,>,<=,>=,<=>(ranges::zip\_view::*iterator*)
=======================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y )
requires (std::equality_comparable<
ranges::iterator_t</*maybe-const*/<Const, Views>>> && ...);
```
| (1) | (since C++23) |
|
```
friend constexpr bool operator<( const /*iterator*/& x, const /*iterator*/& y )
requires /*all-random-access*/<Const, Views...>;
```
| (2) | (since C++23) |
|
```
friend constexpr bool operator>( const /*iterator*/& x, const /*iterator*/& y )
requires /*all-random-access*/<Const, Views...>;
```
| (3) | (since C++23) |
|
```
friend constexpr bool operator<=( const /*iterator*/& x, const /*iterator*/& y )
requires /*all-random-access*/<Const, Views...>;
```
| (4) | (since C++23) |
|
```
friend constexpr bool operator>=( const /*iterator*/& x, const /*iterator*/& y )
requires /*all-random-access*/<Const, Views...>;
```
| (5) | (since C++23) |
|
```
friend constexpr auto operator<=>( const /*iterator*/& x, const /*iterator*/& y )
requires ranges::random_access_range<Base> &&
std::three_way_comparable<ranges::iterator_t<Base>>;
```
| (6) | (since C++23) |
Compares the underlying iterators.
Let `*current\_*` be the underlying *tuple-like* object of iterators to elements of adapted views.
1) Returns: * `x.current_ == y.current_` if `/*all-bidirectional*/<Const, Views...>` is true.
* Otherwise, `true` if there exists an integer `0 <= i < sizeof...(Views)` such that `bool([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.current\_) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(y.current\_))` is true.
* Otherwise, `false`.
2) Equivalent to `return x.current_ < y.current_;`.
3) Equivalent to `return y < x;`
4) Equivalent to `return !(y < x);`
5) Equivalent to `return !(x < y);`
6) Equivalent to `return x.current_ <=> y.current_;`. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::ranges::zip_view::*iterator*<Const>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterators to compare |
### Return value
The result of comparison.
### Notes
`zip_view` models [`common_range`](../../common_range "cpp/ranges/common range") if all adapted views `*vs\_...*` model [`common_range`](../../common_range "cpp/ranges/common range").
cpp std::ranges::repeat_view<W, Bound>::iterator
std::ranges::repeat\_view<W, Bound>::*iterator*
===============================================
| | | |
| --- | --- | --- |
|
```
struct /*iterator*/;
```
| (1) | (since C++23) |
| Helper alias templates | | |
|
```
template< class I >
using /*iota-diff-t*/ = /* see below */; // exposition only
```
| (2) | (since C++20) |
1) The return type of [`repeat_view::begin`](../repeat_view "cpp/ranges/repeat view"). The name of this class (shown here as `/*iterator*/`) is unspecified. 2) The exposition-only alias template `*iota-diff-t*` calculates the difference type for both iterator types and [integer-like types](../../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable"). * If `W` is not an integral type, or if it is an integral type and `sizeof([std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>)` is greater than `sizeof(I)`, then `/*iota-diff-t*/<I>` is `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>`.
* Otherwise, `/*iota-diff-t*/<I>` is a signed integer type of width greater than the width of `I` if such a type exists.
* Otherwise, `I` is one of the widest integral types, and `/*iota-diff-t*/<I>` is an unspecified [signed-integer-like type](../../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable") of width not less than the width of `I`. It is unspecified whether `/*iota-diff-t*/<I>` models [`weakly_incrementable`](../../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") in this case.
### Member types
| Member type | Definition |
| --- | --- |
| `*index-type*` (private) | * `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`, if `Bound` is the same as `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")`. Otherwise,
* `Bound`.
The name is for exposition only. |
| `iterator_concept` | `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` |
| `iterator_category` | `[std::random\_access\_iterator\_tag](../../iterator/iterator_tags "cpp/iterator/iterator tags")` |
| `value_type` | `W` |
| `difference_type` | * `/*index-type*/`, if `/*is-signed-like*/</*index-type*/>` is `true`,
* `/*iota-diff-t*/(/*index-type*/)` otherwise.
|
### Data members
Typical implementation of this iterator type contains two data members:
* `*value\_*` of type `const W*` that holds the pointer to the value to repeat;
* `*current\_*` of type `/*index-type*/` that holds the current position.
These names are exposition only.
### Member functions
std::ranges::repeat\_view::*iterator*::*iterator*
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
/*iterator*/() = default;
```
| (1) | (since C++23) |
|
```
constexpr explicit /*iterator*/( // exposition only
const W* value, /*index-type*/ b = /*index-type*/() );
```
| (2) | (since C++23) |
1) Value initializes the exposition-only data members: * `*value\_*` with `nullptr_t` via its default member initializer;
* `*index\_*` via its default member initializer (`= /*index-type*/()`).
2) Value initializes `*value\_*` with `value` and `*bound\_*` with `b`. If `Bound` is not `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")` then `b` must be non-negative. This constructor is not a part of the public interface.
std::ranges::repeat\_view::*iterator*::operator\*
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr const W& operator*() const noexcept;
```
| | (since C++23) |
Equivalent to `return *value_;`.
std::ranges::repeat\_view::*iterator*::operator++
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator++();
```
| (1) | (since C++23) |
|
```
constexpr void operator++(int);
```
| (2) | (since C++23) |
1) Equivalent to `++current_; return *this;`.
2) Equivalent to `auto tmp = *this; ++*this; return tmp;`.
std::ranges::repeat\_view::*iterator*::operator--
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator--();
```
| (1) | (since C++23) |
|
```
constexpr /*iterator*/ operator--(int);
```
| (2) | (since C++23) |
1) Equivalent to `--current_; return *this;`. If `Bound` is not `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")` then `*bound\_*` must be positive.
2) Equivalent to `auto tmp = *this; --*this; return tmp;`.
std::ranges::repeat\_view::*iterator*::operator+=
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator+=( difference_type n );
```
| | (since C++23) |
Equivalent to `current_ += n; return *this;`. If `Bound` is not `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")` then `(*bound\_* + n)` must be non-negative.
std::ranges::repeat\_view::*iterator*::operator-=
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr /*iterator*/& operator-=( difference_type n );
```
| | (since C++23) |
Equivalent to `current_ -= n; return *this;`. If `Bound` is not `[std::unreachable\_sentinel\_t](../../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")`, then `(*bound\_* - n)` must be non-negative.
std::ranges::repeat\_view::*iterator*::operator[]
--------------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr const W& operator[]( difference_type n ) const noexcept;
```
| | (since C++23) |
Equivalent to `return *(*this + n);`.
### Non-member functions
operator==, <=>(std::ranges::repeat\_view::*iterator*)
-------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==( const /*iterator*/& x, const /*iterator*/& y );
```
| (1) | (since C++23) |
|
```
friend constexpr auto operator<=>( const /*iterator*/& x, const /*iterator*/& y );
```
| (2) | (since C++23) |
1) Equivalent to `x.current_ == y.current_`.
2) Equivalent to `x.current_ <=> y.current_`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `*iterator*` is an associated class of the arguments.
operator+(std::ranges::repeat\_view::*iterator*)
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr /*iterator*/ operator+( /*iterator*/ i, difference_type n );
```
| (1) | (since C++23) |
|
```
friend constexpr /*iterator*/ operator+( difference_type n, /*iterator*/ i );
```
| (2) | (since C++23) |
Equivalent to `i += n; return i;`.
These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `*iterator*` is an associated class of the arguments.
operator-(std::ranges::repeat\_view::*iterator*)
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
friend constexpr /*iterator*/ operator-( /*iterator*/ i, difference_type n );
```
| (1) | (since C++23) |
|
```
friend constexpr difference_type operator-( const /*iterator*/& x,
const /*iterator*/& y );
```
| (2) | (since C++23) |
1) Equivalent to `i -= n; return i;`.
2) Equivalent to `return static_cast<difference_type>(x.current_) - static_cast<difference_type>(y.current_);`. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `*iterator*` is an associated class of the arguments.
### Notes
`*iterator*` is always [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator").
cpp std::is_final std::is\_final
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_final;
```
| | (since C++14) |
If `T` is a final class (that is, a class declared with the [final specifier](../language/final "cpp/language/final")), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
If `T` is a class type, `T` shall be a complete type; otherwise, the behavior is undefined.
The behavior of a program that adds specializations for `is_final` or `is_final_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_final_v = is_final<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a final class type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Final classes cannot be used as base classes.
A [union](../language/union "cpp/language/union") can be marked `final` (and `std::is_final` will detect that), even though unions cannot be used as bases in any case.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_final`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
class A {};
class B final {};
int main()
{
std::cout
<< std::boolalpha
<< std::is_final<A>::value << '\n'
<< std::is_final<B>::value << '\n';
}
```
Output:
```
false
true
```
### See also
| | |
| --- | --- |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| [is\_polymorphic](is_polymorphic "cpp/types/is polymorphic")
(C++11) | checks if a type is a polymorphic class type (class template) |
cpp std::endian std::endian
===========
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
enum class endian
{
little = /*implementation-defined*/,
big = /*implementation-defined*/,
native = /*implementation-defined*/
};
```
| | (since C++20) |
Indicates the endianness of all [scalar types](../language/type "cpp/language/type"):
* If all scalar types are little-endian, `std::endian::native` equals `std::endian::little`
* If all scalar types are big-endian, `std::endian::native` equals `std::endian::big`
Corner case platforms are also supported:
* If all scalar types have sizeof equal to 1, endianness does not matter and all three values, `std::endian::little`, `std::endian::big`, and `std::endian::native` are the same.
* If the platform uses mixed endian, `std::endian::native` equals neither `std::endian::big` nor `std::endian::little`.
### Possible implementation
```
enum class endian
{
#ifdef _WIN32
little = 0,
big = 1,
native = little
#else
little = __ORDER_LITTLE_ENDIAN__,
big = __ORDER_BIG_ENDIAN__,
native = __BYTE_ORDER__
#endif
};
```
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_endian`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <iostream>
int main() {
if constexpr (std::endian::native == std::endian::big)
std::cout << "big-endian\n";
else if constexpr (std::endian::native == std::endian::little)
std::cout << "little-endian\n";
else std::cout << "mixed-endian\n";
}
```
Possible output:
```
little-endian
```
### See also
| | |
| --- | --- |
| [byteswap](../numeric/byteswap "cpp/numeric/byteswap")
(C++23) | reverses the bytes in the given integer value (function template) |
cpp std::is_constant_evaluated std::is\_constant\_evaluated
============================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
constexpr bool is_constant_evaluated() noexcept;
```
| | (since C++20) |
Detects whether the function call occurs within a constant-evaluated context. Returns `true` if the evaluation of the call occurs within the evaluation of an expression or conversion that is [manifestly constant-evaluated](../language/constant_expression#Manifestly_constant-evaluated_expressions "cpp/language/constant expression"); otherwise returns `false`.
While testing whether initializers of following variables are [constant initializers](../language/constant_initialization "cpp/language/constant initialization"), compilers may first perform a trial constant evaluation of the initializers:
* variables with reference type or const-qualified integral or enumeration type
+ if the initializers are constant expressions, the variables are [usable in constant expressions](../language/constant_expression#Usable_in_constant_expressions "cpp/language/constant expression")
* static and thread local variables
+ if when all subexpressions of the initializers (including constructor calls and implicit conversions) are [constant expressions](../language/constant_expression "cpp/language/constant expression"), [static initialization](../language/initialization#Static_initialization "cpp/language/initialization") is performed, which can be asserted by [`constinit`](../language/constinit "cpp/language/constinit")
It is not recommended to depend on the result in this case.
```
int y;
const int a = std::is_constant_evaluated() ? y : 1;
// Trial constant evaluation fails. The constant evaluation is discarded.
// Variable a is dynamically initialized with 1
const int b = std::is_constant_evaluated() ? 2 : y;
// Constant evaluation with std::is_constant_evaluation() == true succeeds.
// Variable b is statically initialized with 2
```
### Parameters
(none).
### Return value
`true` if the evaluation of the call occurs within the evaluation of an expression or conversion that is manifestly constant-evaluated; otherwise `false`.
### Possible implementation
| |
| --- |
|
```
// This implementation requires C++23 if consteval.
constexpr bool is_constant_evaluated() noexcept
{
if consteval {
return true;
}
else {
return false;
}
}
```
|
### Notes
When directly used as the condition of [`static_assert`](../language/static_assert "cpp/language/static assert") declaration or [constexpr if statement](../language/if#constexpr_if "cpp/language/if"), `std::is_constant_evaluated()` always returns `true`.
Because [`if consteval`](../language/if#Consteval_if "cpp/language/if") is absent in C++20, `std::is_constant_evaluated` is typically implemented by a compiler extension.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_constant_evaluated`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <type_traits>
#include <cmath>
#include <iostream>
constexpr double power(double b, int x)
{
if (std::is_constant_evaluated() && !(b == 0.0 && x < 0)) {
// A constant-evaluation context: Use a constexpr-friendly algorithm.
if (x == 0)
return 1.0;
double r = 1.0, p = x > 0 ? b : 1.0 / b;
auto u = unsigned(x > 0 ? x : -x);
while (u != 0) {
if (u & 1) r *= p;
u /= 2;
p *= p;
}
return r;
} else {
// Let the code generator figure it out.
return std::pow(b, double(x));
}
}
int main()
{
// A constant-expression context
constexpr double kilo = power(10.0, 3);
int n = 3;
// Not a constant expression, because n cannot be converted to an rvalue
// in a constant-expression context
// Equivalent to std::pow(10.0, double(n))
double mucho = power(10.0, n);
std::cout << kilo << " " << mucho << "\n"; // (3)
}
```
Output:
```
1000 1000
```
### See also
| | |
| --- | --- |
| [`constexpr` specifier](../language/constexpr "cpp/language/constexpr")(C++11) | specifies that the value of a variable or function can be computed at compile time |
| [`consteval` specifier](../language/consteval "cpp/language/consteval")(C++20) | specifies that a function is an *immediate function*, that is, every call to the function must be in a constant evaluation |
| [`constinit` specifier](../language/constinit "cpp/language/constinit")(C++20) | asserts that a variable has static initialization, i.e. [zero initialization](../language/zero_initialization "cpp/language/zero initialization") and [constant initialization](../language/constant_initialization "cpp/language/constant initialization") |
| programming_docs |
cpp std::is_constructible, std::is_trivially_constructible, std::is_nothrow_constructible std::is\_constructible, std::is\_trivially\_constructible, std::is\_nothrow\_constructible
==========================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class... Args >
struct is_constructible;
```
| (1) | (since C++11) |
|
```
template< class T, class... Args >
struct is_trivially_constructible;
```
| (2) | (since C++11) |
|
```
template< class T, class... Args >
struct is_nothrow_constructible;
```
| (3) | (since C++11) |
1) If `T` is an object or reference type and the variable definition `T obj([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...);` is well-formed, provides the member constant `value` equal to `true`. In all other cases, `value` is `false`.
For the purposes of this check, the variable definition is never interpreted as a function declaration, and the use of `[std::declval](../utility/declval "cpp/utility/declval")` is not considered an [odr-use](../language/definition#ODR-use "cpp/language/definition"). [Access checks](../language/access "cpp/language/access") are performed as if from a context unrelated to `T` and any of the types in `Args`. Only the validity of the immediate context of the variable definition is considered.
2) same as (1), but the variable definition does not call any operation that is not trivial. For the purposes of this check, the call to `[std::declval](../utility/declval "cpp/utility/declval")` is considered trivial.
3) same as (1), but the variable definition is `noexcept`. `T` and all types in the parameter pack `Args` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T, class... Args >
inline constexpr bool is_constructible_v = is_constructible<T, Args...>::value;
```
| | (since C++17) |
|
```
template< class T, class... Args >
inline constexpr bool is_trivially_constructible_v = is_trivially_constructible<T, Args...>::value;
```
| | (since C++17) |
|
```
template< class T, class... Args >
inline constexpr bool is_nothrow_constructible_v = is_nothrow_constructible<T, Args...>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is constructible from `Args...` , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
In many implementations, `is_nothrow_constructible` also checks if the destructor throws because it is effectively `noexcept(T(arg))`. Same applies to `is_trivially_constructible`, which, in these implementations, also requires that the destructor is trivial: [GCC bug 51452](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452) [LWG issue 2116](https://cplusplus.github.io/LWG/issue2116).
### Example
```
#include <iostream>
#include <type_traits>
class Foo {
int v1;
double v2;
public:
Foo(int n) : v1(n), v2() {}
Foo(int n, double f) noexcept : v1(n), v2(f) {}
};
int main() {
auto is = [](bool o) { return (o ? "\t" "is " : "\t" "isn't "); };
std::cout << "Foo ...\n"
<< is(std::is_trivially_constructible_v<Foo, const Foo&>)
<< "Trivially-constructible from const Foo&\n"
<< is(std::is_trivially_constructible_v<Foo, int>)
<< "Trivially-constructible from int\n"
<< is(std::is_constructible_v<Foo, int>)
<< "Constructible from int\n"
<< is(std::is_nothrow_constructible_v<Foo, int>)
<< "Nothrow-constructible from int\n"
<< is(std::is_nothrow_constructible_v<Foo, int, double>)
<< "Nothrow-constructible from int and double\n";
}
```
Output:
```
Foo ...
is Trivially-constructible from const Foo&
isn't Trivially-constructible from int
is Constructible from int
isn't Nothrow-constructible from int
is Nothrow-constructible from int and double
```
### See also
| | |
| --- | --- |
| [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](is_default_constructible "cpp/types/is default constructible")
(C++11)(C++11)(C++11) | checks if a type has a default constructor (class template) |
| [is\_copy\_constructibleis\_trivially\_copy\_constructibleis\_nothrow\_copy\_constructible](is_copy_constructible "cpp/types/is copy constructible")
(C++11)(C++11)(C++11) | checks if a type has a copy constructor (class template) |
| [is\_move\_constructibleis\_trivially\_move\_constructibleis\_nothrow\_move\_constructible](is_move_constructible "cpp/types/is move constructible")
(C++11)(C++11)(C++11) | checks if a type can be constructed from an rvalue reference (class template) |
| [constructible\_from](../concepts/constructible_from "cpp/concepts/constructible from")
(C++20) | specifies that a variable of the type can be constructed from or bound to a set of argument types (concept) |
cpp std::is_member_object_pointer std::is\_member\_object\_pointer
================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_member_object_pointer;
```
| | (since C++11) |
Checks whether `T` is a non-static member object pointer. Provides the member constant `value` which is equal to `true`, if `T` is a non-static member object pointer type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_member_object_pointer` or `is_member_object_pointer_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_member_object_pointer_v = is_member_object_pointer<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a pointer to member object , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_member_object_pointer : std::integral_constant<
bool,
std::is_member_pointer<T>::value &&
!std::is_member_function_pointer<T>::value
> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
class C {};
std::cout << "Is member object pointer?\n" << std::boolalpha
<< std::is_member_object_pointer_v<int(C::*)>
<< ": int(C::*)\n"
<< std::is_member_object_pointer_v<int(C::*)()>
<< ": int(C::*)()\n";
}
```
Output:
```
Is member object pointer?
true: int(C::*)
false: int(C::*)()
```
### See also
| | |
| --- | --- |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_member\_pointer](is_member_pointer "cpp/types/is member pointer")
(C++11) | checks if a type is a pointer to an non-static member function or object (class template) |
| [is\_member\_function\_pointer](is_member_function_pointer "cpp/types/is member function pointer")
(C++11) | checks if a type is a pointer to a non-static member function (class template) |
cpp std::alignment_of std::alignment\_of
==================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct alignment_of;
```
| | (since C++11) |
Provides the member constant `value` equal to the [alignment requirement](../language/object#Alignment "cpp/language/object") of the type `T`, as if obtained by an `alignof` expression. If `T` is an array type, returns the alignment requirements of the element type. If `T` is a reference type, returns the alignment requirements of the type referred to.
If `alignof(T)` is not a valid expression, the behavior is undefined.
The behavior of a program that adds specializations for `alignment_of` or `alignment_of_v` (since C++17) is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr std::size_t alignment_of_v = alignment_of<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `alignof(T)` (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `std::size_t` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct alignment_of : std::integral_constant<
std::size_t,
alignof(T)
> {};
```
|
### Notes
This type trait predates the [`alignof` keyword](../language/alignof "cpp/language/alignof"), which can be used to obtain the same value with less verbosity.
### Example
```
#include <cstdint>
#include <iostream>
#include <type_traits>
struct A {};
struct B {
std::int8_t p;
std::int16_t q;
};
int main()
{
std::cout << std::alignment_of<A>::value << ' ';
std::cout << std::alignment_of<B>::value << ' ';
std::cout << std::alignment_of<int>() << ' '; // alt syntax
std::cout << std::alignment_of_v<double> << '\n'; // c++17 alt syntax
}
```
Possible output:
```
1 2 4 8
```
### See also
| | |
| --- | --- |
| [`alignof` operator](../language/alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type |
| [`alignas` specifier](../language/alignas "cpp/language/alignas")(C++11) | specifies that the storage for the variable should be aligned by specific amount |
| [aligned\_storage](aligned_storage "cpp/types/aligned storage")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) |
| [aligned\_union](aligned_union "cpp/types/aligned union")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for all given types (class template) |
| [max\_align\_t](max_align_t "cpp/types/max align t")
(C++11) | trivial type with alignment requirement as great as any other scalar type (typedef) |
cpp std::is_standard_layout std::is\_standard\_layout
=========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_standard_layout;
```
| | (since C++11) |
If `T` is a [standard-layout type](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type and not (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_standard_layout` or `is_standard_layout_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_standard_layout_v = is_standard_layout<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a standard-layout type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
A pointer to a standard-layout class may be converted (with reinterpret\_cast) to a pointer to its first non-static data member and vice versa.
If a standard-layout union holds two or more standard-layout structs, it is permitted to inspect the common initial part of them.
The macro `[offsetof](offsetof "cpp/types/offsetof")` is only guaranteed to be usable with standard-layout classes.
### Example
```
#include <iostream>
#include <type_traits>
struct A
{
int m;
};
struct B
{
int m1;
private:
int m2;
};
struct C
{
virtual void foo();
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_standard_layout<A>::value << '\n';
std::cout << std::is_standard_layout<B>::value << '\n';
std::cout << std::is_standard_layout<C>::value << '\n';
}
```
Output:
```
true
false
false
```
### See also
| | |
| --- | --- |
| [is\_trivially\_copyable](is_trivially_copyable "cpp/types/is trivially copyable")
(C++11) | checks if a type is trivially copyable (class template) |
| [is\_pod](is_pod "cpp/types/is pod")
(C++11)(deprecated in C++20) | checks if a type is a plain-old data (POD) type (class template) |
| [offsetof](offsetof "cpp/types/offsetof") | byte offset from the beginning of a standard-layout type to specified member (function macro) |
cpp std::is_integral std::is\_integral
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_integral;
```
| | (since C++11) |
Checks whether `T` is an integral type. Provides the member constant `value` which is equal to `true`, if `T` is the type `bool`, `char`, `char8_t` (since C++20), `char16_t`, `char32_t`, `wchar_t`, `short`, `int`, `long`, `long long`, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_integral` or `is_integral_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_integral_v = is_integral<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an integral type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Example
```
#include <iostream>
#include <iomanip>
#include <type_traits>
class A {};
enum E : int {};
template <class T>
T f(T i)
{
static_assert(std::is_integral<T>::value, "Integral required.");
return i;
}
#define SHOW(...) std::cout << std::setw(29) << #__VA_ARGS__ << " == " << __VA_ARGS__ << '\n'
int main()
{
std::cout << std::boolalpha;
SHOW( std::is_integral<A>::value );
SHOW( std::is_integral_v<E> );
SHOW( std::is_integral_v<float> );
SHOW( std::is_integral_v<int> );
SHOW( std::is_integral_v<const int> );
SHOW( std::is_integral_v<bool> );
SHOW( f(123) );
}
```
Output:
```
std::is_integral<A>::value == false
std::is_integral_v<E> == false
std::is_integral_v<float> == false
std::is_integral_v<int> == true
std::is_integral_v<const int> == true
std::is_integral_v<bool> == true
f(123) == 123
```
### See also
| | |
| --- | --- |
| [integral](../concepts/integral "cpp/concepts/integral")
(C++20) | specifies that a type is an integral type (concept) |
| [is\_integer](numeric_limits/is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant of `std::numeric_limits<T>`) |
| [is\_floating\_point](is_floating_point "cpp/types/is floating point")
(C++11) | checks if a type is a floating-point type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
cpp std::is_pointer std::is\_pointer
================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_pointer;
```
| | (since C++11) |
Checks whether `T` is a [pointer to object](../language/pointer "cpp/language/pointer") or a pointer to function (but not a pointer to member/member function) or a cv-qualified version thereof. Provides the member constant `value` which is equal to `true`, if `T` is a object/function pointer type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_pointer` or `is_pointer_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_pointer_v = is_pointer<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a pointer type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_pointer : std::false_type {};
template<class T>
struct is_pointer<T*> : std::true_type {};
template<class T>
struct is_pointer<T* const> : std::true_type {};
template<class T>
struct is_pointer<T* volatile> : std::true_type {};
template<class T>
struct is_pointer<T* const volatile> : std::true_type {};
```
|
### Example
```
#include <type_traits>
int main()
{
class A {};
static_assert(
not std::is_pointer<A>::value
&& not std::is_pointer_v<A> // same thing as above, but in C++17!
&& not std::is_pointer<A>() // same as above, using inherited operator bool
&& not std::is_pointer<A>{} // ditto
&& not std::is_pointer<A>()() // same as above, using inherited operator()
&& not std::is_pointer<A>{}() // ditto
&& std::is_pointer<A *>::value
&& std::is_pointer<A const * volatile>()
&& not std::is_pointer<A &>::value
&& not std::is_pointer<int>::value
&& std::is_pointer<int *>::value
&& std::is_pointer<int **>::value
&& not std::is_pointer<int[10]>::value
&& not std::is_pointer<std::nullptr_t>::value
);
}
```
### See also
| | |
| --- | --- |
| [is\_member\_pointer](is_member_pointer "cpp/types/is member pointer")
(C++11) | checks if a type is a pointer to an non-static member function or object (class template) |
| [is\_member\_object\_pointer](is_member_object_pointer "cpp/types/is member object pointer")
(C++11) | checks if a type is a pointer to a non-static member object (class template) |
| [is\_member\_function\_pointer](is_member_function_pointer "cpp/types/is member function pointer")
(C++11) | checks if a type is a pointer to a non-static member function (class template) |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| programming_docs |
cpp std::is_lvalue_reference std::is\_lvalue\_reference
==========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_lvalue_reference;
```
| | (since C++11) |
Checks whether `T` is a lvalue reference type. Provides the member constant `value` which is equal to `true`, if `T` is a lvalue reference type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_lvalue_reference` or `is_lvalue_reference_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_lvalue_reference_v = is_lvalue_reference<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an lvalue reference type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T> struct is_lvalue_reference : std::false_type {};
template<class T> struct is_lvalue_reference<T&> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_lvalue_reference<A>::value << '\n';
std::cout << std::is_lvalue_reference<A&>::value << '\n';
std::cout << std::is_lvalue_reference<A&&>::value << '\n';
std::cout << std::is_lvalue_reference<int>::value << '\n';
std::cout << std::is_lvalue_reference<int&>::value << '\n';
std::cout << std::is_lvalue_reference<int&&>::value << '\n';
}
```
Output:
```
false
true
false
false
true
false
```
### See also
| | |
| --- | --- |
| [is\_reference](is_reference "cpp/types/is reference")
(C++11) | checks if a type is either a *lvalue reference* or *rvalue reference* (class template) |
| [is\_rvalue\_reference](is_rvalue_reference "cpp/types/is rvalue reference")
(C++11) | checks if a type is a *rvalue reference* (class template) |
cpp std::is_trivial std::is\_trivial
================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_trivial;
```
| | (since C++11) |
If `T` is a [trivial type](../named_req/trivialtype "cpp/named req/TrivialType"), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type and not (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_trivial` or `is_trivial_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_trivial_v = is_trivial<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a trivial type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_trivial : std::integral_constant<
bool,
std::is_trivially_copyable<T>::value &&
std::is_trivially_default_constructible<T>::value
> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
struct A
{
int m;
};
struct B
{
B() {}
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_trivial<A>::value << '\n';
std::cout << std::is_trivial<B>::value << '\n';
}
```
Output:
```
true
false
```
### See also
| | |
| --- | --- |
| [is\_trivially\_copyable](is_trivially_copyable "cpp/types/is trivially copyable")
(C++11) | checks if a type is trivially copyable (class template) |
| [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](is_default_constructible "cpp/types/is default constructible")
(C++11)(C++11)(C++11) | checks if a type has a default constructor (class template) |
cpp Fixed width integer types (since C++11)
Fixed width integer types (since C++11)
=======================================
### Types
| Defined in header `[<cstdint>](../header/cstdint "cpp/header/cstdint")` |
| --- |
| int8\_tint16\_tint32\_tint64\_t
(optional) | signed integer type with width of exactly 8, 16, 32 and 64 bits respectivelywith no padding bits and using 2's complement for negative values(provided if and only if the implementation directly supports the type) (typedef) |
| int\_fast8\_tint\_fast16\_tint\_fast32\_tint\_fast64\_t | fastest signed integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) |
| int\_least8\_tint\_least16\_tint\_least32\_tint\_least64\_t | smallest signed integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) |
| intmax\_t | maximum-width signed integer type (typedef) |
| intptr\_t
(optional) | signed integer type capable of holding a pointer to `void` (typedef) |
| uint8\_tuint16\_tuint32\_tuint64\_t
(optional) | unsigned integer type with width of exactly 8, 16, 32 and 64 bits respectively (provided if and only if the implementation directly supports the type) (typedef) |
| uint\_fast8\_tuint\_fast16\_tuint\_fast32\_tuint\_fast64\_t | fastest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) |
| uint\_least8\_tuint\_least16\_tuint\_least32\_tuint\_least64\_t | smallest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) |
| uintmax\_t | maximum-width unsigned integer type (typedef) |
| uintptr\_t
(optional) | unsigned integer type capable of holding a pointer to `void` (typedef) |
The implementation may define typedef names `int*N*_t`, `int_fast*N*_t`, `int_least*N*_t`, `uint*N*_t`, `uint_fast*N*_t`, and `uint_least*N*_t` when *N* is not 8, 16, 32 or 64. Typedef names of the form `int*N*_t` may only be defined if the implementation supports an integer type of that width with no padding. Thus, `uint24_t` denotes an unsigned integer type with a width of exactly 24 bits.
Each of the macros listed in below is defined if and only if the implementation defines the corresponding typedef name. The macros `INT*N*_C` and `UINT*N*_C` correspond to the typedef names `int_least*N*_t` and `uint_least*N*_t`, respectively.
### Macro constants
| Defined in header `[<cstdint>](../header/cstdint "cpp/header/cstdint")` |
| --- |
| Signed integers : minimum value |
| INT8\_MININT16\_MININT32\_MININT64\_MIN
(optional) | minimum value of an object of type `int8_t`, `int16_t`, `int32_t`, `int64_t` (macro constant) |
| INT\_FAST8\_MININT\_FAST16\_MININT\_FAST32\_MININT\_FAST64\_MIN | minimum value of an object of type `int_fast8_t`, `int_fast16_t`, `int_fast32_t`, `int_fast64_t` (macro constant) |
| INT\_LEAST8\_MININT\_LEAST16\_MININT\_LEAST32\_MININT\_LEAST64\_MIN | minimum value of an object of type `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` (macro constant) |
| INTPTR\_MIN
(optional) | minimum value of an object of type `intptr_t` (macro constant) |
| INTMAX\_MIN | minimum value of an object of type `intmax_t` (macro constant) |
| Signed integers : maximum value |
| INT8\_MAXINT16\_MAXINT32\_MAXINT64\_MAX
(optional) | maximum value of an object of type `int8_t`, `int16_t`, `int32_t`, `int64_t` (macro constant) |
| INT\_FAST8\_MAXINT\_FAST16\_MAXINT\_FAST32\_MAXINT\_FAST64\_MAX | maximum value of an object of type `int_fast8_t`, `int_fast16_t`, `int_fast32_t`, `int_fast64_t` (macro constant) |
| INT\_LEAST8\_MAXINT\_LEAST16\_MAXINT\_LEAST32\_MAXINT\_LEAST64\_MAX | maximum value of an object of type `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` (macro constant) |
| INTPTR\_MAX
(optional) | maximum value of an object of type `intptr_t` (macro constant) |
| INTMAX\_MAX | maximum value of an object of type `intmax_t` (macro constant) |
| Unsigned integers : maximum value |
| UINT8\_MAXUINT16\_MAXUINT32\_MAXUINT64\_MAX
(optional) | maximum value of an object of type `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t` (macro constant) |
| UINT\_FAST8\_MAXUINT\_FAST16\_MAXUINT\_FAST32\_MAXUINT\_FAST64\_MAX | maximum value of an object of type `uint_fast8_t`, `uint_fast16_t`, `uint_fast32_t`, `uint_fast64_t` (macro constant) |
| UINT\_LEAST8\_MAXUINT\_LEAST16\_MAXUINT\_LEAST32\_MAXUINT\_LEAST64\_MAX | maximum value of an object of type `uint_least8_t`, `uint_least16_t`, `uint_least32_t`, `uint_least64_t` (macro constant) |
| UINTPTR\_MAX
(optional) | maximum value of an object of type `uintptr_t` (macro constant) |
| UINTMAX\_MAX | maximum value of an object of type `uintmax_t` (macro constant) |
### Function macros for minimum-width integer constants
| | |
| --- | --- |
| INT8\_CINT16\_CINT32\_CINT64\_C | expands to an integer constant expression having the value specified by its argument and whose type is the [promoted](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") type of `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` respectively (function macro) |
| INTMAX\_C | expands to an integer constant expression having the value specified by its argument and the type `intmax_t` (function macro) |
| UINT8\_CUINT16\_CUINT32\_CUINT64\_C | expands to an integer constant expression having the value specified by its argument and whose type is the [promoted](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") type of `uint_least8_t`, `uint_least16_t`, `uint_least32_t`, `uint_least64_t` respectively (function macro) |
| UINTMAX\_C | expands to an integer constant expression having the value specified by its argument and the type `uintmax_t` (function macro) |
```
#include <cstdint>
UINT64_C(0x123) // expands to a literal of type uint_least64_t and value 0x123
```
### Format macro constants
| Defined in header `[<cinttypes>](../header/cinttypes "cpp/header/cinttypes")` |
| --- |
#### Format constants for the `[std::fprintf](../io/c/fprintf "cpp/io/c/fprintf")` family of functions
Each of the `PRI` macros listed here is defined if and only if the implementation defines the corresponding typedef name.
| Equivalentfor `int` or`unsigned int` | Description | Macros for data types |
| --- | --- | --- |
|
`std::int`**x**`_t`
|
`std::int_least`**x**`_t`
|
`std::int_fast`**x**`_t`
| `std::intmax_t` | `std::intptr_t` |
| `d` | output of a signed decimal integer value | PRId**x** | PRIdLEAST**x** | PRIdFAST**x** | PRIdMAX | PRIdPTR |
| `i` | PRIi**x** | PRIiLEAST**x** | PRIiFAST**x** | PRIiMAX | PRIiPTR |
| `u` | output of an unsigned decimal integer value | PRIu**x** | PRIuLEAST**x** | PRIuFAST**x** | PRIuMAX | PRIuPTR |
| `o` | output of an unsigned octal integer value | PRIo**x** | PRIoLEAST**x** | PRIoFAST**x** | PRIoMAX | PRIoPTR |
| `x` | output of an unsigned lowercase hexadecimal integer value | PRIx**x** | PRIxLEAST**x** | PRIxFAST**x** | PRIxMAX | PRIxPTR |
| `X` | output of an unsigned uppercase hexadecimal integer value | PRIX**x** | PRIXLEAST**x** | PRIXFAST**x** | PRIXMAX | PRIXPTR |
#### Format constants for the `[std::fscanf](../io/c/fscanf "cpp/io/c/fscanf")` family of functions
Each of the `SCN` macros listed in here is defined if and only if the implementation defines the corresponding typedef name and has a suitable `[std::fscanf](../io/c/fscanf "cpp/io/c/fscanf")` length modifier for the type.
| Equivalentfor `int` or`unsigned int` | Description | Macros for data types |
| --- | --- | --- |
|
`std::int`**x**`_t`
|
`std::int_least`**x**`_t`
|
`std::int_fast`**x**`_t`
| `std::intmax_t` | `std::intptr_t` |
| `d` | input of a signed decimal integer value | SCNd**x** | SCNdLEAST**x** | SCNdFAST**x** | SCNdMAX | SCNdPTR |
| `i` | input of a signed integer value | SCNi**x** | SCNiLEAST**x** | SCNiFAST**x** | SCNiMAX | SCNiPTR |
| `u` | input of an unsigned decimal integer value | SCNu**x** | SCNuLEAST**x** | SCNuFAST**x** | SCNuMAX | SCNuPTR |
| `o` | input of an unsigned octal integer value | SCNo**x** | SCNoLEAST**x** | SCNoFAST**x** | SCNoMAX | SCNoPTR |
| `x` | input of an unsigned hexadecimal integer value | SCNx**x** | SCNxLEAST**x** | SCNxFAST**x** | SCNxMAX | SCNxPTR |
### Notes
Because C++ interprets a character immediately following a string literal as a [user-defined string literal](../language/user_literal "cpp/language/user literal"), C code such as `printf("%"PRId64"\n",n);` is invalid C++ and requires a space before `PRId64`.
The C99 standard suggests that C++ implementations should not define the above limit, constant, or format macros unless the macros `__STDC_LIMIT_MACROS`, `__STDC_CONSTANT_MACROS` or `__STDC_FORMAT_MACROS` (respectively) are defined before including the relevant C header (`stdint.h` or `inttypes.h`). This recommendation was not adopted by any C++ standard and was removed in C11. However, some implementations (such as glibc 2.17) try to apply this rule, and it may be necessary to define the `__STDC` macros; C++ compilers may try to work around this by automatically defining them in some circumstances.
### Example
```
#include <cstdio>
#include <cinttypes>
int main()
{
std::printf("%zu\n", sizeof(std::int64_t));
std::printf("%s\n", PRId64);
std::printf("%+" PRId64 "\n", INT64_MIN);
std::printf("%+" PRId64 "\n", INT64_MAX);
std::int64_t n = 7;
std::printf("%+" PRId64 "\n", n);
}
```
Possible output:
```
8
lld
-9223372036854775808
+9223372036854775807
+7
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2820](https://cplusplus.github.io/LWG/issue2820) | C++11 | the requirements for optional typedef names and macros were inconsistent with C | made consistent |
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 17.4 Integer types [cstdint]
+ 29.12.2 Header <cinttypes> synopsis [cinttypes.syn]
* C++17 standard (ISO/IEC 14882:2017):
+ 21.4 Integer types [cstdint]
+ 30.11.2 Header <cinttypes> synopsis [cinttypes.syn]
* C++14 standard (ISO/IEC 14882:2014):
+ 18.4 Integer types [cstdint]
+ 27.9.2 C library files [c.files]
* C++11 standard (ISO/IEC 14882:2011):
+ 18.4 Integer types [cstdint]
+ 27.9.2 C library files [c.files]
### See also
* [Fundamental types](../language/types "cpp/language/types")
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/types/integer "c/types/integer") for Fixed width integer types |
cpp std::is_convertible, std::is_nothrow_convertible std::is\_convertible, std::is\_nothrow\_convertible
===================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class From, class To >
struct is_convertible;
```
| (1) | (since C++11) |
|
```
template< class From, class To >
struct is_nothrow_convertible;
```
| (2) | (since C++20) |
1) If the imaginary function definition `To test() { return [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<From>(); }` is well-formed, (that is, either `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<From>()` can be converted to `To` using [implicit conversions](../language/implicit_cast "cpp/language/implicit cast"), or both `From` and `To` are possibly cv-qualified `void`), provides the member constant `value` equal to `true`. Otherwise `value` is `false`. For the purposes of this check, the use of `[std::declval](../utility/declval "cpp/utility/declval")` in the return statement is not considered an [odr-use](../language/definition#ODR-use "cpp/language/definition").
[Access checks](../language/access "cpp/language/access") are performed as if from a context unrelated to either type. Only the validity of the immediate context of the expression in the return statement (including conversions to the return type) is considered.
2) Same as (1), but the conversion is also `noexcept`. `From` and `To` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class From, class To >
inline constexpr bool is_convertible_v = is_convertible<From, To>::value;
```
| | (since C++17) |
|
```
template< class From, class To >
inline constexpr bool is_nothrow_convertible_v = is_nothrow_convertible<From, To>::value;
```
| | (since C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `From` is convertible to `To` , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| First version |
| --- |
|
```
namespace detail {
template<class T>
auto test_returnable(int) -> decltype(
void(static_cast<T(*)()>(nullptr)), std::true_type{}
);
template<class>
auto test_returnable(...) -> std::false_type;
template<class From, class To>
auto test_implicitly_convertible(int) -> decltype(
void(std::declval<void(&)(To)>()(std::declval<From>())), std::true_type{}
);
template<class, class>
auto test_implicitly_convertible(...) -> std::false_type;
} // namespace detail
template<class From, class To>
struct is_convertible : std::integral_constant<bool,
(decltype(detail::test_returnable<To>(0))::value &&
decltype(detail::test_implicitly_convertible<From, To>(0))::value) ||
(std::is_void<From>::value && std::is_void<To>::value)
> {};
```
|
| Second version |
|
```
template<class From, class To>
struct is_nothrow_convertible : std::conjunction<std::is_void<From>, std::is_void<To>> {};
template<class From, class To>
requires
requires {
static_cast<To(*)()>(nullptr);
{ std::declval<void(&)(To) noexcept>()(std::declval<From>()) } noexcept;
}
struct is_nothrow_convertible<From, To> : std::true_type {};
```
|
### Notes
Gives well-defined results for reference types, void types, array types, and function types.
Currently the standard has not specified whether the destruction of the object produced by the conversion (either a result object or a temporary bound to a reference) is considered as a part of the conversion. This is [LWG issue 3400](https://cplusplus.github.io/LWG/issue3400).
All known implementations treat the destruction as a part of the conversion, as proposed in [P0758R1](https://wg21.link/p0758r1#Appendix).
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_nothrow_convertible`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>
class E { public: template<class T> E(T&&) { } };
int main()
{
class A {};
class B : public A {};
class C {};
class D { public: operator C() { return c; } C c; };
std::cout
<< std::boolalpha
<< std::is_convertible_v<B*, A*> << ' ' // true
<< std::is_convertible_v<A*, B*> << ' ' // false
<< std::is_convertible_v<D, C> << ' ' // true
<< std::is_convertible_v<B*, C*> << ' ' // false
// Note that the Perfect Forwarding constructor makes the class E be
// "convertible" from everything. So, A is replaceable by B, C, D..:
<< std::is_convertible_v<A, E> << ' '; // true
using std::operator "" s, std::operator "" sv;
auto stringify = []<typename T>(T x) {
if constexpr (std::is_convertible_v<T, std::string> or
std::is_convertible_v<T, std::string_view>) {
return x;
} else {
return std::to_string(x);
}
};
const char* three = "three";
std::cout
<< std::is_convertible_v<std::string_view, std::string> << ' ' // false
<< std::is_convertible_v<std::string, std::string_view> << ' ' // true
<< std::quoted(stringify("one"s)) << ' '
<< std::quoted(stringify("two"sv)) << ' '
<< std::quoted(stringify(three)) << ' '
<< std::quoted(stringify(42)) << ' '
<< std::quoted(stringify(42.)) << '\n';
}
```
Output:
```
true false true false true false true "one" "two" "three" "42" "42.000000"
```
### See also
| | |
| --- | --- |
| [is\_base\_of](is_base_of "cpp/types/is base of")
(C++11) | checks if a type is derived from the other type (class template) |
| [is\_pointer\_interconvertible\_base\_of](is_pointer_interconvertible_base_of "cpp/types/is pointer interconvertible base of")
(C++20) | checks if a type is a *pointer-interconvertible* (initial) base of another type (class template) |
| [is\_pointer\_interconvertible\_with\_class](is_pointer_interconvertible_with_class "cpp/types/is pointer interconvertible with class")
(C++20) | checks if objects of a type are pointer-interconvertible with the specified subobject of that type (function template) |
| [convertible\_to](../concepts/convertible_to "cpp/concepts/convertible to")
(C++20) | specifies that a type is implicitly convertible to another type (concept) |
| programming_docs |
cpp std::bad_cast std::bad\_cast
==============
| Defined in header `[<typeinfo>](../header/typeinfo "cpp/header/typeinfo")` | | |
| --- | --- | --- |
|
```
class bad_cast : public std::exception;
```
| | |
An exception of this type is thrown when a [`dynamic_cast`](../language/dynamic_cast "cpp/language/dynamic cast") to a reference type fails the run-time check (e.g. because the types are not related by inheritance), and also from `[std::use\_facet](../locale/use_facet "cpp/locale/use facet")` if the requested facet does not exist in the locale.
![std-bad cast-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs a new `bad_cast` object (public member function) |
| operator= | replaces the `bad_cast` object (public member function) |
| what | returns the explanatory string (public member function) |
std::bad\_cast::bad\_cast
--------------------------
| | | |
| --- | --- | --- |
| | (1) | |
|
```
bad_cast() throw();
```
| (until C++11) |
|
```
bad_cast() noexcept;
```
| (since C++11) |
| | (2) | |
|
```
bad_cast( const bad_cast& other ) throw();
```
| (until C++11) |
|
```
bad_cast( const bad_cast& other ) noexcept;
```
| (since C++11) |
Constructs a new `bad_cast` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../error/exception/what "cpp/error/exception/what").
1) Default constructor.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_cast` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11)
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to copy |
std::bad\_cast::operator=
--------------------------
| | | |
| --- | --- | --- |
|
```
bad_cast& operator=( const bad_cast& other ) throw();
```
| | (until C++11) |
|
```
bad_cast& operator=( const bad_cast& other ) noexcept;
```
| | (since C++11) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_cast` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11).
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::bad\_cast::what
---------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const throw();
```
| | (until C++11) |
|
```
virtual const char* what() const noexcept;
```
| | (since C++11) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::exception](../error/exception "cpp/error/exception")
---------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
### Example
```
#include <iostream>
#include <typeinfo>
struct Foo { virtual ~Foo() {} };
struct Bar { virtual ~Bar() { std::cout << "~Bar\n"; } };
struct Pub : Bar { ~Pub() override { std::cout << "~Pub\n"; } };
int main()
{
Pub pub;
try
{
[[maybe_unused]]
Bar& r1 = dynamic_cast<Bar&>(pub); // OK, upcast
[[maybe_unused]]
Foo& r2 = dynamic_cast<Foo&>(pub); // throws
}
catch(const std::bad_cast& e)
{
std::cout << "e.what(): " << e.what() << '\n';
}
}
```
Possible output:
```
e.what(): std::bad_cast
~Pub
~Bar
```
cpp std::result_of, std::invoke_result std::result\_of, std::invoke\_result
====================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class >
class result_of; // not defined
template< class F, class... ArgTypes >
class result_of<F(ArgTypes...)>;
```
| (1) | (since C++11) (deprecated in C++17) (removed in C++20) |
|
```
template< class F, class... ArgTypes>
class invoke_result;
```
| (2) | (since C++17) |
Deduces the return type of an [INVOKE expression](../named_req/callable "cpp/named req/Callable") at compile time.
| | |
| --- | --- |
| `F` must be a callable type, reference to function, or reference to callable type. Invoking `F` with `ArgTypes...` must be a well-formed expression. | (since C++11)(until C++14) |
| `F` and all types in `ArgTypes` can be any complete type, array of unknown bound, or (possibly cv-qualified) `void`. | (since C++14) |
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Member types
| Member type | Definition |
| --- | --- |
| `type` | the return type of the [Callable](../named_req/callable "cpp/named req/Callable") type `F` if invoked with the arguments `ArgTypes...`. Only defined if F can be called with the arguments `ArgTypes...` in unevaluated context. (since C++14) |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using result_of_t = typename result_of<T>::type;
```
| (1) | (since C++14) (deprecated in C++17) (removed in C++20) |
|
```
template< class F, class... ArgTypes>
using invoke_result_t = typename invoke_result<F, ArgTypes...>::type;
```
| (2) | (since C++17) |
### Possible implementation
```
namespace detail {
template <class T>
struct is_reference_wrapper : std::false_type {};
template <class U>
struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {};
template<class T>
struct invoke_impl {
template<class F, class... Args>
static auto call(F&& f, Args&&... args)
-> decltype(std::forward<F>(f)(std::forward<Args>(args)...));
};
template<class B, class MT>
struct invoke_impl<MT B::*> {
template<class T, class Td = typename std::decay<T>::type,
class = typename std::enable_if<std::is_base_of<B, Td>::value>::type
>
static auto get(T&& t) -> T&&;
template<class T, class Td = typename std::decay<T>::type,
class = typename std::enable_if<is_reference_wrapper<Td>::value>::type
>
static auto get(T&& t) -> decltype(t.get());
template<class T, class Td = typename std::decay<T>::type,
class = typename std::enable_if<!std::is_base_of<B, Td>::value>::type,
class = typename std::enable_if<!is_reference_wrapper<Td>::value>::type
>
static auto get(T&& t) -> decltype(*std::forward<T>(t));
template<class T, class... Args, class MT1,
class = typename std::enable_if<std::is_function<MT1>::value>::type
>
static auto call(MT1 B::*pmf, T&& t, Args&&... args)
-> decltype((invoke_impl::get(std::forward<T>(t)).*pmf)(std::forward<Args>(args)...));
template<class T>
static auto call(MT B::*pmd, T&& t)
-> decltype(invoke_impl::get(std::forward<T>(t)).*pmd);
};
template<class F, class... Args, class Fd = typename std::decay<F>::type>
auto INVOKE(F&& f, Args&&... args)
-> decltype(invoke_impl<Fd>::call(std::forward<F>(f), std::forward<Args>(args)...));
} // namespace detail
// Minimal C++11 implementation:
template <class> struct result_of;
template <class F, class... ArgTypes>
struct result_of<F(ArgTypes...)> {
using type = decltype(detail::INVOKE(std::declval<F>(), std::declval<ArgTypes>()...));
};
// Conforming C++14 implementation (is also a valid C++11 implementation):
namespace detail {
template <typename AlwaysVoid, typename, typename...>
struct invoke_result { };
template <typename F, typename...Args>
struct invoke_result<decltype(void(detail::INVOKE(std::declval<F>(), std::declval<Args>()...))),
F, Args...> {
using type = decltype(detail::INVOKE(std::declval<F>(), std::declval<Args>()...));
};
} // namespace detail
template <class> struct result_of;
template <class F, class... ArgTypes>
struct result_of<F(ArgTypes...)> : detail::invoke_result<void, F, ArgTypes...> {};
template <class F, class... ArgTypes>
struct invoke_result : detail::invoke_result<void, F, ArgTypes...> {};
```
### Notes
As formulated in C++11, the behavior of `std::result_of` is undefined when `INVOKE(std::declval<F>(), std::declval<ArgTypes>()...)` is ill-formed (e.g. when F is not a callable type at all). C++14 changes that to a [SFINAE](../language/sfinae "cpp/language/sfinae") (when F is not callable, `std::result_of<F(ArgTypes...)>` simply doesn't have the `type` member).
The motivation behind `std::result_of` is to determine the result of invoking a [Callable](../named_req/callable "cpp/named req/Callable"), in particular if that result type is different for different sets of arguments.
`F(Args...)` is a function type with `Args...` being the argument types and `F` being the return type. As such, `std::result_of` suffers from several quirks that led to its deprecation in favor of `std::invoke_result` in C++17:
* `F` cannot be a function type or an array type (but can be a reference to them);
* if any of the `Args` has type "array of `T`" or a function type `T`, it is automatically adjusted to `T*`;
* neither `F` nor any of `Args...` can be an abstract class type;
* if any of `Args...` has a top-level cv-qualifier, it is discarded;
* none of `Args...` may be of type `void`.
To avoid these quirks, `result_of` is often used with reference types as `F` and `Args...`. For example:
```
template<class F, class... Args>
std::result_of_t<F&&(Args&&...)> // instead of std::result_of_t<F(Args...)>, which is wrong
my_invoke(F&& f, Args&&... args) {
/* implementation */
}
```
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_result_of_sfinae`](../feature_test#Library_features "cpp/feature test") |
### Examples
```
#include <type_traits>
#include <iostream>
struct S {
double operator()(char, int&);
float operator()(int) { return 1.0;}
};
template<class T>
typename std::result_of<T(int)>::type f(T& t)
{
std::cout << "overload of f for callable T\n";
return t(0);
}
template<class T, class U>
int f(U u)
{
std::cout << "overload of f for non-callable T\n";
return u;
}
int main()
{
// the result of invoking S with char and int& arguments is double
std::result_of<S(char, int&)>::type d = 3.14; // d has type double
static_assert(std::is_same<decltype(d), double>::value, "");
// std::invoke_result uses different syntax (no parentheses)
std::invoke_result<S,char,int&>::type b = 3.14;
static_assert(std::is_same<decltype(b), double>::value, "");
// the result of invoking S with int argument is float
std::result_of<S(int)>::type x = 3.14; // x has type float
static_assert(std::is_same<decltype(x), float>::value, "");
// result_of can be used with a pointer to member function as follows
struct C { double Func(char, int&); };
std::result_of<decltype(&C::Func)(C, char, int&)>::type g = 3.14;
static_assert(std::is_same<decltype(g), double>::value, "");
f<C>(1); // may fail to compile in C++11; calls the non-callable overload in C++14
}
```
Output:
```
overload of f for non-callable T
```
### See also
| | |
| --- | --- |
| [invokeinvoke\_r](../utility/functional/invoke "cpp/utility/functional/invoke")
(C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) |
| [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](is_invocable "cpp/types/is invocable")
(C++17) | checks if a type can be invoked (as if by `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`) with the given argument types (class template) |
| [declval](../utility/declval "cpp/utility/declval")
(C++11) | obtains a reference to its argument for use in unevaluated context (function template) |
cpp std::is_pointer_interconvertible_with_class std::is\_pointer\_interconvertible\_with\_class
===============================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template<class S, class M>
constexpr bool is_pointer_interconvertible_with_class( M S::* mp ) noexcept;
```
| | (since C++20) |
Given an object `s` of type `S`, determines whether `s.*mp` refers to a subobject of `s` and `s` is [pointer-interconvertible](../language/static_cast#pointer-interconvertible "cpp/language/static cast") with its subobject `s.*mp`. The program is ill-formed if `S` is not a [complete type](../language/type#Incomplete_type "cpp/language/type").
If `S` is not a [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"), or `M` is not an object type, or `mp` is equal to `nullptr`, the result is always `false`.
### Parameters
| | | |
| --- | --- | --- |
| mp | - | a pointer-to-member to detect |
### Return value
`true` if `s.*mp` refers a subobject of `s` and `s` is pointer-interconvertible with its subobject `s.*mp`, otherwise `false`, where `s` is an object of type `S`.
### Notes
The type of a pointer-to-member expression `&S::m` is not always `M S::*`, where `m` is of type `M`, because `m` may be a member inherited from a base class of `S`. The template arguments can be specified in order to avoid potentially surprising results.
If there is a value `mp` of type `M S::*` such that `std::is_pointer_interconvertible_with_class(mp) == true`, then `reinterpret_cast<M&>(s)` has well-defined result and it refers the same subobject as `s.*mp`, where `s` is a valid lvalue of type `S`.
On common platforms, the bit pattern of `mp` is all zero if `std::is_pointer_interconvertible_with_class(mp) == true`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_pointer_interconvertible`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <type_traits>
#include <iostream>
struct Foo { int x; };
struct Bar { int y; };
struct Baz : Foo, Bar {}; // not standard-layout
int main()
{
std::cout << std::boolalpha
<< std::is_same_v<decltype(&Baz::x), int Baz::*> << '\n'
<< std::is_pointer_interconvertible_with_class(&Baz::x) << '\n'
<< std::is_pointer_interconvertible_with_class<Baz, int>(&Baz::x) << '\n';
}
```
Output:
```
false
true
false
```
### See also
| | |
| --- | --- |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
| [is\_member\_object\_pointer](is_member_object_pointer "cpp/types/is member object pointer")
(C++11) | checks if a type is a pointer to a non-static member object (class template) |
cpp std::extent std::extent
===========
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, unsigned N = 0>
struct extent;
```
| | (since C++11) |
If `T` is an array type, provides the member constant `value` equal to the number of elements along the `N`th dimension of the array, if `N` is in `[0, std::rank<T>::value)`. For any other type, or if `T` is an array of unknown bound along its first dimension and `N` is 0, `value` is 0.
The behavior of a program that adds specializations for `extent` or `extent_v` (since C++17) is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, unsigned N = 0 >
inline constexpr std::size_t extent_v = extent<T, N>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | the number of elements along the `N`th dimension of `T` (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `std::size_t` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` |
### Possible implementation
| |
| --- |
|
```
template<class T, unsigned N = 0>
struct extent : std::integral_constant<std::size_t, 0> {};
template<class T>
struct extent<T[], 0> : std::integral_constant<std::size_t, 0> {};
template<class T, unsigned N>
struct extent<T[], N> : std::extent<T, N-1> {};
template<class T, std::size_t I>
struct extent<T[I], 0> : std::integral_constant<std::size_t, I> {};
template<class T, std::size_t I, unsigned N>
struct extent<T[I], N> : std::extent<T, N-1> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::extent<int[3]>::value << '\n'; //< default dimension is 0
std::cout << std::extent<int[3][4], 0>::value << '\n';
std::cout << std::extent<int[3][4], 1>::value << '\n';
std::cout << std::extent<int[3][4], 2>::value << '\n';
std::cout << std::extent<int[]>::value << '\n';
const auto ext = std::extent<int[9]>{};
std::cout << ext << '\n'; //< implicit conversion to std::size_t
const int ints[] = {1,2,3,4};
std::cout << std::extent<decltype(ints)>::value << '\n'; //< array size
[[maybe_unused]] int ary[][3]={ {1,2,3} };
// ary[0] is type of reference of 'int[3]', so, extent
// cannot calculate correctly and return 0
static_assert(std::is_same_v<decltype(ary[0]), int(&)[3]>);
std::cout << std::extent<decltype(ary[0])>::value << '\n';
// removing reference will give correct extent value 3
std::cout << std::extent<std::remove_cvref_t<decltype(ary[0])>>::value << '\n';
}
```
Output:
```
3
3
4
0
0
9
4
0
3
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [rank](rank "cpp/types/rank")
(C++11) | obtains the number of dimensions of an array type (class template) |
| [remove\_extent](remove_extent "cpp/types/remove extent")
(C++11) | removes one extent from the given array type (class template) |
| [remove\_all\_extents](remove_all_extents "cpp/types/remove all extents")
(C++11) | removes all extents from the given array type (class template) |
cpp std::is_union std::is\_union
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_union;
```
| | (since C++11) |
Checks whether `T` is a [union type](../language/union "cpp/language/union"). Provides the member constant `value`, which is equal to `true` if `T` is a union type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_union` or `is_union_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_union_v = is_union<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a union type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Example
```
#include <iostream>
#include <type_traits>
struct A {};
typedef union {
int a;
float b;
} B;
struct C {
B d;
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_union<A>::value << '\n';
std::cout << std::is_union<B>::value << '\n';
std::cout << std::is_union<C>::value << '\n';
std::cout << std::is_union<int>::value << '\n';
}
```
Output:
```
false
true
false
false
```
### See also
| | |
| --- | --- |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| programming_docs |
cpp std::aligned_storage std::aligned\_storage
=====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< std::size_t Len, std::size_t Align = /*default-alignment*/ >
struct aligned_storage;
```
| | (since C++11) (deprecated in C++23) |
Provides the nested type *`type`*, which is a [trivial](../named_req/trivialtype "cpp/named req/TrivialType") [standard-layout](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") type suitable for use as uninitialized storage for any object whose size is at most `Len` and whose [alignment requirement](../language/object#Alignment "cpp/language/object") is a divisor of `Align`.
The default value of `Align` is the most stringent (the largest) alignment requirement for any object whose size is at most `Len`. If the default value is not used, `Align` must be the value of `alignof(T)` for some type `T`, or the behavior is undefined.
The behavior is undefined if `Len == 0`.
It is implementation-defined whether any [extended alignment](../language/object#Alignment "cpp/language/object") is supported.
The behavior of a program that adds specializations for `aligned_storage` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | a trivial and standard-layout type of at least size `Len` with alignment requirement `Align` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< std::size_t Len, std::size_t Align = /*default-alignment*/ >
using aligned_storage_t = typename aligned_storage<Len, Align>::type;
```
| | (since C++14) (deprecated in C++23) |
### Notes
The type defined by `std::aligned_storage<>::type` can be used to create uninitialized memory blocks suitable to hold the objects of given type, optionally aligned stricter than their natural alignment requirement, for example on a cache or page boundary.
As with any other uninitialized storage, the objects are created using [placement new](../language/new "cpp/language/new") and destroyed with explicit destructor calls.
### Possible implementation
Except for default argument, aligned\_storage is expressible in terms of alignas:
| |
| --- |
|
```
template<std::size_t Len, std::size_t Align = /* default alignment not implemented */>
struct aligned_storage {
struct type {
alignas(Align) unsigned char data[Len];
};
};
```
|
### Example
A primitive static vector class, demonstrating creation, access, and destruction of objects in aligned storage.
```
#include <new>
#include <iostream>
#include <type_traits>
#include <string>
template<class T, std::size_t N>
class static_vector
{
// properly aligned uninitialized storage for N T's
std::aligned_storage_t<sizeof(T), alignof(T)> data[N];
std::size_t m_size = 0;
public:
// Create an object in aligned storage
template<typename ...Args> void emplace_back(Args&&... args)
{
if( m_size >= N ) // possible error handling
throw std::bad_alloc{};
// construct value in memory of aligned storage
// using inplace operator new
::new(&data[m_size]) T(std::forward<Args>(args)...);
++m_size;
}
// Access an object in aligned storage
const T& operator[](std::size_t pos) const
{
// Note: std::launder is needed after the change of object model in P0137R1
return *std::launder(reinterpret_cast<const T*>(&data[pos]));
}
// Destroy objects from aligned storage
~static_vector()
{
for(std::size_t pos = 0; pos < m_size; ++pos) {
// Note: std::launder is needed after the change of object model in P0137R1
std::destroy_at(std::launder(reinterpret_cast<T*>(&data[pos])));
}
}
};
int main()
{
static_vector<std::string, 10> v1;
v1.emplace_back(5, '*');
v1.emplace_back(10, '*');
std::cout << v1[0] << '\n' << v1[1] << '\n';
}
```
Output:
```
*****
**********
```
### See also
| | |
| --- | --- |
| [`alignas` specifier](../language/alignas "cpp/language/alignas")(C++11) | specifies that the storage for the variable should be aligned by specific amount |
| [alignment\_of](alignment_of "cpp/types/alignment of")
(C++11) | obtains the type's alignment requirements (class template) |
| [aligned\_alloc](../memory/c/aligned_alloc "cpp/memory/c/aligned alloc")
(C++17) | allocates aligned memory (function) |
| [aligned\_union](aligned_union "cpp/types/aligned union")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for all given types (class template) |
| [max\_align\_t](max_align_t "cpp/types/max align t")
(C++11) | trivial type with alignment requirement as great as any other scalar type (typedef) |
| [launder](../utility/launder "cpp/utility/launder")
(C++17) | pointer optimization barrier (function template) |
cpp std::add_lvalue_reference, std::add_rvalue_reference std::add\_lvalue\_reference, std::add\_rvalue\_reference
========================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct add_lvalue_reference;
```
| (1) | (since C++11) |
|
```
template< class T >
struct add_rvalue_reference;
```
| (2) | (since C++11) |
Creates a lvalue or rvalue reference type of `T`.
1) If `T` is a function type that has no cv- or ref- qualifier or an object type, provides a member typedef `type` which is `T&`. If `T` is an rvalue reference to some type `U`, then `type` is `U&`. Otherwise, `type` is `T`.
2) If `T` is a function type that has no cv- or ref- qualifier or an object type, provides a member typedef `type` which is `T&&`, otherwise `type` is `T`. The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | reference to `T`, or `T` if not allowed |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using add_lvalue_reference_t = typename add_lvalue_reference<T>::type;
```
| | (since C++14) |
|
```
template< class T >
using add_rvalue_reference_t = typename add_rvalue_reference<T>::type;
```
| | (since C++14) |
### Notes
These type transformations honor reference collapse rules:
* `std::add_lvalue_reference<T&>::type` is `T&`
* `std::add_lvalue_reference<T&&>::type` is `T&`
* `std::add_rvalue_reference<T&>::type` is `T&`
* `std::add_rvalue_reference<T&&>::type` is `T&&`
The major difference to directly using `T&` is that `std::add_lvalue_reference<void>::type` is `void`, while `void&` leads to a compilation error.
### Possible implementation
| |
| --- |
|
```
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T> // Note that `cv void&` is a substitution failure
auto try_add_lvalue_reference(int) -> type_identity<T&>;
template <class T> // Handle T = cv void case
auto try_add_lvalue_reference(...) -> type_identity<T>;
template <class T>
auto try_add_rvalue_reference(int) -> type_identity<T&&>;
template <class T>
auto try_add_rvalue_reference(...) -> type_identity<T>;
} // namespace detail
template <class T>
struct add_lvalue_reference : decltype(detail::try_add_lvalue_reference<T>(0)) {};
template <class T>
struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference<T>(0)) {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main() {
using nonref = int;
using lref = typename std::add_lvalue_reference<nonref>::type;
using rref = typename std::add_rvalue_reference<nonref>::type;
using voidref = std::add_lvalue_reference_t<void>;
std::cout << std::boolalpha;
std::cout << std::is_lvalue_reference<nonref>::value << '\n';
std::cout << std::is_lvalue_reference<lref>::value << '\n';
std::cout << std::is_rvalue_reference<rref>::value << '\n';
std::cout << std::is_reference_v<voidref> << '\n';
}
```
Output:
```
false
true
true
false
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2101](https://cplusplus.github.io/LWG/issue2101) | C++11 | These transformation traits were requiredto produce reference to cv-/ref-qualified function types. | Produce cv-/ref-qualified function types themselves. |
### See also
| | |
| --- | --- |
| [is\_reference](is_reference "cpp/types/is reference")
(C++11) | checks if a type is either a *lvalue reference* or *rvalue reference* (class template) |
| [remove\_reference](remove_reference "cpp/types/remove reference")
(C++11) | removes a reference from the given type (class template) |
| [remove\_cvref](remove_cvref "cpp/types/remove cvref")
(C++20) | combines `[std::remove\_cv](remove_cv "cpp/types/remove cv")` and `[std::remove\_reference](remove_reference "cpp/types/remove reference")` (class template) |
cpp std::rank std::rank
=========
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct rank;
```
| | (since C++11) |
If `T` is an array type, provides the member constant `value` equal to the number of dimensions of the array. For any other type, `value` is 0.
The behavior of a program that adds specializations for `rank` or `rank_v` (since C++17) is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr std::size_t rank_v = rank<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | the number of dimensions of `T` or zero (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `std::size_t` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct rank : public std::integral_constant<std::size_t, 0> {};
template<class T>
struct rank<T[]> : public std::integral_constant<std::size_t, rank<T>::value + 1> {};
template<class T, std::size_t N>
struct rank<T[N]> : public std::integral_constant<std::size_t, rank<T>::value + 1> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::rank<int>{} << "\n\n";
std::cout << std::rank<int[5]>{} << '\n';
std::cout << std::rank<int[5][5]>{} << '\n';
std::cout << std::rank<int[][5][5]>{} << '\n';
[[maybe_unused]] int ary[][3]={ {1,2,3} };
// The reason of rank of "ary[0]" is calculated as 0
std::cout << std::rank<decltype(ary[0])>::value << '\n';
// is that rank cannot deal with reference type. i.e. int(&)[3]
static_assert(std::is_same_v<decltype(ary[0]), int(&)[3]>);
// The solution is to remove reference type
std::cout << std::rank<std::remove_cvref_t<decltype(ary[0])>>::value << '\n';
}
```
Output:
```
0
1
2
3
0
1
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
| [remove\_extent](remove_extent "cpp/types/remove extent")
(C++11) | removes one extent from the given array type (class template) |
| [remove\_all\_extents](remove_all_extents "cpp/types/remove all extents")
(C++11) | removes all extents from the given array type (class template) |
cpp std::is_default_constructible, std::is_trivially_default_constructible, std::is_nothrow_default_constructible std::is\_default\_constructible, std::is\_trivially\_default\_constructible, std::is\_nothrow\_default\_constructible
=====================================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_default_constructible;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_default_constructible;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_default_constructible;
```
| (3) | (since C++11) |
1) Provides the member constant `value` equal to `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T>::value`.
2) Provides the member constant `value` equal to `[std::is\_trivially\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T>::value`.
3) Provides the member constant `value` equal to `[std::is\_nothrow\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T>::value`. `T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_default_constructible_v =
is_default_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_default_constructible_v =
is_trivially_default_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_default_constructible_v =
is_nothrow_default_constructible<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is default-constructible , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T>
struct is_default_constructible : std::is_constructible<T> {};
template< class T>
struct is_trivially_default_constructible : std::is_trivially_constructible<T> {};
template< class T>
struct is_nothrow_default_constructible : std::is_nothrow_constructible<T> {};
```
|
### Notes
In many implementations, `is_nothrow_default_constructible` also checks if the destructor throws because it is effectively `noexcept(T())`. Same applies to `is_trivially_default_constructible`, which, in these implementations, also requires that the destructor is trivial: [GCC bug 51452](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452), [LWG issue 2116](https://cplusplus.github.io/LWG/issue2116).
`std::is_default_constructible<T>` does not test that `T x;` would compile; it attempts [direct-initialization](../language/direct_initialization "cpp/language/direct initialization") with an empty argument list (see `[std::is\_constructible](is_constructible "cpp/types/is constructible")`). Thus, `std::is_default_constructible_v<const int>` and `std::is_default_constructible_v<const int[10]>` are `true`.
### Example
```
#include <iostream>
#include <type_traits>
struct Ex1 {
std::string str; // member has a non-trivial default ctor
};
struct Ex2 {
int n;
Ex2() = default; // trivial and non-throwing
};
int main() {
std::cout << std::boolalpha << "Ex1 is default-constructible? "
<< std::is_default_constructible<Ex1>::value << '\n'
<< "Ex1 is trivially default-constructible? "
<< std::is_trivially_default_constructible<Ex1>::value << '\n'
<< "Ex2 is trivially default-constructible? "
<< std::is_trivially_default_constructible<Ex2>::value << '\n'
<< "Ex2 is nothrow default-constructible? "
<< std::is_nothrow_default_constructible<Ex2>::value << '\n';
}
```
Output:
```
Ex1 is default-constructible? true
Ex1 is trivially default-constructible? false
Ex2 is trivially default-constructible? true
Ex2 is nothrow default-constructible? true
```
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
| [is\_copy\_constructibleis\_trivially\_copy\_constructibleis\_nothrow\_copy\_constructible](is_copy_constructible "cpp/types/is copy constructible")
(C++11)(C++11)(C++11) | checks if a type has a copy constructor (class template) |
| [is\_move\_constructibleis\_trivially\_move\_constructibleis\_nothrow\_move\_constructible](is_move_constructible "cpp/types/is move constructible")
(C++11)(C++11)(C++11) | checks if a type can be constructed from an rvalue reference (class template) |
| [default\_initializable](../concepts/default_initializable "cpp/concepts/default initializable")
(C++20) | specifies that an object of a type can be default constructed (concept) |
cpp std::remove_cvref std::remove\_cvref
==================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_cvref;
```
| | (since C++20) |
If the type `T` is a reference type, provides the member typedef `type` which is the type referred to by `T` with its topmost cv-qualifiers removed. Otherwise `type` is `T` with its topmost cv-qualifiers removed.
The behavior of a program that adds specializations for `remove_cvref` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type referred by `T` or `T` itself if it is not a reference, with top-level cv-qualifiers removed |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_cvref_t = typename remove_cvref<T>::type;
```
| | (since C++20) |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct remove_cvref {
typedef std::remove_cv_t<std::remove_reference_t<T>> type;
};
```
|
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_remove_cvref`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha
<< std::is_same_v<std::remove_cvref_t<int>, int> << '\n'
<< std::is_same_v<std::remove_cvref_t<int&>, int> << '\n'
<< std::is_same_v<std::remove_cvref_t<int&&>, int> << '\n'
<< std::is_same_v<std::remove_cvref_t<const int&>, int> << '\n'
<< std::is_same_v<std::remove_cvref_t<const int[2]>, int[2]> << '\n'
<< std::is_same_v<std::remove_cvref_t<const int(&)[2]>, int[2]> << '\n'
<< std::is_same_v<std::remove_cvref_t<int(int)>, int(int)> << '\n';
}
```
Output:
```
true
true
true
true
true
true
true
```
### See also
| | |
| --- | --- |
| [remove\_cvremove\_constremove\_volatile](remove_cv "cpp/types/remove cv")
(C++11)(C++11)(C++11) | removes `const` or/and `volatile` specifiers from the given type (class template) |
| [remove\_reference](remove_reference "cpp/types/remove reference")
(C++11) | removes a reference from the given type (class template) |
| [decay](decay "cpp/types/decay")
(C++11) | applies type transformations as when passing a function argument by value (class template) |
| programming_docs |
cpp std::remove_extent std::remove\_extent
===================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_extent;
```
| | (since C++11) |
If `T` is an array of some type `X`, provides the member typedef `type` equal to `X`, otherwise `type` is `T`. Note that if T is a multidimensional array, only the first dimension is removed.
The behavior of a program that adds specializations for `remove_extent` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type of the element of `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_extent_t = typename remove_extent<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct remove_extent { typedef T type; };
template<class T>
struct remove_extent<T[]> { typedef T type; };
template<class T, std::size_t N>
struct remove_extent<T[N]> { typedef T type; };
```
|
### Example
```
#include <iostream>
#include <iterator>
#include <algorithm>
#include <type_traits>
template<class A>
typename std::enable_if< std::rank<A>::value == 1 >::type
print_1d(const A& a)
{
copy(a, a+std::extent<A>::value,
std::ostream_iterator<typename std::remove_extent<A>::type>(std::cout, " "));
std::cout << '\n';
}
int main()
{
int a[][3] = {{1,2,3},{4,5,6}};
// print_1d(a); // compile-time error
print_1d(a[1]);
}
```
Output:
```
4 5 6
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [rank](rank "cpp/types/rank")
(C++11) | obtains the number of dimensions of an array type (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
| [remove\_all\_extents](remove_all_extents "cpp/types/remove all extents")
(C++11) | removes all extents from the given array type (class template) |
cpp std::byte std::byte
=========
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
|
```
enum class byte : unsigned char {} ;
```
| | (since C++17) |
`std::byte` is a distinct type that implements the concept of byte as specified in the C++ language definition.
Like `char` and `unsigned char`, it can be used to access raw memory occupied by other objects ([object representation](../language/object "cpp/language/object")), but unlike those types, it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and the only operators defined for it are the bitwise ones.
### Non-member functions
std::to\_integer
-----------------
| | | |
| --- | --- | --- |
|
```
template <class IntegerType>
constexpr IntegerType to_integer( std::byte b ) noexcept;
```
| | (since C++17) |
Equivalent to: `return IntegerType(b);` This overload participates in overload resolution only if `[std::is\_integral\_v](http://en.cppreference.com/w/cpp/types/is_integral)<IntegerType>` is true.
std::operator<<=,operator>>=
-----------------------------
| | | |
| --- | --- | --- |
|
```
template <class IntegerType>
constexpr std::byte& operator<<=( std::byte& b, IntegerType shift ) noexcept;
```
| (1) | (since C++17) |
|
```
template <class IntegerType>
constexpr std::byte& operator>>=( std::byte& b, IntegerType shift ) noexcept;
```
| (2) | (since C++17) |
1) Equivalent to: `return b = b << shift;` This overload participates in overload resolution only if `[std::is\_integral\_v](http://en.cppreference.com/w/cpp/types/is_integral)<IntegerType>` is true.
2) Equivalent to: `return b = b >> shift;` This overload participates in overload resolution only if `[std::is\_integral\_v](http://en.cppreference.com/w/cpp/types/is_integral)<IntegerType>` is true.
std::operator<<,operator>>
---------------------------
| | | |
| --- | --- | --- |
|
```
template <class IntegerType>
constexpr std::byte operator <<( std::byte b, IntegerType shift ) noexcept;
```
| (1) | (since C++17) |
|
```
template <class IntegerType>
constexpr std::byte operator >>( std::byte b, IntegerType shift ) noexcept;
```
| (2) | (since C++17) |
1) Equivalent to: `return std::byte(static_cast<unsigned int>(b) << shift);` This overload participates in overload resolution only if `[std::is\_integral\_v](http://en.cppreference.com/w/cpp/types/is_integral)<IntegerType>` is true.
2) Equivalent to: `return std::byte(static_cast<unsigned int>(b) >> shift);` This overload participates in overload resolution only if `[std::is\_integral\_v](http://en.cppreference.com/w/cpp/types/is_integral)<IntegerType>` is true.
std::operator|=,operator&=,operator^=
--------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr std::byte& operator|=( std::byte& l, std::byte r ) noexcept;
```
| (1) | (since C++17) |
|
```
constexpr std::byte& operator&=( std::byte& l, std::byte r ) noexcept;
```
| (2) | (since C++17) |
|
```
constexpr std::byte& operator^=( std::byte& l, std::byte r ) noexcept;
```
| (3) | (since C++17) |
1) Equivalent to: `return l = l | r;`.
2) Equivalent to: `return l = l & r;`.
3) Equivalent to: `return l = l ^ r;`.
std::operator|,operator&,operator^,operator~
---------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr std::byte operator|( std::byte l, std::byte r ) noexcept;
```
| (1) | (since C++17) |
|
```
constexpr std::byte operator&( std::byte l, std::byte r ) noexcept;
```
| (2) | (since C++17) |
|
```
constexpr std::byte operator^( std::byte l, std::byte r ) noexcept;
```
| (3) | (since C++17) |
|
```
constexpr std::byte operator~( std::byte b ) noexcept;
```
| (4) | (since C++17) |
1) Equivalent to: `return std::byte(static_cast<unsigned int>(l) | static_cast<unsigned int>(r));`.
2) Equivalent to: `return std::byte(static_cast<unsigned int>(l) & static_cast<unsigned int>(r));`.
3) Equivalent to: `return std::byte(static_cast<unsigned int>(l) ^ static_cast<unsigned int>(r));`.
4) Equivalent to: `return std::byte(~static_cast<unsigned int>(b));`
### Notes
A numeric value `n` can be converted to a byte value using `std::byte{n}`, due to C++17 [relaxed enum class initialization](../language/enum#enum_relaxed_init_cpp17 "cpp/language/enum") rules.
A byte can be converted to a numeric value (such as to produce an integer hash of an object) using [`std::to_integer`](#Non-member_functions).
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_byte`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <cstddef>
#include <bitset>
std::ostream& operator<< (std::ostream& os, std::byte b) {
return os << std::bitset<8>(std::to_integer<int>(b));
}
int main()
{
std::byte b{42};
std::cout << "1. " << b << '\n';
// b *= 2 compilation error
b <<= 1;
std::cout << "2. " << b << '\n';
b >>= 1;
std::cout << "3. " << b << '\n';
std::cout << "4. " << (b << 1) << '\n';
std::cout << "5. " << (b >> 1) << '\n';
b |= std::byte{0b11110000};
std::cout << "6. " << b << '\n';
b &= std::byte{0b11110000};
std::cout << "7. " << b << '\n';
b ^= std::byte{0b11111111};
std::cout << "8. " << b << '\n';
}
```
Output:
```
1. 00101010
2. 01010100
3. 00101010
4. 01010100
5. 00010101
6. 11111010
7. 11110000
8. 00001111
```
cpp std::is_pointer_interconvertible_base_of std::is\_pointer\_interconvertible\_base\_of
============================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class Base, class Derived >
struct is_pointer_interconvertible_base_of;
```
| | (since C++20) |
If `Derived` is unambiguously derived from `Base` and every `Derived` object is [pointer-interconvertible](../language/static_cast#pointer-interconvertible "cpp/language/static cast") with its `Base` subobject, or if both are the same non-union class (in both cases ignoring cv-qualification), provides the member constant `value` equal to `true`. Otherwise `value` is `false`.
If both `Base` and `Derived` are non-union class types, and they are not the same type (ignoring cv-qualification), `Derived` shall be a [complete type](../language/incomplete_type "cpp/language/incomplete type"); otherwise the behavior is undefined.
The behavior of a program that adds specializations for `is_pointer_interconvertible_base_of` or `is_pointer_interconvertible_base_of_v` is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class Base, class Derived >
inline constexpr bool is_pointer_interconvertible_base_of_v =
is_pointer_interconvertible_base_of<Base, Derived>::value;
```
| | (since C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `Derived` is unambiguously derived from `Base` and every `Derived` object is [pointer-interconvertible](../language/static_cast#pointer-interconvertible "cpp/language/static cast") with its `Base` subobject, or if both are the same non-union class (in both cases ignoring cv-qualification), `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
`std::is_pointer_interconvertible_base_of_v<T, U>` may be `true` even if `T` is a private or protected base class of `U`.
Let.
* `U` be a complete object type,
* `T` be a complete object type with cv-qualification not less than `U`,
* `u` be any valid lvalue of `U`,
`reinterpret_cast<T&>(u)` always has well-defined result if `std::is_pointer_interconvertible_base_of_v<T, U>` is `true`.
If `T` and `U` are not the same type (ignoring cv-qualification) and `T` is a pointer-interconvertible base class of `U`, then both `[std::is\_standard\_layout\_v](http://en.cppreference.com/w/cpp/types/is_standard_layout)<T>` and `[std::is\_standard\_layout\_v](http://en.cppreference.com/w/cpp/types/is_standard_layout)<U>` are `true`.
If `T` is standard layout class type, then all base classes of `T` (if any) are pointer-interconvertible base class of `T`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_pointer_interconvertible`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
struct Foo {};
struct Bar {};
class Baz : Foo, public Bar {
int x;
};
class NonStdLayout : public Baz {
int y;
};
int main()
{
std::cout << std::boolalpha
<< std::is_pointer_interconvertible_base_of_v<Bar, Baz> << '\n'
<< std::is_pointer_interconvertible_base_of_v<Foo, Baz> << '\n'
<< std::is_pointer_interconvertible_base_of_v<Baz, NonStdLayout> << '\n'
<< std::is_pointer_interconvertible_base_of_v<NonStdLayout, NonStdLayout> << '\n';
}
```
Output:
```
true
true
false
true
```
### See also
| | |
| --- | --- |
| [is\_base\_of](is_base_of "cpp/types/is base of")
(C++11) | checks if a type is derived from the other type (class template) |
| [is\_empty](is_empty "cpp/types/is empty")
(C++11) | checks if a type is a class (but not union) type and has no non-static data members (class template) |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
cpp std::is_polymorphic std::is\_polymorphic
====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_polymorphic;
```
| | (since C++11) |
If `T` is a [polymorphic class](../language/object#Polymorphic_objects "cpp/language/object") (that is, a non-union class that declares or inherits at least one virtual function), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
If `T` is a non-union class type, `T` shall be a complete type; otherwise, the behavior is undefined.
The behavior of a program that adds specializations for `is_polymorphic` or `is_polymorphic_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_polymorphic_v = is_polymorphic<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a [polymorphic](../language/object#Polymorphic_objects "cpp/language/object") class type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
namespace detail {
template <class T>
std::true_type detect_is_polymorphic(
decltype(dynamic_cast<const volatile void*>(static_cast<T*>(nullptr)))
);
template <class T>
std::false_type detect_is_polymorphic(...);
} // namespace detail
template <class T>
struct is_polymorphic : decltype(detail::detect_is_polymorphic<T>(nullptr)) {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
virtual void foo();
};
struct C : B {};
struct D {
virtual ~D() = default;
};
int main()
{
std::cout << std::boolalpha
<< std::is_polymorphic<A>::value << ' '
<< std::is_polymorphic<B>::value << ' '
<< std::is_polymorphic<C>::value << ' '
<< std::is_polymorphic<D>::value << '\n';
}
```
Output:
```
false true true true
```
### See also
| | |
| --- | --- |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| [is\_abstract](is_abstract "cpp/types/is abstract")
(C++11) | checks if a type is an abstract class type (class template) |
| [has\_virtual\_destructor](has_virtual_destructor "cpp/types/has virtual destructor")
(C++11) | checks if a type has a virtual destructor (class template) |
cpp std::size_t std::size\_t
============
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
| Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | |
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` | | |
| Defined in header `[<ctime>](../header/ctime "cpp/header/ctime")` | | |
| Defined in header `[<cuchar>](../header/cuchar "cpp/header/cuchar")` | | (since C++17) |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` | | |
|
```
typedef /*implementation-defined*/ size_t;
```
| | |
`std::size_t` is the unsigned integer type of the result of the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator as well as the [`sizeof...`](../language/sizeof... "cpp/language/sizeof...") operator and the [`alignof`](../language/alignof "cpp/language/alignof") operator (since C++11).
| | |
| --- | --- |
| The bit width of `std::size_t` is not less than 16. | (since C++11) |
### Notes
`std::size_t` can store the maximum size of a theoretically possible object of any type (including array). A type whose size cannot be represented by `std::size_t` is ill-formed. (since C++14) On many platforms (an exception is systems with segmented addressing) `std::size_t` can safely store the value of any non-member pointer, in which case it is synonymous with `[std::uintptr\_t](integer "cpp/types/integer")`.
`std::size_t` is commonly used for array indexing and loop counting. Programs that use other types, such as `unsigned int`, for array indexing may fail on, e.g. 64-bit systems when the index exceeds `[UINT\_MAX](climits "cpp/types/climits")` or if it relies on 32-bit modular arithmetic.
When indexing C++ containers, such as `[std::string](../string/basic_string "cpp/string/basic string")`, `[std::vector](../container/vector "cpp/container/vector")`, etc, the appropriate type is the member typedef `size_type` provided by such containers. It is usually defined as a synonym for `std::size_t`.
| | |
| --- | --- |
| The [integer literal suffix](../language/integer_literal "cpp/language/integer literal") for `std::size_t` is `uz` (or `UZ`). | (since C++23) |
### Example
```
#include <cstddef>
#include <iostream>
#include <array>
int main()
{
std::array<std::size_t, 10> a;
// Example with C++23 size_t literal
for (auto i = 0uz; i != a.size(); ++i)
std::cout << (a[i] = i) << ' ';
std::cout << '\n';
// Example of decrementing loop
for (std::size_t i = a.size(); i--;)
std::cout << a[i] << ' ';
// Note the naive decrementing loop:
// for (std::size_t i = a.size() - 1; i >= 0; --i) ...
// is an infinite loop, because unsigned numbers are always non-negative
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
```
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 6.8.3 Compound types [basic.compound] (p: 75-76)
+ 7.6.2.5 Sizeof [expr.sizeof] (p: 129-130)
+ 7.6.2.6 Alignof [expr.alignof] (p: 130)
+ 17.2.4 Sizes, alignments, and offsets [support.types.layout] (p: 507-508)
* C++17 standard (ISO/IEC 14882:2017):
+ 6.9.2 Compound types [basic.compound] (p: 81-82)
+ 8.3.3 Sizeof [expr.sizeof] (p: 121-122)
+ 8.3.6 Alignof [expr.alignof] (p: 129)
+ 21.2.4 Sizes, alignments, and offsets [support.types.layout] (p: 479)
* C++14 standard (ISO/IEC 14882:2014):
+ 3.9.2 Compound types [basic.compound] (p: 73-74)
+ 5.3.3 Sizeof [expr.sizeof] (p: 109-110)
+ 5.3.6 Alignof [expr.alignof] (p: 116)
+ 18.2 Types [support.types] (p: 443-444)
* C++11 standard (ISO/IEC 14882:2011):
+ 5.3.3 Sizeof [expr.sizeof] (p: 111)
+ 5.3.6 Alignof [expr.alignof] (p: 116)
+ 18.2 Types [support.types] (p: 454-455)
* C++03 standard (ISO/IEC 14882:2003):
+ 5.3.3 Sizeof [expr.sizeof] (p: 79)
* C++98 standard (ISO/IEC 14882:1998):
+ 5.3.3 Sizeof [expr.sizeof] (p: 77)
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 1122](https://cplusplus.github.io/CWG/issues/1122.html) | C++98 | the definition of `size_t` was in the C standard (`<stddef.h>`) | it is implementation-defined |
### See also
| | |
| --- | --- |
| [ptrdiff\_t](ptrdiff_t "cpp/types/ptrdiff t") | signed integer type returned when subtracting two pointers (typedef) |
| [offsetof](offsetof "cpp/types/offsetof") | byte offset from the beginning of a standard-layout type to specified member (function macro) |
| [integer literals](../language/integer_literal "cpp/language/integer literal") | binary, (since C++14) decimal, octal, or hexadecimal numbers of integer type |
| [C documentation](https://en.cppreference.com/w/c/types/size_t "c/types/size t") for `size_t` |
| programming_docs |
cpp offsetof offsetof
========
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
|
```
#define offsetof(type, member) /*implementation-defined*/
```
| | |
The macro `offsetof` expands to an integral constant expression of type `[std::size\_t](size_t "cpp/types/size t")`, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.
Given an object `o` of type `type` and static storage duration, `o.member` shall be an lvalue constant expression that refers to a subobject of `o`. Otherwise, the behavior is undefined. Particularly, if `member` is a [static data member](../language/static "cpp/language/static"), a [bit-field](../language/bit_field "cpp/language/bit field"), or a [member function](../language/member_functions "cpp/language/member functions"), the behavior is undefined.
If `type` is not a [PODType](../named_req/podtype "cpp/named req/PODType") (until C++11)[standard layout type](../language/data_members#Standard-layout "cpp/language/data members") (since C++11), the behavior is undefined (until C++17)use of the `offsetof` macro is conditionally-supported (since C++17).
The expression `offsetof(type, member)` is never [type-dependent](../language/dependent_name#Dependent_types "cpp/language/dependent name") and it is value-dependent if and only if type is dependent.
### Exceptions
`offsetof` throws no exceptions.
| | |
| --- | --- |
| The expression `noexcept(offsetof(type, member))` always evaluates to `true`. | (since C++11) |
### Notes
| | |
| --- | --- |
| The offset of the first member of a standard-layout type is always zero ([empty-base optimization](../language/ebo "cpp/language/ebo") is mandatory). | (since C++11) |
`offsetof` cannot be implemented in standard C++ and requires compiler support: [GCC](https://github.com/gcc-mirror/gcc/blob/68ec60c4a377b532ec2d265ea542107c36b1d15c/gcc/ginclude/stddef.h#L406), [LLVM](https://github.com/llvm-mirror/clang/blob/release_70/lib/Headers/stddef.h#L120).
`member` is not restricted to a direct member. It can denote a subobject of a given member, such as an element of an array member. This is specified by C [DR 496](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_496).
It is specified in C23 that defining a new type in `offsetof` is undefined behavior, and such usage is only partially supported by some implementations in C++ modes: `offsetof(struct Foo { int a; }, a)` is supported by ICC and some old versions of GCC, while `offsetof(struct Foo { int a, b; }, a)` is rejected by all known implementations because of the comma in the definition of `Foo`.
### Example
```
#include <iostream>
#include <cstddef>
struct S {
char m0;
double m1;
short m2;
char m3;
// private: int z; // warning: 'S' is a non-standard-layout type
};
int main()
{
std::cout
<< "offset of char m0 = " << offsetof(S, m0) << '\n'
<< "offset of double m1 = " << offsetof(S, m1) << '\n'
<< "offset of short m2 = " << offsetof(S, m2) << '\n'
<< "offset of char m3 = " << offsetof(S, m3) << '\n';
}
```
Possible output:
```
offset of char m0 = 0
offset of double m1 = 8
offset of short m2 = 16
offset of char m3 = 18
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 273](https://cplusplus.github.io/CWG/issues/273.html) | C++98 | `offsetof` may not work if unary `operator&` is overloaded | required to work correctly even if `operator&` is overloaded |
### See also
| | |
| --- | --- |
| [size\_t](size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
| [C documentation](https://en.cppreference.com/w/c/types/offsetof "c/types/offsetof") for `offsetof` |
cpp NULL NULL
====
| Defined in header `[<clocale>](../header/clocale "cpp/header/clocale")` | | |
| --- | --- | --- |
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | |
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` | | |
| Defined in header `[<ctime>](../header/ctime "cpp/header/ctime")` | | |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` | | |
|
```
#define NULL /*implementation-defined*/
```
| | |
The macro `NULL` is an implementation-defined null pointer constant, which may be.
| | |
| --- | --- |
| an integral [constant expression](../language/constant_expression "cpp/language/constant expression") [rvalue](../language/value_category "cpp/language/value category") of integer type that evaluates to zero. | (until C++11) |
| an [integer literal](../language/integer_literal "cpp/language/integer literal") with value zero, or a prvalue of type `[std::nullptr\_t](nullptr_t "cpp/types/nullptr t")`. | (since C++11) |
A null pointer constant may be [implicitly converted](../language/implicit_cast "cpp/language/implicit cast") to any pointer and pointer to member type; such conversion results in the null pointer value of that type. If a null pointer constant has integer type, it may be converted to a prvalue of type `[std::nullptr\_t](nullptr_t "cpp/types/nullptr t")`.
### Possible implementation
| |
| --- |
|
```
#define NULL 0
//since C++11
#define NULL nullptr
```
|
### Notes
In C, the macro `NULL` may have the type `void*`, but that is not allowed in C++.
Some implementations define `NULL` as the compiler extension `__null` with following properties:
* `__null` is equivalent to a zero-valued integer literal (and thus compatible with the C++ standard) and has the same size as `void*`, e.g. it is equivalent to `0`/`0L` on ILP32/LP64 platforms respectively;
* conversion from `__null` to an arithmetic type, including the type of `__null` itself, may trigger a warning.
### Example
```
#include <cstddef>
#include <type_traits>
#include <iostream>
#include <typeinfo>
class S;
int main()
{
int* p = NULL;
int* p2 = static_cast<std::nullptr_t>(NULL);
void(*f)(int) = NULL;
int S::*mp = NULL;
void(S::*mfp)(int) = NULL;
auto nullvar = NULL; // a warning may be triggered when compiling with gcc/clang
std::cout << "The type of `nullvar` is " << typeid(nullvar).name() << '\n';
if constexpr(std::is_same_v<decltype(NULL), std::nullptr_t>) {
std::cout << "NULL implemented with type std::nullptr_t\n";
} else {
std::cout << "NULL implemented using an integral type\n";
}
[](...){}(p, p2, f, mp, mfp); //< suppresses "unused variable" warnings
}
```
Possible output:
```
The type of `nullvar` is long
NULL implemented using an integral type
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 903](https://cplusplus.github.io/CWG/issues/903.html) | C++11 | constant expressions with zero value such as 1-1 were allowed | only the literal zero is allowed |
### See also
| | |
| --- | --- |
| [`nullptr`](../language/nullptr "cpp/language/nullptr")(C++11) | the pointer literal which specifies a null pointer value |
| [nullptr\_t](nullptr_t "cpp/types/nullptr t")
(C++11) | the type of the null pointer literal [`nullptr`](../language/nullptr "cpp/language/nullptr") (typedef) |
| [C documentation](https://en.cppreference.com/w/c/types/NULL "c/types/NULL") for `NULL` |
cpp std::aligned_union std::aligned\_union
===================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< std::size_t Len, class... Types >
struct aligned_union;
```
| | (since C++11) (deprecated in C++23) |
Provides the nested type `type`, which is a [trivial](../named_req/trivialtype "cpp/named req/TrivialType") [standard-layout](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") type of a size and alignment suitable for use as uninitialized storage for an object of any of the types listed in `Types`. The size of the storage is at least `Len`. `std::aligned_union` also determines the strictest (largest) alignment requirement among all `Types` and makes it available as the constant `alignment_value`.
If `sizeof...(Types) == 0` or if any of the types in `Types` is not a complete object type, the behavior is undefined.
It is implementation-defined whether any [extended alignment](../language/object#Alignment "cpp/language/object") is supported.
The behavior of a program that adds specializations for `aligned_union` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | a trivial and standard-layout type suitable for storage of any type from `Types` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< std::size_t Len, class... Types >
using aligned_union_t = typename aligned_union<Len,Types...>::type;
```
| | (since C++14) (deprecated in C++23) |
### Member constants
| | |
| --- | --- |
| alignment\_value
[static] | the strictest alignment requirement of all `Types` (public static member constant) |
### Possible implementation
| |
| --- |
|
```
#include <algorithm>
template <std::size_t Len, class... Types>
struct aligned_union
{
static constexpr std::size_t alignment_value = std::max({alignof(Types)...});
struct type
{
alignas(alignment_value) char _s[std::max({Len, sizeof(Types)...})];
};
};
```
|
### Example
```
#include <type_traits>
#include <iostream>
#include <string>
int main()
{
std::cout
<< sizeof(std::aligned_union_t<0, char>) << ' ' // 1
<< sizeof(std::aligned_union_t<2, char>) << ' ' // 2
<< sizeof(std::aligned_union_t<2, char[3]>) << ' ' // 3 (!)
<< sizeof(std::aligned_union_t<3, char[4]>) << ' ' // 4
<< sizeof(std::aligned_union_t<1, char, int, double>) << ' ' // 8
<< sizeof(std::aligned_union_t<12, char, int, double>) << '\n'; // 16 (!)
using var_t = std::aligned_union<16, int, std::string>;
std::cout
<< "var_t::alignment_value = " << var_t::alignment_value << '\n'
<< "sizeof(var_t::type) = " << sizeof(var_t::type) << '\n';
var_t::type aligned_storage;
int* int_ptr = new(&aligned_storage) int(42); // placement new
std::cout << "*int_ptr = " << *int_ptr << '\n';
std::string* string_ptr = new(&aligned_storage) std::string("bar");
std::cout << "*string_ptr = " << *string_ptr << '\n';
*string_ptr = "baz";
std::cout << "*string_ptr = " << *string_ptr << '\n';
string_ptr->~basic_string();
}
```
Possible output:
```
1 2 3 4 8 16
var_t::alignment_value = 8
sizeof(var_t::type) = 32
*int_ptr = 42
*string_ptr = bar
*string_ptr = baz
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2979](https://cplusplus.github.io/LWG/issue2979) | C++11 | complete type wasn't required | requires complete types |
### See also
| | |
| --- | --- |
| [alignment\_of](alignment_of "cpp/types/alignment of")
(C++11) | obtains the type's alignment requirements (class template) |
| [aligned\_storage](aligned_storage "cpp/types/aligned storage")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) |
cpp std::is_copy_assignable, std::is_trivially_copy_assignable, std::is_nothrow_copy_assignable std::is\_copy\_assignable, std::is\_trivially\_copy\_assignable, std::is\_nothrow\_copy\_assignable
===================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_copy_assignable;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_copy_assignable;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_copy_assignable;
```
| (3) | (since C++11) |
1) If `T` is not a referenceable type (i.e., possibly cv-qualified `void` or a function type with a *cv-qualifier-seq* or a *ref-qualifier*), provides a member constant `value` equal to `false`. Otherwise, provides a member constant `value` equal to `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const T&>::value`.
2) Same as (1), but uses `[std::is\_trivially\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const T&>`
3) Same as (1), but uses `[std::is\_nothrow\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, const T&>`
`T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_copy_assignable_v = is_copy_assignable<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_copy_assignable_v = is_trivially_copy_assignable<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_copy_assignable_v = is_nothrow_copy_assignable<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is copy-assignable, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T>
struct is_copy_assignable
: std::is_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<const T>::type> {};
template< class T>
struct is_trivially_copy_assignable
: std::is_trivially_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<const T>::type> {};
template< class T>
struct is_nothrow_copy_assignable
: std::is_nothrow_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<const T>::type> {};
```
|
### Notes
The trait `std::is_copy_assignable` is less strict than [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") because it does not check the type of the result of the assignment (which, for a [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") type, must be an lvalue of type `T`) and does not check the semantic requirement that the argument expression remains unchanged. It also does not check that `T` satisfies [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"), which is required of all [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") types.
### Example
```
#include <iostream>
#include <utility>
#include <type_traits>
struct Foo { int n; };
int main() {
std::cout << std::boolalpha
<< "Foo is trivially copy-assignable? "
<< std::is_trivially_copy_assignable<Foo>::value << '\n'
<< "int[2] is copy-assignable? "
<< std::is_copy_assignable<int[2]>::value << '\n'
<< "int is nothrow copy-assignable? "
<< std::is_nothrow_copy_assignable<int>::value << '\n';
}
```
Output:
```
Foo is trivially copy-assignable? true
int[2] is copy-assignable? false
int is nothrow copy-assignable? true
```
### See also
| | |
| --- | --- |
| [is\_assignableis\_trivially\_assignableis\_nothrow\_assignable](is_assignable "cpp/types/is assignable")
(C++11)(C++11)(C++11) | checks if a type has a assignment operator for a specific argument (class template) |
| [is\_move\_assignableis\_trivially\_move\_assignableis\_nothrow\_move\_assignable](is_move_assignable "cpp/types/is move assignable")
(C++11)(C++11)(C++11) | checks if a type has a move assignment operator (class template) |
cpp std::is_class std::is\_class
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_class;
```
| | (since C++11) |
Checks whether `T` is a non-union class type. Provides the member constant `value` which is equal to `true`, if `T` is a class type (but not union). Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_class` or `is_class_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_class_v = is_class<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a non-union class type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
namespace detail {
template <class T>
std::integral_constant<bool, !std::is_union<T>::value> test(int T::*);
template <class>
std::false_type test(...);
}
template <class T>
struct is_class : decltype(detail::test<T>(nullptr))
{};
```
|
### Example
```
#include <iostream>
#include <type_traits>
struct A {};
class B {};
enum class E {};
union U { class UC {}; };
static_assert(not std::is_class_v<U>);
static_assert(std::is_class_v<U::UC>);
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_class<A>::value << ": A\n";
std::cout << std::is_class_v<B> << ": B \n";
std::cout << std::is_class_v<B*> << ": B* \n";
std::cout << std::is_class_v<B&> << ": B& \n";
std::cout << std::is_class_v<const B> << ": const B \n";
std::cout << std::is_class<E>::value << ": E\n";
std::cout << std::is_class_v<int> << ": int\n";
std::cout << std::is_class_v<struct S> << ": struct S (incomplete)\n";
std::cout << std::is_class_v<class C> << ": class C (incomplete)\n";
}
```
Output:
```
true: A
true: B
false: B*
false: B&
true: const B
false: E
false: int
true: struct S (incomplete)
true: class C (incomplete)
```
### See also
| | |
| --- | --- |
| [is\_union](is_union "cpp/types/is union")
(C++11) | checks if a type is an union type (class template) |
| programming_docs |
cpp std::is_destructible, std::is_trivially_destructible, std::is_nothrow_destructible std::is\_destructible, std::is\_trivially\_destructible, std::is\_nothrow\_destructible
=======================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_destructible;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_destructible;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_destructible;
```
| (3) | (since C++11) |
1) If `T` is a reference type, provides the member constant `value` equal to `true`.
If `T` is (possibly cv-qualified) `void`, a function type, or an array of unknown bound, `value` equals `false`.
If `T` is an object type, then, for the type `U` equal to `[std::remove\_all\_extents](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>::type`, if the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U&>().~U()` is well-formed in unevaluated context, `value` equals `true`. Otherwise, `value` equals `false`.
2) same as (1) and additionally `[std::remove\_all\_extents](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>::type` is either a non-class type or a class type with a [trivial destructor](../language/destructor#Trivial_destructor "cpp/language/destructor").
3) same as (1), but the destructor is noexcept.
`T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_destructible_v = is_destructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_destructible_v = is_trivially_destructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_destructible_v = is_nothrow_destructible<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is destructible, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Because the C++ program terminates if a destructor throws an exception during stack unwinding (which usually cannot be predicted), all practical destructors are non-throwing even if they are not declared noexcept. All destructors found in the C++ standard library are non-throwing.
Storage occupied by [trivially destructible](../language/destructor#Trivial_destructor "cpp/language/destructor") objects [may be reused](../language/lifetime#Storage_reuse "cpp/language/lifetime") without calling the destructor.
### Example
```
#include <iostream>
#include <string>
#include <type_traits>
struct Foo {
std::string str;
~Foo() noexcept {};
};
struct Bar {
~Bar() = default;
};
int main() {
std::cout << std::boolalpha
<< "std::string is destructible? "
<< std::is_destructible<std::string>::value << '\n'
<< "Foo is trivially destructible? "
<< std::is_trivially_destructible_v<Foo> << '\n'
<< "Foo is nothrow destructible? "
<< std::is_nothrow_destructible<Foo>() << '\n'
<< "Bar is trivially destructible? "
<< std::is_trivially_destructible<Bar>{} << '\n';
}
```
Output:
```
std::string is destructible? true
Foo is trivially destructible? false
Foo is nothrow destructible? true
Bar is trivially destructible? true
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2049](https://cplusplus.github.io/LWG/issue2049) | C++11 | the specification was incompletable because of the imaginary wrapping struct | made complete |
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
| [has\_virtual\_destructor](has_virtual_destructor "cpp/types/has virtual destructor")
(C++11) | checks if a type has a virtual destructor (class template) |
| [destructible](../concepts/destructible "cpp/concepts/destructible")
(C++20) | specifies that an object of the type can be destroyed (concept) |
| [destructor](../language/destructor "cpp/language/destructor") | releases claimed resources |
cpp std::is_volatile std::is\_volatile
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_volatile;
```
| | (since C++11) |
If `T` is a volatile-qualified type (that is, `volatile`, or `const volatile`), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_volatile` or `is_volatile_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_volatile_v = is_volatile<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a volatile-qualified type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T> struct is_volatile : std::false_type {};
template<class T> struct is_volatile<volatile T> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_volatile<int>::value << '\n';
std::cout << std::is_volatile<volatile int>::value << '\n';
}
```
Output:
```
false
true
```
### See also
| | |
| --- | --- |
| [is\_const](is_const "cpp/types/is const")
(C++11) | checks if a type is const-qualified (class template) |
cpp std::bad_typeid std::bad\_typeid
================
| Defined in header `[<typeinfo>](../header/typeinfo "cpp/header/typeinfo")` | | |
| --- | --- | --- |
|
```
class bad_typeid : public std::exception;
```
| | |
An exception of this type is thrown when a [`typeid`](../language/typeid "cpp/language/typeid") operator is applied to a dereferenced null pointer value of a polymorphic type.
![std-bad typeid-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs a new `bad_typeid` object (public member function) |
| operator= | replaces the `bad_typeid` object (public member function) |
| what | returns the explanatory string (public member function) |
std::bad\_typeid::bad\_typeid
------------------------------
| | | |
| --- | --- | --- |
| | (1) | |
|
```
bad_typeid() throw();
```
| (until C++11) |
|
```
bad_typeid() noexcept;
```
| (since C++11) |
| | (2) | |
|
```
bad_typeid( const bad_typeid& other ) throw();
```
| (until C++11) |
|
```
bad_typeid( const bad_typeid& other ) noexcept;
```
| (since C++11) |
Constructs a new `bad_typeid` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../error/exception/what "cpp/error/exception/what").
1) Default constructor.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_typeid` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11)
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to copy |
std::bad\_typeid::operator=
----------------------------
| | | |
| --- | --- | --- |
|
```
bad_typeid& operator=( const bad_typeid& other ) throw();
```
| | (until C++11) |
|
```
bad_typeid& operator=( const bad_typeid& other ) noexcept;
```
| | (since C++11) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_typeid` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11).
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::bad\_typeid::what
-----------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const throw();
```
| | (until C++11) |
|
```
virtual const char* what() const noexcept;
```
| | (since C++11) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::exception](../error/exception "cpp/error/exception")
---------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
### Example
```
#include <iostream>
#include <typeinfo>
struct S { // The type has to be polymorphic
virtual void f();
};
int main()
{
S* p = nullptr;
try {
std::cout << typeid(*p).name() << '\n';
} catch(const std::bad_typeid& e) {
std::cout << e.what() << '\n';
}
}
```
Possible output:
```
Attempted a typeid of NULL pointer!
```
cpp std::is_abstract std::is\_abstract
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_abstract;
```
| | (since C++11) |
If `T` is an [abstract class](../language/abstract_class "cpp/language/abstract class") (that is, a non-union class that declares or inherits at least one pure virtual function), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
If `T` is a non-union class type, `T` shall be a complete type; otherwise, the behavior is undefined.
The behavior of a program that adds specializations for `is_abstract` or `is_abstract_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_abstract_v = is_abstract<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an [abstract class](../language/abstract_class "cpp/language/abstract class") type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Example
```
#include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
virtual void foo();
};
struct C {
virtual void foo() = 0;
};
struct D : C {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_abstract<A>::value << '\n';
std::cout << std::is_abstract<B>::value << '\n';
std::cout << std::is_abstract<C>::value << '\n';
std::cout << std::is_abstract<D>::value << '\n';
}
```
Output:
```
false
false
true
true
```
### See also
| | |
| --- | --- |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| [is\_polymorphic](is_polymorphic "cpp/types/is polymorphic")
(C++11) | checks if a type is a polymorphic class type (class template) |
cpp std::integral_constant std::integral\_constant
=======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, T v >
struct integral_constant;
```
| | (since C++11) |
`std::integral_constant` wraps a static constant of specified type. It is the base class for the C++ type traits.
The behavior of a program that adds specializations for `integral_constant` is undefined.
### Helper alias templates
A helper alias template `std::bool_constant` is defined for the common case where `T` is `bool`.
| | | |
| --- | --- | --- |
|
```
template <bool B>
using bool_constant = integral_constant<bool, B>;
```
| | (since C++17) |
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bool_constant`](../feature_test#Library_features "cpp/feature test") |
### Specializations
Two typedefs for the common case where `T` is `bool` are provided:
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` |
| --- |
| Type | Definition |
| `true_type` | `std::integral_constant<bool, true>` |
| `false_type` | `std::integral_constant<bool, false>` |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
| `type` | `std::integral_constant<T,v>` |
### Member constants
| Name | Value |
| --- | --- |
| constexpr T value
[static] | static constant of type `T` with value `v` (public static member constant) |
### Member functions
| | |
| --- | --- |
| **operator value\_type** | returns the wrapped value (public member function) |
| **operator()**
(C++14) | returns the wrapped value (public member function) |
std::integral\_constant::operator value\_type
----------------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr operator value_type() const noexcept;
```
| | |
Conversion function. Returns the wrapped value.
std::integral\_constant::operator()
------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr value_type operator()() const noexcept;
```
| | (since C++14) |
Returns the wrapped value. This function enables `std::integral_constant` to serve as a source of compile-time function objects.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_integral_constant_callable`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| |
| --- |
|
```
template<class T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant; // using injected-class-name
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; } // since c++14
};
```
|
### Example
```
#include <type_traits>
int main()
{
typedef std::integral_constant<int, 2> two_t;
typedef std::integral_constant<int, 4> four_t;
// static_assert(std::is_same<two_t, four_t>::value,
// "two_t and four_t are not equal!");
// error: static assertion failed: "two_t and four_t are not equal!"
static_assert(two_t::value*2 == four_t::value,
"2*2 != 4"
);
enum class my_e { e1, e2 };
typedef std::integral_constant<my_e, my_e::e1> my_e_e1;
typedef std::integral_constant<my_e, my_e::e2> my_e_e2;
static_assert(my_e_e1() == my_e::e1);
// static_assert(my_e_e1::value == my_e::e2,
// "my_e_e1::value != my_e::e2");
// error: static assertion failed: "my_e_e1::value != my_e::e2"
static_assert(std::is_same<my_e_e2, my_e_e2>::value,
"my_e_e2 != my_e_e2");
}
```
cpp std::make_signed std::make\_signed
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct make_signed;
```
| | (since C++11) |
If `T` is an integral (except `bool`) or enumeration type, provides the member typedef `type` which is the signed integer type corresponding to `T`, with the same cv-qualifiers.
If `T` is signed or unsigned `char`, `short`, `int`, `long`, `long long`, the signed type from this list corresponding to `T` is provided.
If `T` is an enumeration type or `char`, `wchar_t`, `char8_t` (since C++20), `char16_t`, `char32_t`, the signed integer type with the smallest [rank](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") having the same `sizeof` as `T` is provided.
| | |
| --- | --- |
| Otherwise, the behavior is undefined. | (until C++20) |
| Otherwise, the program is ill-formed. | (since C++20) |
The behavior of a program that adds specializations for `make_signed` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the signed integer type corresponding to `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using make_signed_t = typename make_signed<T>::type;
```
| | (since C++14) |
### Example
```
#include <iostream>
#include <type_traits>
int main() {
typedef std::make_signed<unsigned char>::type char_type;
typedef std::make_signed<unsigned int>::type int_type;
typedef std::make_signed<volatile unsigned long>::type long_type;
bool ok1 = std::is_same<char_type, signed char>::value;
bool ok2 = std::is_same<int_type, signed int>::value;
bool ok3 = std::is_same<long_type, volatile signed long>::value;
std::cout << std::boolalpha
<< "char_type is 'signed char'? : " << ok1 << '\n'
<< "int_type is 'signed int'? : " << ok2 << '\n'
<< "long_type is 'volatile signed long'? : " << ok3 << '\n';
}
```
Output:
```
char_type is 'signed char'? : true
int_type is 'signed int'? : true
long_type is 'volatile signed long'? : true
```
### See also
| | |
| --- | --- |
| [is\_signed](is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
| [is\_unsigned](is_unsigned "cpp/types/is unsigned")
(C++11) | checks if a type is an unsigned arithmetic type (class template) |
| [make\_unsigned](make_unsigned "cpp/types/make unsigned")
(C++11) | makes the given integral type unsigned (class template) |
| programming_docs |
cpp std::is_unbounded_array std::is\_unbounded\_array
=========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_unbounded_array;
```
| | (since C++20) |
Checks whether `T` is an [array type of unknown bound](../language/array#Arrays_of_unknown_bound "cpp/language/array"). Provides the member constant `value` which is equal to `true`, if `T` is an array type of unknown bound. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_unbounded_array` or `is_unbounded_array_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_unbounded_array_v = is_unbounded_array<T>::value;
```
| | (since C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an array type of unknown bound , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_unbounded_array: std::false_type {};
template<class T>
struct is_unbounded_array<T[]> : std::true_type {};
```
|
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bounded_array_traits`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
#define OUT(...) std::cout << #__VA_ARGS__ << " : " << __VA_ARGS__ << '\n'
class A {};
int main()
{
std::cout << std::boolalpha;
OUT( std::is_unbounded_array_v<A> );
OUT( std::is_unbounded_array_v<A[]> );
OUT( std::is_unbounded_array_v<A[3]> );
OUT( std::is_unbounded_array_v<float> );
OUT( std::is_unbounded_array_v<int> );
OUT( std::is_unbounded_array_v<int[]> );
OUT( std::is_unbounded_array_v<int[3]> );
}
```
Output:
```
std::is_unbounded_array_v<A> : false
std::is_unbounded_array_v<A[]> : true
std::is_unbounded_array_v<A[3]> : false
std::is_unbounded_array_v<float> : false
std::is_unbounded_array_v<int> : false
std::is_unbounded_array_v<int[]> : true
std::is_unbounded_array_v<int[3]> : false
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_bounded\_array](is_bounded_array "cpp/types/is bounded array")
(C++20) | checks if a type is an array type of known bound (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
cpp std::is_compound std::is\_compound
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_compound;
```
| | (since C++11) |
If `T` is a compound type (that is, array, function, object pointer, function pointer, member object pointer, member function pointer, reference, class, union, or enumeration, including any cv-qualified variants), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_compound` or `is_compound_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_compound_v = is_compound<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a compound type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Compound types are the types that are constructed from fundamental types. Any C++ type is either fundamental or compound.
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_compound : std::integral_constant<bool, !std::is_fundamental<T>::value> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main() {
class cls {};
std::cout << (std::is_compound<cls>::value
? "`cls` is compound"
: "`cls` is not a compound") << '\n';
std::cout << (std::is_compound_v<int>
? "`int` is compound"
: "`int` is not a compound") << '\n';
}
```
Output:
```
`cls` is compound
`int` is not a compound
```
### See also
| | |
| --- | --- |
| [is\_fundamental](is_fundamental "cpp/types/is fundamental")
(C++11) | checks if a type is a fundamental type (class template) |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| [is\_object](is_object "cpp/types/is object")
(C++11) | checks if a type is an object type (class template) |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
cpp std::max_align_t std::max\_align\_t
==================
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
|
```
typedef /*implementation-defined*/ max_align_t;
```
| | (since C++11) |
`std::max_align_t` is a [trivial](../named_req/trivialtype "cpp/named req/TrivialType") [standard-layout](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") type whose [alignment requirement](../language/object#Alignment "cpp/language/object") is at least as strict (as large) as that of every scalar type.
### Notes
Pointers returned by allocation functions such as `[std::malloc](../memory/c/malloc "cpp/memory/c/malloc")` are suitably aligned for any object, which means they are aligned at least as strictly as `std::max_align_t`.
`std::max_align_t` is usually synonymous with the largest scalar type, which is `long double` on most platforms, and its alignment requirement is either 8 or 16.
### Example
```
#include <iostream>
#include <cstddef>
int main()
{
std::cout << alignof(std::max_align_t) << '\n';
}
```
Possible output:
```
16
```
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 17.2.4 Sizes, alignments, and offsets [support.types.layout] (p: 507-508)
* C++17 standard (ISO/IEC 14882:2017):
+ 21.2.4 Sizes, alignments, and offsets [support.types.layout] (p: 479)
* C++14 standard (ISO/IEC 14882:2014):
+ 18.2 Types [support.types] (p: 443-444)
* C++11 standard (ISO/IEC 14882:2011):
+ 18.2 Types [support.types] (p: 454-455)
### See also
| | |
| --- | --- |
| [`alignof` operator](../language/alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type |
| [alignment\_of](alignment_of "cpp/types/alignment of")
(C++11) | obtains the type's alignment requirements (class template) |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| [C documentation](https://en.cppreference.com/w/c/types/max_align_t "c/types/max align t") for `max_align_t` |
cpp std::is_null_pointer std::is\_null\_pointer
======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_null_pointer;
```
| | (since C++14) |
Checks whether `T` is the type `[std::nullptr\_t](nullptr_t "cpp/types/nullptr t")`.
Provides the member constant `value` that is equal to `true`, if `T` is the type `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)`, `const [std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)`, `volatile [std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)`, or `const volatile [std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)`.
Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_null_pointer` or `is_null_pointer_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_null_pointer_v = is_null_pointer<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is the type `[std::nullptr\_t](nullptr_t "cpp/types/nullptr t")` (possibly cv-qualified) , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_null_pointer : std::is_same<std::nullptr_t, std::remove_cv_t<T>> {};
```
|
### Notes
`[std::is\_pointer](is_pointer "cpp/types/is pointer")` is `false` for `[std::nullptr\_t](nullptr_t "cpp/types/nullptr t")` because it is not a built-in pointer type.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_null_pointer`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha
<< std::is_null_pointer< decltype(nullptr) >::value << ' '
<< std::is_null_pointer< int* >::value << '\n'
<< std::is_pointer< decltype(nullptr) >::value << ' '
<< std::is_pointer<int*>::value << '\n';
}
```
Output:
```
true false
false true
```
### See also
| | |
| --- | --- |
| [is\_void](is_void "cpp/types/is void")
(C++11) | checks if a type is `void` (class template) |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
| [is\_union](is_union "cpp/types/is union")
(C++11) | checks if a type is an union type (class template) |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| [is\_function](is_function "cpp/types/is function")
(C++11) | checks if a type is a function type (class template) |
| [is\_object](is_object "cpp/types/is object")
(C++11) | checks if a type is an object type (class template) |
cpp std::remove_reference std::remove\_reference
======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_reference;
```
| | (since C++11) |
If the type `T` is a reference type, provides the member typedef `type` which is the type referred to by `T`. Otherwise `type` is `T`.
The behavior of a program that adds specializations for `remove_reference` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type referred by `T` or `T` if it is not a reference |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_reference_t = typename remove_reference<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template< class T > struct remove_reference { typedef T type; };
template< class T > struct remove_reference<T&> { typedef T type; };
template< class T > struct remove_reference<T&&> { typedef T type; };
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main() {
std::cout << std::boolalpha;
std::cout << "std::remove_reference<int>::type is int? "
<< std::is_same<int, std::remove_reference<int>::type>::value << '\n';
std::cout << "std::remove_reference<int&>::type is int? "
<< std::is_same<int, std::remove_reference<int&>::type>::value << '\n';
std::cout << "std::remove_reference<int&&>::type is int? "
<< std::is_same<int, std::remove_reference<int&&>::type>::value << '\n';
std::cout << "std::remove_reference<const int&>::type is const int? "
<< std::is_same<const int,
std::remove_reference<const int&>::type>::value << '\n';
}
```
Output:
```
std::remove_reference<int>::type is int? true
std::remove_reference<int&>::type is int? true
std::remove_reference<int&&>::type is int? true
std::remove_reference<const int&>::type is const int? true
```
### See also
| | |
| --- | --- |
| [is\_reference](is_reference "cpp/types/is reference")
(C++11) | checks if a type is either a *lvalue reference* or *rvalue reference* (class template) |
| [add\_lvalue\_referenceadd\_rvalue\_reference](add_reference "cpp/types/add reference")
(C++11)(C++11) | adds a *lvalue* or *rvalue* reference to the given type (class template) |
| [remove\_cvref](remove_cvref "cpp/types/remove cvref")
(C++20) | combines `[std::remove\_cv](remove_cv "cpp/types/remove cv")` and `std::remove_reference` (class template) |
cpp std::has_virtual_destructor std::has\_virtual\_destructor
=============================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct has_virtual_destructor;
```
| | (since C++11) |
If `T` is a type with a virtual destructor, provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
If `T` is a non-union class type, `T` shall be a complete type; otherwise, the behavior is undefined.
The behavior of a program that adds specializations for `has_virtual_destructor` or `has_virtual_destructor_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool has_virtual_destructor_v = has_virtual_destructor<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` has a virtual destructor , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
If a class has a public virtual destructor, it can be derived from, and the derived object can be safely deleted through a pointer to the base object ([GotW #18](http://www.gotw.ca/publications/mill18.htm)). When true, [is\_polymorphic](is_polymorphic "cpp/types/is polymorphic") is true.
### Example
```
#include <iostream>
#include <type_traits>
#include <string>
#include <stdexcept>
int main()
{
std::cout << std::boolalpha
<< "std::string has a virtual destructor? "
<< std::has_virtual_destructor<std::string>::value << '\n'
<< "std::runtime_error has a virtual destructor? "
<< std::has_virtual_destructor<std::runtime_error>::value << '\n';
}
```
Output:
```
std::string has a virtual destructor? false
std::runtime_error has a virtual destructor? true
```
### See also
| | |
| --- | --- |
| [is\_destructibleis\_trivially\_destructibleis\_nothrow\_destructible](is_destructible "cpp/types/is destructible")
(C++11)(C++11)(C++11) | checks if a type has a non-deleted destructor (class template) |
| [is\_polymorphic](is_polymorphic "cpp/types/is polymorphic")
(C++11) | checks if a type is a polymorphic class type (class template) |
cpp std::is_floating_point std::is\_floating\_point
========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_floating_point;
```
| | (since C++11) |
Checks whether `T` is a floating-point type. Provides the member constant `value` which is equal to `true`, if `T` is the type `float`, `double`, `long double`, including any cv-qualified variants. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_floating_point` or `is_floating_point_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_floating_point_v = is_floating_point<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a floating-point type (possibly cv-qualified) , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_floating_point
: std::integral_constant<
bool,
std::is_same<float, typename std::remove_cv<T>::type>::value ||
std::is_same<double, typename std::remove_cv<T>::type>::value ||
std::is_same<long double, typename std::remove_cv<T>::type>::value
> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha;
std::cout << " A: " << std::is_floating_point<A>::value << '\n';
std::cout << " float: " << std::is_floating_point<float>::value << '\n';
std::cout << " float&: " << std::is_floating_point<float&>::value << '\n';
std::cout << " double: " << std::is_floating_point<double>::value << '\n';
std::cout << "double&: " << std::is_floating_point<double&>::value << '\n';
std::cout << " int: " << std::is_floating_point<int>::value << '\n';
}
```
Output:
```
A: false
float: true
float&: false
double: true
double&: false
int: false
```
### See also
| | |
| --- | --- |
| [is\_iec559](numeric_limits/is_iec559 "cpp/types/numeric limits/is iec559")
[static] | identifies the IEC 559/IEEE 754 floating-point types (public static member constant of `std::numeric_limits<T>`) |
| [is\_integral](is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [floating\_point](../concepts/floating_point "cpp/concepts/floating point")
(C++20) | specifies that a type is a floating-point type (concept) |
| programming_docs |
cpp std::is_rvalue_reference std::is\_rvalue\_reference
==========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_rvalue_reference;
```
| | (since C++11) |
Checks whether `T` is an rvalue reference type. Provides the member constant `value` which is equal to `true`, if `T` is an rvalue reference type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_rvalue_reference` or `is_rvalue_reference_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_rvalue_reference_v = is_rvalue_reference<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an rvalue reference type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template <class T> struct is_rvalue_reference : std::false_type {};
template <class T> struct is_rvalue_reference<T&&> : std::true_type {};
```
|
### Example
```
#include <type_traits>
class A {};
int main()
{
static_assert( not std::is_rvalue_reference_v<A> );
static_assert( not std::is_rvalue_reference_v<A&> );
static_assert( std::is_rvalue_reference_v<A&&> );
static_assert( not std::is_rvalue_reference_v<int> );
static_assert( not std::is_rvalue_reference_v<int&> );
static_assert( std::is_rvalue_reference_v<int&&> );
}
```
### See also
| | |
| --- | --- |
| [is\_lvalue\_reference](is_lvalue_reference "cpp/types/is lvalue reference")
(C++11) | checks if a type is a *lvalue reference* (class template) |
| [is\_reference](is_reference "cpp/types/is reference")
(C++11) | checks if a type is either a *lvalue reference* or *rvalue reference* (class template) |
cpp std::ptrdiff_t std::ptrdiff\_t
===============
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
|
```
typedef /*implementation-defined*/ ptrdiff_t;
```
| | |
`std::ptrdiff_t` is the signed integer type of the result of subtracting two pointers.
| | |
| --- | --- |
| The bit width of `std::ptrdiff_t` is not less than 17. | (since C++11) |
### Notes
`std::ptrdiff_t` is used for [pointer arithmetic](../language/operator_arithmetic#Additive_operators "cpp/language/operator arithmetic") and array indexing, if negative values are possible. Programs that use other types, such as `int`, may fail on, e.g. 64-bit systems when the index exceeds `[INT\_MAX](climits "cpp/types/climits")` or if it relies on 32-bit modular arithmetic.
When working with the C++ container library, the proper type for the difference between iterators is the member typedef `difference_type`, which is often synonymous with `std::ptrdiff_t`.
Only pointers to elements of the same array (including the pointer one past the end of the array) may be subtracted from each other.
If an array is so large (greater than `[PTRDIFF\_MAX](climits "cpp/types/climits")` elements, but less than `[SIZE\_MAX](climits "cpp/types/climits")` bytes), that the difference between two pointers may not be representable as `std::ptrdiff_t`, the result of subtracting two such pointers is undefined.
For char arrays shorter than `[PTRDIFF\_MAX](climits "cpp/types/climits")`, `std::ptrdiff_t` acts as the signed counterpart of `[std::size\_t](size_t "cpp/types/size t")`: it can store the size of the array of any type and is, on most platforms, synonymous with `[std::intptr\_t](integer "cpp/types/integer")`.
### Example
```
#include <cstddef>
#include <iostream>
int main()
{
const std::size_t N = 10;
int* a = new int[N];
int* end = a + N;
for (std::ptrdiff_t i = N; i > 0; --i)
std::cout << (*(end - i) = i) << ' ';
delete[] a;
}
```
Output:
```
10 9 8 7 6 5 4 3 2 1
```
### See also
| | |
| --- | --- |
| [size\_t](size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) |
| [offsetof](offsetof "cpp/types/offsetof") | byte offset from the beginning of a standard-layout type to specified member (function macro) |
| [C documentation](https://en.cppreference.com/w/c/types/ptrdiff_t "c/types/ptrdiff t") for `ptrdiff_t` |
cpp std::is_void std::is\_void
=============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_void;
```
| | (since C++11) |
Checks whether `T` is a void type. Provides the member constant `value` that is equal to `true`, if `T` is the type `void`, `const void`, `volatile void`, or `const volatile void`. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_void` or `is_void_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_void_v = is_void<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is the type `void` (possibly cv-qualified) , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_void : std::is_same<void, typename std::remove_cv<T>::type> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_void<void>::value << '\n';
std::cout << std::is_void<int>::value << '\n';
}
```
Output:
```
true
false
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
| [is\_union](is_union "cpp/types/is union")
(C++11) | checks if a type is an union type (class template) |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
| [is\_function](is_function "cpp/types/is function")
(C++11) | checks if a type is a function type (class template) |
| [is\_object](is_object "cpp/types/is object")
(C++11) | checks if a type is an object type (class template) |
cpp std::is_trivially_copyable std::is\_trivially\_copyable
============================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_trivially_copyable;
```
| | (since C++11) |
If `T` is a [trivially copyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type, provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type and not (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_trivially_copyable` or `is_trivially_copyable_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_trivially_copyable_v = is_trivially_copyable<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a trivially copyable type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Objects of trivially-copyable types that are not potentially-overlapping subobjects are the only C++ objects that may be safely copied with `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")` or serialized to/from binary files with [`std::ofstream::write()`](../io/basic_ostream/write "cpp/io/basic ostream/write")/[`std::ifstream::read()`](../io/basic_istream/read "cpp/io/basic istream/read").
### Example
```
#include <iostream>
#include <type_traits>
struct A
{
int m;
};
struct B
{
B(B const&) {}
};
struct C
{
virtual void foo();
};
struct D
{
int m;
D(D const&) = default; // -> trivially copyable
D(int x): m(x+1) {}
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_trivially_copyable<A>::value << '\n';
std::cout << std::is_trivially_copyable<B>::value << '\n';
std::cout << std::is_trivially_copyable<C>::value << '\n';
std::cout << std::is_trivially_copyable<D>::value << '\n';
}
```
Output:
```
true
false
false
true
```
### See also
| | |
| --- | --- |
| [is\_trivial](is_trivial "cpp/types/is trivial")
(C++11) | checks if a type is trivial (class template) |
cpp std::is_array std::is\_array
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_array;
```
| | (since C++11) |
Checks whether `T` is an array type. Provides the member constant `value` which is equal to `true`, if `T` is an array type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_array` or `is_array_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_array_v = is_array<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an array type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_array : std::false_type {};
template<class T>
struct is_array<T[]> : std::true_type {};
template<class T, std::size_t N>
struct is_array<T[N]> : std::true_type {};
```
|
### Example
```
#include <array>
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_array<A>::value << '\n';
std::cout << std::is_array<A[]>::value << '\n';
std::cout << std::is_array<A[3]>::value << '\n';
std::cout << std::is_array<float>::value << '\n';
std::cout << std::is_array<int>::value << '\n';
std::cout << std::is_array<int[]>::value << '\n';
std::cout << std::is_array<int[3]>::value << '\n';
std::cout << std::is_array<std::array<int, 3>>::value << '\n';
}
```
Output:
```
false
true
true
false
false
true
true
false
```
### See also
| | |
| --- | --- |
| [is\_bounded\_array](is_bounded_array "cpp/types/is bounded array")
(C++20) | checks if a type is an array type of known bound (class template) |
| [is\_unbounded\_array](is_unbounded_array "cpp/types/is unbounded array")
(C++20) | checks if a type is an array type of unknown bound (class template) |
| [rank](rank "cpp/types/rank")
(C++11) | obtains the number of dimensions of an array type (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
| [remove\_extent](remove_extent "cpp/types/remove extent")
(C++11) | removes one extent from the given array type (class template) |
| [remove\_all\_extents](remove_all_extents "cpp/types/remove all extents")
(C++11) | removes all extents from the given array type (class template) |
cpp C numeric limits interface C numeric limits interface
==========================
See also `[std::numeric\_limits](numeric_limits "cpp/types/numeric limits")` interface.
### Limits of integer types
| |
| --- |
| Limits of core language integer types |
| Defined in header `[<climits>](../header/climits "cpp/header/climits")` |
| CHAR\_BIT | number of bits in a byte (macro constant) |
| MB\_LEN\_MAX | maximum number of bytes in a multibyte character (macro constant) |
| CHAR\_MIN | minimum value of `char` (macro constant) |
| CHAR\_MAX | maximum value of `char` (macro constant) |
| SCHAR\_MINSHRT\_MININT\_MINLONG\_MINLLONG\_MIN
(C++11) | minimum value of `signed char`, `short`, `int`, `long` and `long long` respectively (macro constant) |
| SCHAR\_MAXSHRT\_MAXINT\_MAXLONG\_MAXLLONG\_MAX
(C++11) | maximum value of `signed char`, `short`, `int`, `long` and `long long` respectively (macro constant) |
| UCHAR\_MAXUSHRT\_MAXUINT\_MAXULONG\_MAXULLONG\_MAX
(C++11) | maximum value of `unsigned char`, `unsigned short`, `unsigned int`,`unsigned long` and `unsigned long long` respectively (macro constant) |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| Defined in header `[<cstdint>](../header/cstdint "cpp/header/cstdint")` |
| WCHAR\_MIN
(C++11) | minimum value of object of `wchar_t` type (macro constant) |
| WCHAR\_MAX
(C++11) | maximum value of object of `wchar_t` type (macro constant) |
| Limits of library type aliases |
| Defined in header `[<cstdint>](../header/cstdint "cpp/header/cstdint")` |
| PTRDIFF\_MIN
(C++11) | minimum value of object of `[std::ptrdiff\_t](ptrdiff_t "cpp/types/ptrdiff t")` type (macro constant) |
| PTRDIFF\_MAX
(C++11) | maximum value of object of `[std::ptrdiff\_t](ptrdiff_t "cpp/types/ptrdiff t")` type (macro constant) |
| SIZE\_MAX
(C++11) | maximum value of object of `[std::size\_t](size_t "cpp/types/size t")` type (macro constant) |
| SIG\_ATOMIC\_MIN
(C++11) | minimum value of object of `[std::sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t")` type (macro constant) |
| SIG\_ATOMIC\_MAX
(C++11) | maximum value of object of `[std::sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t")` type (macro constant) |
| WINT\_MIN
(C++11) | minimum value of object of `std::wint_t` type (macro constant) |
| WINT\_MAX
(C++11) | maximum value of object of `std::wint_t` type (macro constant) |
#### Notes
The types of these constants, other than `CHAR_BIT` and `MB_LEN_MAX`, are required to match the results of the [integral promotions](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") as applied to objects of the types they describe: `CHAR_MAX` may have type `int` or `unsigned int`, but never `char`. Similarly `USHRT_MAX` may not be of an unsigned type: its type may be `int`.
A freestanding implementation may lack `[std::sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t")` and/or `std::wint_t` typedef names, in which case the `SIG_ATOMIC_*` and/or `WINT_*` macros are correspondingly absent.
#### Example
```
#include <climits>
#include <cstdint>
#include <iomanip>
#include <iostream>
int main()
{
constexpr int w = 14;
std::cout << std::left;
# define COUT(x) std::cout << std::setw(w) << #x << " = " << x << '\n'
COUT( CHAR_BIT );
COUT( MB_LEN_MAX );
COUT( CHAR_MIN );
COUT( CHAR_MAX );
COUT( SCHAR_MIN );
COUT( SHRT_MIN );
COUT( INT_MIN );
COUT( LONG_MIN );
COUT( LLONG_MIN );
COUT( SCHAR_MAX );
COUT( SHRT_MAX );
COUT( INT_MAX );
COUT( LONG_MAX );
COUT( LLONG_MAX );
COUT( UCHAR_MAX );
COUT( USHRT_MAX );
COUT( UINT_MAX );
COUT( ULONG_MAX );
COUT( ULLONG_MAX );
COUT( PTRDIFF_MIN );
COUT( PTRDIFF_MAX );
COUT( SIZE_MAX );
COUT( SIG_ATOMIC_MIN );
COUT( SIG_ATOMIC_MAX );
COUT( WCHAR_MIN );
COUT( WCHAR_MAX );
COUT( WINT_MIN );
COUT( WINT_MAX );
}
```
Possible output:
```
CHAR_BIT = 8
MB_LEN_MAX = 16
CHAR_MIN = -128
CHAR_MAX = 127
SCHAR_MIN = -128
SHRT_MIN = -32768
INT_MIN = -2147483648
LONG_MIN = -9223372036854775808
LLONG_MIN = -9223372036854775808
SCHAR_MAX = 127
SHRT_MAX = 32767
INT_MAX = 2147483647
LONG_MAX = 9223372036854775807
LLONG_MAX = 9223372036854775807
UCHAR_MAX = 255
USHRT_MAX = 65535
UINT_MAX = 4294967295
ULONG_MAX = 18446744073709551615
ULLONG_MAX = 18446744073709551615
PTRDIFF_MIN = -9223372036854775808
PTRDIFF_MAX = 9223372036854775807
SIZE_MAX = 18446744073709551615
SIG_ATOMIC_MIN = -2147483648
SIG_ATOMIC_MAX = 2147483647
WCHAR_MIN = -2147483648
WCHAR_MAX = 2147483647
WINT_MIN = 0
WINT_MAX = 4294967295
```
### Limits of floating-point types
| Defined in header `[<cfloat>](../header/cfloat "cpp/header/cfloat")` |
| --- |
| FLT\_RADIX | the radix (integer base) used by the representation of all three floating-point types (macro constant) |
| DECIMAL\_DIG
(C++11) | conversion from `long double` to decimal with at least `DECIMAL_DIG` digits and back to `long double` is the identity conversion: this is the decimal precision required to serialize/deserialize a `long double` (see also `[std::numeric\_limits::max\_digits10](numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10")`) (macro constant) |
| FLT\_DECIMAL\_DIGDBL\_DECIMAL\_DIGLDBL\_DECIMAL\_DIG
(C++17) | conversion from `float`/`double`/`long double` to decimal with at least `FLT_DECIMAL_DIG`/`DBL_DECIMAL_DIG`/`LDBL_DECIMAL_DIG` digits and back is the identity conversion: this is the decimal precision required to serialize/deserialize a floating-point value (see also `[std::numeric\_limits::max\_digits10](numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10")`). Defined to at least `6`, `10`, and `10` respectively, or `9` for IEEE float and `17` for IEEE double. (macro constant) |
| FLT\_MINDBL\_MINLDBL\_MIN | minimum normalized positive value of `float`, `double` and `long double` respectively (macro constant) |
| FLT\_TRUE\_MINDBL\_TRUE\_MINLDBL\_TRUE\_MIN
(C++17) | minimum positive value of `float`, `double` and `long double` respectively (macro constant) |
| FLT\_MAXDBL\_MAXLDBL\_MAX | maximum finite value of `float`, `double` and `long double` respectively (macro constant) |
| FLT\_EPSILONDBL\_EPSILONLDBL\_EPSILON | difference between `1.0` and the next representable value for `float`, `double` and `long double` respectively (macro constant) |
| FLT\_DIGDBL\_DIGLDBL\_DIG | number of decimal digits that are guaranteed to be preserved in text → `float`/`double`/`long double` → text roundtrip without change due to rounding or overflow (see `[std::numeric\_limits::digits10](numeric_limits/digits10 "cpp/types/numeric limits/digits10")` for explanation) (macro constant) |
| FLT\_MANT\_DIGDBL\_MANT\_DIGLDBL\_MANT\_DIG | number of base `FLT_RADIX` digits that can be represented without losing precision for `float`, `double` and `long double` respectively (macro constant) |
| FLT\_MIN\_EXPDBL\_MIN\_EXPLDBL\_MIN\_EXP | minimum negative integer such that `FLT_RADIX` raised by power one less than that integer is a normalized `float`, `double` and `long double` respectively (macro constant) |
| FLT\_MIN\_10\_EXPDBL\_MIN\_10\_EXPLDBL\_MIN\_10\_EXP | minimum negative integer such that 10 raised to that power is a normalized `float`, `double` and `long double` respectively (macro constant) |
| FLT\_MAX\_EXPDBL\_MAX\_EXPLDBL\_MAX\_EXP | maximum positive integer such that `FLT_RADIX` raised by power one less than that integer is a representable finite `float`, `double` and `long double` respectively (macro constant) |
| FLT\_MAX\_10\_EXPDBL\_MAX\_10\_EXPLDBL\_MAX\_10\_EXP | maximum positive integer such that 10 raised to that power is a representable finite `float`, `double` and `long double` respectively (macro constant) |
| [FLT\_ROUNDS](climits/flt_rounds "cpp/types/climits/FLT ROUNDS") | default rounding mode of floating-point arithmetics (macro constant) |
| [FLT\_EVAL\_METHOD](climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD")
(C++11) | specifies in what precision all arithmetic operations are done (macro constant) |
| FLT\_HAS\_SUBNORMDBL\_HAS\_SUBNORMLDBL\_HAS\_SUBNORM
(C++17) | specifies whether the type supports subnormal ([denormal](https://en.wikipedia.org/wiki/Denormal_number "enwiki:Denormal number")) numbers: `-1` – indeterminable, `0` – absent, `1` – present (macro constant) |
#### Example
```
#include <cfloat>
#include <iomanip>
#include <iostream>
int main()
{
int w = 16;
std::cout << std::left; // std::cout << std::setprecision(53);
# define COUT(x) std::cout << std::setw(w) << #x << " = " << x << '\n'
COUT( FLT_RADIX );
COUT( DECIMAL_DIG );
COUT( FLT_DECIMAL_DIG );
COUT( DBL_DECIMAL_DIG );
COUT( LDBL_DECIMAL_DIG );
COUT( FLT_MIN );
COUT( DBL_MIN );
COUT( LDBL_MIN );
COUT( FLT_TRUE_MIN );
COUT( DBL_TRUE_MIN );
COUT( LDBL_TRUE_MIN );
COUT( FLT_MAX );
COUT( DBL_MAX );
COUT( LDBL_MAX );
COUT( FLT_EPSILON );
COUT( DBL_EPSILON );
COUT( LDBL_EPSILON );
COUT( FLT_DIG );
COUT( DBL_DIG );
COUT( LDBL_DIG );
COUT( FLT_MANT_DIG );
COUT( DBL_MANT_DIG );
COUT( LDBL_MANT_DIG );
COUT( FLT_MIN_EXP );
COUT( DBL_MIN_EXP );
COUT( LDBL_MIN_EXP );
COUT( FLT_MIN_10_EXP );
COUT( DBL_MIN_10_EXP );
COUT( LDBL_MIN_10_EXP );
COUT( FLT_MAX_EXP );
COUT( DBL_MAX_EXP );
COUT( LDBL_MAX_EXP );
COUT( FLT_MAX_10_EXP );
COUT( DBL_MAX_10_EXP );
COUT( LDBL_MAX_10_EXP );
COUT( FLT_ROUNDS );
COUT( FLT_EVAL_METHOD );
COUT( FLT_HAS_SUBNORM );
COUT( DBL_HAS_SUBNORM );
COUT( LDBL_HAS_SUBNORM );
}
```
Possible output:
```
FLT_RADIX = 2
DECIMAL_DIG = 21
FLT_DECIMAL_DIG = 9
DBL_DECIMAL_DIG = 17
LDBL_DECIMAL_DIG = 21
FLT_MIN = 1.17549e-38
DBL_MIN = 2.22507e-308
LDBL_MIN = 3.3621e-4932
FLT_TRUE_MIN = 1.4013e-45
DBL_TRUE_MIN = 4.94066e-324
LDBL_TRUE_MIN = 3.6452e-4951
FLT_MAX = 3.40282e+38
DBL_MAX = 1.79769e+308
LDBL_MAX = 1.18973e+4932
FLT_EPSILON = 1.19209e-07
DBL_EPSILON = 2.22045e-16
LDBL_EPSILON = 1.0842e-19
FLT_DIG = 6
DBL_DIG = 15
LDBL_DIG = 18
FLT_MANT_DIG = 24
DBL_MANT_DIG = 53
LDBL_MANT_DIG = 64
FLT_MIN_EXP = -125
DBL_MIN_EXP = -1021
LDBL_MIN_EXP = -16381
FLT_MIN_10_EXP = -37
DBL_MIN_10_EXP = -307
LDBL_MIN_10_EXP = -4931
FLT_MAX_EXP = 128
DBL_MAX_EXP = 1024
LDBL_MAX_EXP = 16384
FLT_MAX_10_EXP = 38
DBL_MAX_10_EXP = 308
LDBL_MAX_10_EXP = 4932
FLT_ROUNDS = 1
FLT_EVAL_METHOD = 0
FLT_HAS_SUBNORM = 1
DBL_HAS_SUBNORM = 1
LDBL_HAS_SUBNORM = 1
```
### See also
* [Fixed width integer types](integer "cpp/types/integer")
* [Arithmetic types](../language/types "cpp/language/types")
* [C++ type system overview](../language/type "cpp/language/type")
* [Type support (basic types, RTTI, type traits)](../types "cpp/types")
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/types/limits "c/types/limits") for Numeric limits |
| programming_docs |
cpp std::is_scalar std::is\_scalar
===============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_scalar;
```
| | (since C++11) |
If `T` is a [scalar type](../named_req/scalartype "cpp/named req/ScalarType"), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_scalar` or `is_scalar_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_scalar_v = is_scalar<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a scalar type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Each individual memory location in the C++ memory model, including the hidden memory locations used by language features (e.g virtual table pointer), has scalar type (or is a sequence of adjacent bit-fields of non-zero length). Sequencing of side-effects in expression evaluation, interthread synchronization, and dependency ordering are all defined in terms of individual scalar objects.
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_scalar : std::integral_constant<bool,
std::is_arithmetic<T>::value ||
std::is_enum<T>::value ||
std::is_pointer<T>::value ||
std::is_member_pointer<T>::value ||
std::is_null_pointer<T>::value> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
#include <typeinfo>
#include <utility>
template<typename Head, typename... Tail>
void are_scalars(Head&& head, Tail&&... tail)
{
using T = std::decay_t<decltype(head)>;
std::cout << typeid(T).name() << " is "
<< (std::is_scalar_v<T> ? "" : "not ")
<< "a scalar\n";
if constexpr (sizeof... (Tail))
{
are_scalars(std::forward<decltype(tail)>(tail)...);
}
}
int main()
{
struct S { int m; } s;
int S::* mp = &S::m;
enum class E { e };
are_scalars(42, 3.14, E::e, "str", mp, nullptr, s);
}
```
Possible output:
```
int is a scalar
double is a scalar
main::E is a scalar
char const* is a scalar
int main::S::* is a scalar
nullptr is a scalar
main::S is not a scalar
```
### See also
| | |
| --- | --- |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_member\_pointer](is_member_pointer "cpp/types/is member pointer")
(C++11) | checks if a type is a pointer to an non-static member function or object (class template) |
cpp std::common_reference std::common\_reference
======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class... T >
struct common_reference;
```
| | (since C++20) |
Determines the common reference type of the types `T...`, that is, the type to which all the types in `T...` can be converted or bound. If such a type exists (as determined according to the rules below), the member `type` names that type. Otherwise, there is no member `type`. The behavior is undefined if any of the types in `T...` is an incomplete type other than (possibly cv-qualified) `void`.
When given reference types, `common_reference` attempts to find a reference type to which the supplied reference types can all be bound, but may return a non-reference type if it cannot find such a reference type.
* If `sizeof...(T)` is zero, there is no member `type`.
* If `sizeof...(T)` is one (i.e., `T...` contains only one type `T0`), the member `type` names the same type as `T0`.
* If `sizeof...(T)` is two (i.e., `T...` contains two types `T1` and `T2`):
+ If `T1` and `T2` are both reference types, and the *simple common reference type* `S` of `T1` and `T2` (as defined below) exists, then the member type `type` names `S`;
+ Otherwise, if `std::basic\_common\_reference<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T1>, [std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T2>, T1Q, T2Q>::type` exists, where `TiQ` is a unary alias template such that `TiQ<U>` is `U` with the addition of `Ti`'s cv- and reference qualifiers, then the member type `type` names that type;
+ Otherwise, if `decltype(false? val<T1>() : val<T2>())`, where `val` is a function template `template<class T> T val();`, is a valid type, then the member type `type` names that type;
+ Otherwise, if `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<T1, T2>` is a valid type, then the member type `type` names that type;
+ Otherwise, there is no member `type`.
* If `sizeof...(T)` is greater than two (i.e., `T...` consists of the types `T1, T2, R...`), then if `std::common_reference_t<T1, T2>` exists, the member `type` denotes `std::common_reference_t<std::common_reference_t<T1, T2>, R...>` if such a type exists. In all other cases, there is no member `type`.
The *simple common reference type* of two reference types `T1` and `T2` is defined as follows:
* If `T1` is `*cv1* X &` and `T2` is `*cv2* Y &` (i.e., both are lvalue reference types): their simple common reference type is `decltype(false? [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<cv12 X &>() : [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<cv12 Y &>())`, where *cv12* is the union of *cv1* and *cv2*, if that type exists and is a reference type;
* If `T1` and `T2` are both rvalue reference types: if the simple common reference type of `T1 &` and `T2 &` (determined according to the previous bullet) exists, then let `C` denote that type's corresponding rvalue reference type. If `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<T1, C>` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<T2, C>` are both `true`, then the simple common reference type of `T1` and `T2` is `C`.
* Otherwise, one of the two types must be an lvalue reference type `A &` and the other must be an rvalue reference type `B &&` (`A` and `B` might be cv-qualified). Let `D` denote the simple common reference type of `A &` and `B const &`, if any. If `D` exists and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<B&&, D>` is `true`, then the simple common reference type is `D`.
* Otherwise, there's no simple common reference type.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the common reference type for all `T...` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class... T >
using common_reference_t = typename std::common_reference<T...>::type;
```
| | |
|
```
template< class T, class U, template<class> class TQual, template<class> class UQual >
struct basic_common_reference { };
```
| | |
The class template `basic_common_reference` is a customization point that allows users to influence the result of `common_reference` for user-defined types (typically proxy references). The primary template is empty.
### Specializations
A program may specialize `std::basic_common_reference<T, U, TQual, UQual>` on the first two parameters `T` and `U` if `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<T, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>>` and `[std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<U, [std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<U>>` are both `true` and at least one of them depends on a program-defined type.
If such a specialization has a member named `type`, it must be a public and unambiguous member that names a type to which both `TQual<T>` and `UQual<U>` are convertible. Additionally, `std::basic_common_reference<T, U, TQual, UQual>::type` and `std::basic_common_reference<U, T, UQual, TQual>::type` must denote the same type.
A program may not specialize `basic_common_reference` on the third or fourth parameters, nor may it specialize `common_reference` itself. A program that adds specializations in violation of these rules has undefined behavior.
The standard library provides following specializations of `basic_common_reference`:
| | |
| --- | --- |
| [std::basic\_common\_reference<std::pair>](../utility/pair/basic_common_reference "cpp/utility/pair/basic common reference")
(C++23) | determines the common reference type of two `pair`s (class template specialization) |
| [std::basic\_common\_reference<*tuple-like*>](../utility/tuple/basic_common_reference "cpp/utility/tuple/basic common reference")
(C++23) | determines the common reference type of a `tuple` and a tuple-like type (class template specialization) |
### Notes
### Examples
### See also
| | |
| --- | --- |
| [common\_type](common_type "cpp/types/common type")
(C++11) | determines the common type of a group of types (class template) |
| [common\_reference\_with](../concepts/common_reference_with "cpp/concepts/common reference with")
(C++20) | specifies that two types share a common reference type (concept) |
cpp std::is_move_assignable, std::is_trivially_move_assignable, std::is_nothrow_move_assignable std::is\_move\_assignable, std::is\_trivially\_move\_assignable, std::is\_nothrow\_move\_assignable
===================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_move_assignable;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_move_assignable;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_move_assignable;
```
| (3) | (since C++11) |
1) If `T` is not a referenceable type (i.e., possibly cv-qualified `void` or a function type with a *cv-qualifier-seq* or a *ref-qualifier*), provides a member constant `value` equal to `false`. Otherwise, provides a member constant `value` equal to `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, T&&>::value`.
2) Same as (1), but uses `[std::is\_trivially\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, T&&>`
3) Same as (1), but uses `[std::is\_nothrow\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<T&, T&&>`
`T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_move_assignable_v = is_move_assignable<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_move_assignable_v = is_trivially_move_assignable<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_move_assignable_v = is_nothrow_move_assignable<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is move-assignable, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T>
struct is_move_assignable
: std::is_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type> {};
template< class T>
struct is_trivially_move_assignable
: std::is_trivially_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type> {};
template< class T>
struct is_nothrow_move_assignable
: std::is_nothrow_assignable< typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type> {};
```
|
### Notes
The trait `std::is_move_assignable` is less strict than [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") because it does not check the type of the result of the assignment (which, for a [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") type, must be `T&`), nor the semantic requirement that the target's value after the assignment is equivalent to the source's value before the assignment.
The type does not have to implement a [move assignment operator](../language/move_operator "cpp/language/move operator") in order to satisfy this trait; see [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") for details.
### Example
```
#include <iostream>
#include <string>
#include <type_traits>
struct Foo { int n; };
struct NoMove {
// prevents implicit declaration of default move assignment operator
// however, the class is still move-assignable because its
// copy assignment operator can bind to an rvalue argument
NoMove& operator=(const NoMove&) { return *this; }
};
int main() {
std::cout << std::boolalpha
<< "std::string is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<std::string>::value << '\n'
<< "int[2] is move-assignable? "
<< std::is_move_assignable<int[2]>::value << '\n'
<< "Foo is trivally move-assignable? "
<< std::is_trivially_move_assignable<Foo>::value << '\n';
std::cout << std::boolalpha
<< "NoMove is move-assignable? "
<< std::is_move_assignable<NoMove>::value << '\n'
<< "NoMove is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<NoMove>::value << '\n';
}
```
Output:
```
std::string is nothrow move-assignable? true
int[2] is move-assignable? false
Foo is trivially move-assignable? true
NoMove is move-assignable? true
NoMove is nothrow move-assignable? false
```
### See also
| | |
| --- | --- |
| [is\_assignableis\_trivially\_assignableis\_nothrow\_assignable](is_assignable "cpp/types/is assignable")
(C++11)(C++11)(C++11) | checks if a type has a assignment operator for a specific argument (class template) |
| [is\_copy\_assignableis\_trivially\_copy\_assignableis\_nothrow\_copy\_assignable](is_copy_assignable "cpp/types/is copy assignable")
(C++11)(C++11)(C++11) | checks if a type has a copy assignment operator (class template) |
cpp std::is_enum std::is\_enum
=============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_enum;
```
| | (since C++11) |
Checks whether `T` is an [enumeration type](../language/enum "cpp/language/enum"). Provides the member constant `value` which is equal to `true`, if `T` is an enumeration type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_enum` or `is_enum_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_enum_v = is_enum<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an enumeration type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Example
```
#include <iostream>
#include <type_traits>
struct A { enum E { }; };
enum E {};
enum class Ec : int {};
int main()
{
std::cout
<< std::boolalpha
<< std::is_enum<A>::value << '\n'
<< std::is_enum<E>::value << '\n'
<< std::is_enum<A::E>() << '\n'
<< std::is_enum_v<int> << '\n' // Uses helper variable template (C++17)
<< std::is_enum_v<Ec> << '\n'; // Uses helper variable template (C++17)
}
```
Output:
```
false
true
true
false
true
```
### See also
| | |
| --- | --- |
| [is\_integral](is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| [is\_scoped\_enum](is_scoped_enum "cpp/types/is scoped enum")
(C++23) | checks if a type is a scoped enumeration type (class template) |
cpp std::is_member_function_pointer std::is\_member\_function\_pointer
==================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_member_function_pointer;
```
| | (since C++11) |
Checks whether `T` is a non-static member function pointer. Provides the member constant `value` which is equal to `true`, if `T` is a non-static member function pointer type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_member_function_pointer` or `is_member_function_pointer_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_member_function_pointer_v = is_member_function_pointer<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a member function pointer type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_member_function_pointer_helper : std::false_type {};
template< class T, class U>
struct is_member_function_pointer_helper<T U::*> : std::is_function<T> {};
template< class T >
struct is_member_function_pointer
: is_member_function_pointer_helper< typename std::remove_cv<T>::type > {};
```
|
### Example
```
#include <type_traits>
class A {
public:
void member() { }
};
int main()
{
// fails at compile time if A::member is a data member and not a function
static_assert(std::is_member_function_pointer<decltype(&A::member)>::value,
"A::member is not a member function.");
}
```
### See also
| | |
| --- | --- |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_member\_object\_pointer](is_member_object_pointer "cpp/types/is member object pointer")
(C++11) | checks if a type is a pointer to a non-static member object (class template) |
| [is\_member\_pointer](is_member_pointer "cpp/types/is member pointer")
(C++11) | checks if a type is a pointer to an non-static member function or object (class template) |
| programming_docs |
cpp std::numeric_limits std::numeric\_limits
====================
| Defined in header `[<limits>](../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
template< class T > class numeric_limits;
```
| | |
The `numeric_limits` class template provides a standardized way to query various properties of arithmetic types (e.g. the largest possible value for type `int` is `std::numeric_limits<int>::max()`).
This information is provided via specializations of the `numeric_limits` template. The standard library makes available specializations for all arithmetic types:
| Defined in header `[<limits>](../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
template<> class numeric_limits<bool>;
```
| | |
|
```
template<> class numeric_limits<char>;
```
| | |
|
```
template<> class numeric_limits<signed char>;
```
| | |
|
```
template<> class numeric_limits<unsigned char>;
```
| | |
|
```
template<> class numeric_limits<wchar_t>;
```
| | |
|
```
template<> class numeric_limits<char8_t>;
```
| | (since C++20) |
|
```
template<> class numeric_limits<char16_t>;
```
| | (since C++11) |
|
```
template<> class numeric_limits<char32_t>;
```
| | (since C++11) |
|
```
template<> class numeric_limits<short>;
```
| | |
|
```
template<> class numeric_limits<unsigned short>;
```
| | |
|
```
template<> class numeric_limits<int>;
```
| | |
|
```
template<> class numeric_limits<unsigned int>;
```
| | |
|
```
template<> class numeric_limits<long>;
```
| | |
|
```
template<> class numeric_limits<unsigned long>;
```
| | |
|
```
template<> class numeric_limits<long long>;
```
| | (since C++11) |
|
```
template<> class numeric_limits<unsigned long long>;
```
| | (since C++11) |
|
```
template<> class numeric_limits<float>;
```
| | |
|
```
template<> class numeric_limits<double>;
```
| | |
|
```
template<> class numeric_limits<long double>;
```
| | |
Additionally, a specialization exists for every cv-qualified version of each cv-unqualified type for which the specialization exists, identical to the unqualified specialization, e.g. `std::numeric_limits<const int>`, `std::numeric_limits<volatile int>`, and `std::numeric_limits<const volatile int>` are provided and are equivalent to `std::numeric_limits<int>`.
Aliases of arithmetic types (such as `[std::size\_t](size_t "cpp/types/size t")` or `[std::streamsize](../io/streamsize "cpp/io/streamsize")`) may also be examined with the `std::numeric_limits` type traits.
Non-arithmetic standard types, such as `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>` or `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)`, do not have specializations.
| | |
| --- | --- |
| If the implementation defines any [integer-class types](../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable"), specializations of `std::numeric_limits` must also be provided for them. | (since C++20) |
Implementations may provide specializations of `std::numeric_limits` for implementation-specific types: e.g. GCC provides `std::numeric_limits<__int128>`. Non-standard libraries may [add specializations](../language/extending_std "cpp/language/extending std") for library-provided types, e.g. [OpenEXR](http://openexr.com/) provides `std::numeric_limits<half>` for a 16-bit floating-point type.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to retrieve numeric properties for |
### Member constants
| | |
| --- | --- |
| [is\_specialized](numeric_limits/is_specialized "cpp/types/numeric limits/is specialized")
[static] | identifies types for which `std::numeric_limits` is specialized (public static member constant) |
| [is\_signed](numeric_limits/is_signed "cpp/types/numeric limits/is signed")
[static] | identifies signed types (public static member constant) |
| [is\_integer](numeric_limits/is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_exact](numeric_limits/is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
| [has\_infinity](numeric_limits/has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant) |
| [has\_quiet\_NaN](numeric_limits/has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant) |
| [has\_signaling\_NaN](numeric_limits/has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant) |
| [has\_denorm](numeric_limits/has_denorm "cpp/types/numeric limits/has denorm")
[static] | identifies the denormalization style used by the floating-point type (public static member constant) |
| [has\_denorm\_loss](numeric_limits/has_denorm_loss "cpp/types/numeric limits/has denorm loss")
[static] | identifies the floating-point types that detect loss of precision as denormalization loss rather than inexact result (public static member constant) |
| [round\_style](numeric_limits/round_style "cpp/types/numeric limits/round style")
[static] | identifies the rounding style used by the type (public static member constant) |
| [is\_iec559](numeric_limits/is_iec559 "cpp/types/numeric limits/is iec559")
[static] | identifies the IEC 559/IEEE 754 floating-point types (public static member constant) |
| [is\_bounded](numeric_limits/is_bounded "cpp/types/numeric limits/is bounded")
[static] | identifies types that represent a finite set of values (public static member constant) |
| [is\_modulo](numeric_limits/is_modulo "cpp/types/numeric limits/is modulo")
[static] | identifies types that handle overflows with modulo arithmetic (public static member constant) |
| [digits](numeric_limits/digits "cpp/types/numeric limits/digits")
[static] | number of `radix` digits that can be represented without change (public static member constant) |
| [digits10](numeric_limits/digits10 "cpp/types/numeric limits/digits10")
[static] | number of decimal digits that can be represented without change (public static member constant) |
| [max\_digits10](numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10")
[static] (C++11) | number of decimal digits necessary to differentiate all values of this type (public static member constant) |
| [radix](numeric_limits/radix "cpp/types/numeric limits/radix")
[static] | the radix or integer base used by the representation of the given type (public static member constant) |
| [min\_exponent](numeric_limits/min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [min\_exponent10](numeric_limits/min_exponent10 "cpp/types/numeric limits/min exponent10")
[static] | the smallest negative power of ten that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](numeric_limits/max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
| [max\_exponent10](numeric_limits/max_exponent10 "cpp/types/numeric limits/max exponent10")
[static] | the largest integer power of 10 that is a valid finite floating-point value (public static member constant) |
| [traps](numeric_limits/traps "cpp/types/numeric limits/traps")
[static] | identifies types which can cause arithmetic operations to trap (public static member constant) |
| [tinyness\_before](numeric_limits/tinyness_before "cpp/types/numeric limits/tinyness before")
[static] | identifies floating-point types that detect tinyness before rounding (public static member constant) |
### Member functions
| | |
| --- | --- |
| [min](numeric_limits/min "cpp/types/numeric limits/min")
[static] | returns the smallest finite value of the given type (public static member function) |
| [lowest](numeric_limits/lowest "cpp/types/numeric limits/lowest")
[static] (C++11) | returns the lowest finite value of the given type (public static member function) |
| [max](numeric_limits/max "cpp/types/numeric limits/max")
[static] | returns the largest finite value of the given type (public static member function) |
| [epsilon](numeric_limits/epsilon "cpp/types/numeric limits/epsilon")
[static] | returns the difference between `1.0` and the next representable value of the given floating-point type (public static member function) |
| [round\_error](numeric_limits/round_error "cpp/types/numeric limits/round error")
[static] | returns the maximum rounding error of the given floating-point type (public static member function) |
| [infinity](numeric_limits/infinity "cpp/types/numeric limits/infinity")
[static] | returns the positive infinity value of the given floating-point type (public static member function) |
| [quiet\_NaN](numeric_limits/quiet_nan "cpp/types/numeric limits/quiet NaN")
[static] | returns a quiet NaN value of the given floating-point type (public static member function) |
| [signaling\_NaN](numeric_limits/signaling_nan "cpp/types/numeric limits/signaling NaN")
[static] | returns a signaling NaN value of the given floating-point type (public static member function) |
| [denorm\_min](numeric_limits/denorm_min "cpp/types/numeric limits/denorm min")
[static] | returns the smallest positive subnormal value of the given floating-point type (public static member function) |
### Helper classes
| | |
| --- | --- |
| [float\_round\_style](numeric_limits/float_round_style "cpp/types/numeric limits/float round style") | indicates floating-point rounding modes (enum) |
| [float\_denorm\_style](numeric_limits/float_denorm_style "cpp/types/numeric limits/float denorm style") | indicates floating-point denormalization modes (enum) |
### Relationship with C library macro constants
| Specialization`std::numeric_limits<T>`where `T` is | Members |
| --- | --- |
| `min()` | `lowest()`(C++11) | `max()` | `radix` |
| `bool` | `false` | `false` | `true` | `2` |
| `char` | `[CHAR\_MIN](climits "cpp/types/climits")` | `[CHAR\_MIN](climits "cpp/types/climits")` | `[CHAR\_MAX](climits "cpp/types/climits")` | `2` |
| `signed char` | `[SCHAR\_MIN](climits "cpp/types/climits")` | `[SCHAR\_MIN](climits "cpp/types/climits")` | `[SCHAR\_MAX](climits "cpp/types/climits")` | `2` |
| `unsigned char` | `0` | `0` | `[UCHAR\_MAX](climits "cpp/types/climits")` | `2` |
| `wchar_t` | `[WCHAR\_MIN](climits "cpp/types/climits")` | `[WCHAR\_MIN](climits "cpp/types/climits")` | `[WCHAR\_MAX](climits "cpp/types/climits")` | `2` |
| `char8_t` | `0` | `0` | `[UCHAR\_MAX](climits "cpp/types/climits")` | `2` |
| `char16_t` | `0` | `0` | `[UINT\_LEAST16\_MAX](integer "cpp/types/integer")` | `2` |
| `char32_t` | `0` | `0` | `[UINT\_LEAST32\_MAX](integer "cpp/types/integer")` | `2` |
| `short` | `[SHRT\_MIN](climits "cpp/types/climits")` | `[SHRT\_MIN](climits "cpp/types/climits")` | `[SHRT\_MAX](climits "cpp/types/climits")` | `2` |
| `signed short` |
| `unsigned short` | `0` | `0` | `[USHRT\_MAX](climits "cpp/types/climits")` | `2` |
| `int` | `[INT\_MIN](climits "cpp/types/climits")` | `[INT\_MIN](climits "cpp/types/climits")` | `[INT\_MAX](climits "cpp/types/climits")` | `2` |
| `signed int` |
| `unsigned int` | `0` | `0` | `[UINT\_MAX](climits "cpp/types/climits")` | `2` |
| `long` | `[LONG\_MIN](climits "cpp/types/climits")` | `[LONG\_MIN](climits "cpp/types/climits")` | `[LONG\_MAX](climits "cpp/types/climits")` | `2` |
| `signed long` |
| `unsigned long` | `0` | `0` | `[ULONG\_MAX](climits "cpp/types/climits")` | `2` |
| `long long` | `[LLONG\_MIN](climits "cpp/types/climits")` | `[LLONG\_MIN](climits "cpp/types/climits")` | `[LLONG\_MAX](climits "cpp/types/climits")` | `2` |
| `signed long long` |
| `unsigned long long` | `0` | `0` | `[ULLONG\_MAX](climits "cpp/types/climits")` | `2` |
| Specialization`std::numeric_limits<T>`where `T` is | Members |
| --- | --- |
| `denorm_min()` | `min()` | `lowest()`(C++11) | `max()` | `epsilon()` | `digits` | `digits10` |
| `float` | `[FLT\_TRUE\_MIN](climits "cpp/types/climits")` | `[FLT\_MIN](climits "cpp/types/climits")` | `-[FLT\_MAX](http://en.cppreference.com/w/cpp/types/climits)` | `[FLT\_MAX](climits "cpp/types/climits")` | `[FLT\_EPSILON](climits "cpp/types/climits")` | `[FLT\_MANT\_DIG](climits "cpp/types/climits")` | `[FLT\_DIG](climits "cpp/types/climits")` |
| `double` | `[DBL\_TRUE\_MIN](climits "cpp/types/climits")` | `[DBL\_MIN](climits "cpp/types/climits")` | `-[DBL\_MAX](http://en.cppreference.com/w/cpp/types/climits)` | `[DBL\_MAX](climits "cpp/types/climits")` | `[DBL\_EPSILON](climits "cpp/types/climits")` | `[DBL\_MANT\_DIG](climits "cpp/types/climits")` | `[DBL\_DIG](climits "cpp/types/climits")` |
| `long double` | `[LDBL\_TRUE\_MIN](climits "cpp/types/climits")` | `[LDBL\_MIN](climits "cpp/types/climits")` | `-[LDBL\_MAX](http://en.cppreference.com/w/cpp/types/climits)` | `[LDBL\_MAX](climits "cpp/types/climits")` | `[LDBL\_EPSILON](climits "cpp/types/climits")` | `[LDBL\_MANT\_DIG](climits "cpp/types/climits")` | `[LDBL\_DIG](climits "cpp/types/climits")` |
| Specialization`std::numeric_limits<T>`where `T` is | Members (continue) |
| --- | --- |
| `min_exponent` | `min_exponent10` | `max_exponent` | `max_exponent10` | `radix` |
| `float` | `[FLT\_MIN\_EXP](climits "cpp/types/climits")` | `[FLT\_MIN\_10\_EXP](climits "cpp/types/climits")` | `[FLT\_MAX\_EXP](climits "cpp/types/climits")` | `[FLT\_MAX\_10\_EXP](climits "cpp/types/climits")` | `[FLT\_RADIX](climits "cpp/types/climits")` |
| `double` | `[DBL\_MIN\_EXP](climits "cpp/types/climits")` | `[DBL\_MIN\_10\_EXP](climits "cpp/types/climits")` | `[DBL\_MAX\_EXP](climits "cpp/types/climits")` | `[DBL\_MAX\_10\_EXP](climits "cpp/types/climits")` | `[FLT\_RADIX](climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MIN\_EXP](climits "cpp/types/climits")` | `[LDBL\_MIN\_10\_EXP](climits "cpp/types/climits")` | `[LDBL\_MAX\_EXP](climits "cpp/types/climits")` | `[LDBL\_MAX\_10\_EXP](climits "cpp/types/climits")` | `[FLT\_RADIX](climits "cpp/types/climits")` |
### Example
```
#include <limits>
#include <iostream>
int main()
{
std::cout
<< "type\t│ lowest()\t│ min()\t\t│ max()\n"
<< "bool\t│ "
<< std::numeric_limits<bool>::lowest() << "\t\t│ "
<< std::numeric_limits<bool>::min() << "\t\t│ "
<< std::numeric_limits<bool>::max() << '\n'
<< "uchar\t│ "
<< +std::numeric_limits<unsigned char>::lowest() << "\t\t│ "
<< +std::numeric_limits<unsigned char>::min() << "\t\t│ "
<< +std::numeric_limits<unsigned char>::max() << '\n'
<< "int\t│ "
<< std::numeric_limits<int>::lowest() << "\t│ "
<< std::numeric_limits<int>::min() << "\t│ "
<< std::numeric_limits<int>::max() << '\n'
<< "float\t│ "
<< std::numeric_limits<float>::lowest() << "\t│ "
<< std::numeric_limits<float>::min() << "\t│ "
<< std::numeric_limits<float>::max() << '\n'
<< "double\t│ "
<< std::numeric_limits<double>::lowest() << "\t│ "
<< std::numeric_limits<double>::min() << "\t│ "
<< std::numeric_limits<double>::max() << '\n';
}
```
Possible output:
```
type │ lowest() │ min() │ max()
bool │ 0 │ 0 │ 1
uchar │ 0 │ 0 │ 255
int │ -2147483648 │ -2147483648 │ 2147483647
float │ -3.40282e+38 │ 1.17549e-38 │ 3.40282e+38
double │ -1.79769e+308 │ 2.22507e-308 │ 1.79769e+308
```
### See also
* [Fixed width integer types](integer "cpp/types/integer")
* [Arithmetic types](../language/types "cpp/language/types")
* [C++ type system overview](../language/type "cpp/language/type")
* [Type support (basic types, RTTI, type traits)](../types "cpp/types")
cpp std::remove_pointer std::remove\_pointer
====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_pointer;
```
| | (since C++11) |
Provides the member typedef `type` which is the type pointed to by `T`, or, if `T` is not a pointer, then `type` is the same as `T`.
The behavior of a program that adds specializations for `remove_pointer` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type pointed to by `T` or `T` if it's not a pointer |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_pointer_t = typename remove_pointer<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template< class T > struct remove_pointer {typedef T type;};
template< class T > struct remove_pointer<T*> {typedef T type;};
template< class T > struct remove_pointer<T* const> {typedef T type;};
template< class T > struct remove_pointer<T* volatile> {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};
```
|
### Example
```
#include <iostream>
#include <type_traits>
template<class T1, class T2>
void print_is_same()
{
std::cout << std::is_same<T1, T2>() << '\n';
}
void print_separator()
{
std::cout << "-----\n";
}
int main()
{
std::cout << std::boolalpha;
print_is_same<int, int>(); // true
print_is_same<int, int*>(); // false
print_is_same<int, int**>(); // false
print_separator();
print_is_same<int, std::remove_pointer<int>::type>(); // true
print_is_same<int, std::remove_pointer<int*>::type>(); // true
print_is_same<int, std::remove_pointer<int**>::type>(); // false
print_separator();
print_is_same<int, std::remove_pointer<int* const>::type>(); // true
print_is_same<int, std::remove_pointer<int* volatile>::type>(); // true
print_is_same<int, std::remove_pointer<int* const volatile>::type>(); // true
}
```
Output:
```
true
false
false
-----
true
true
false
-----
true
true
true
```
### See also
| | |
| --- | --- |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [add\_pointer](add_pointer "cpp/types/add pointer")
(C++11) | adds a pointer to the given type (class template) |
cpp std::is_pod std::is\_pod
============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_pod;
```
| | (since C++11) (deprecated in C++20) |
If `T` is a [POD type](../named_req/podtype "cpp/named req/PODType") ("plain old data type"), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type and not (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_pod` or `is_pod_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_pod_v = is_pod<T>::value;
```
| | (since C++17) (deprecated in C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a POD type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Example
```
#include <iostream>
#include <type_traits>
struct A
{
int m;
};
struct B
{
int m1;
private:
int m2;
};
struct C
{
virtual void foo();
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_pod<A>::value << '\n';
std::cout << std::is_pod<B>::value << '\n';
std::cout << std::is_pod<C>::value << '\n';
}
```
Output:
```
true
false
false
```
### See also
| | |
| --- | --- |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
| [is\_trivial](is_trivial "cpp/types/is trivial")
(C++11) | checks if a type is trivial (class template) |
| programming_docs |
cpp std::is_move_constructible, std::is_trivially_move_constructible, std::is_nothrow_move_constructible std::is\_move\_constructible, std::is\_trivially\_move\_constructible, std::is\_nothrow\_move\_constructible
============================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_move_constructible;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_move_constructible;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_move_constructible;
```
| (3) | (since C++11) |
1) If `T` is not a referenceable type (i.e., possibly cv-qualified `void` or a function type with a *cv-qualifier-seq* or a *ref-qualifier*), provides a member constant `value` equal to `false`. Otherwise, provides a member constant `value` equal to `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, T&&>::value`.
2) Same as (1), but uses `[std::is\_trivially\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, T&&>`.
3) Same as (1), but uses `[std::is\_nothrow\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, T&&>`. `T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_move_constructible_v = is_move_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_move_constructible_v = is_trivially_move_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_move_constructible_v = is_nothrow_move_constructible<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is move-constructible , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_move_constructible :
std::is_constructible<T, typename std::add_rvalue_reference<T>::type> {};
template<class T>
struct is_trivially_move_constructible :
std::is_trivially_constructible<T, typename std::add_rvalue_reference<T>::type> {};
template<class T>
struct is_nothrow_move_constructible :
std::is_nothrow_constructible<T, typename std::add_rvalue_reference<T>::type> {};
```
|
### Notes
Types without a move constructor, but with a copy constructor that accepts `const T&` arguments, satisfy `std::is_move_constructible`.
Move constructors are usually noexcept, since otherwise they are unusable in any code that provides strong exception guarantee.
In many implementations, `is_nothrow_move_constructible` also checks if the destructor throws because it is effectively `noexcept(T(arg))`. Same applies to `is_trivially_move_constructible`, which, in these implementations, also requires that the destructor is trivial: [GCC bug 51452](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452), [LWG issue 2116](https://cplusplus.github.io/LWG/issue2116).
### Example
```
#include <iostream>
#include <type_traits>
struct Ex1 {
std::string str; // member has a non-trivial but non-throwing move ctor
};
struct Ex2 {
int n;
Ex2(Ex2&&) = default; // trivial and non-throwing
};
struct NoMove {
// prevents implicit declaration of default move constructor
// however, the class is still move-constructible because its
// copy constructor can bind to an rvalue argument
NoMove(const NoMove&) {}
};
#define OUT(...) std::cout << #__VA_ARGS__ << " : " << __VA_ARGS__ << '\n'
int main() {
std::cout << std::boolalpha;
OUT( std::is_move_constructible_v<Ex1> );
OUT( std::is_trivially_move_constructible_v<Ex1> );
OUT( std::is_nothrow_move_constructible_v<Ex1> );
OUT( std::is_trivially_move_constructible_v<Ex2> );
OUT( std::is_nothrow_move_constructible_v<Ex2> );
OUT( std::is_move_constructible_v<NoMove> );
OUT( std::is_nothrow_move_constructible_v<NoMove> );
}
```
Output:
```
std::is_move_constructible_v<Ex1> : true
std::is_trivially_move_constructible_v<Ex1> : false
std::is_nothrow_move_constructible_v<Ex1> : true
std::is_trivially_move_constructible_v<Ex2> : true
std::is_nothrow_move_constructible_v<Ex2> : true
std::is_move_constructible_v<NoMove> : true
std::is_nothrow_move_constructible_v<NoMove> : false
```
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
| [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](is_default_constructible "cpp/types/is default constructible")
(C++11)(C++11)(C++11) | checks if a type has a default constructor (class template) |
| [is\_copy\_constructibleis\_trivially\_copy\_constructibleis\_nothrow\_copy\_constructible](is_copy_constructible "cpp/types/is copy constructible")
(C++11)(C++11)(C++11) | checks if a type has a copy constructor (class template) |
| [move\_constructible](../concepts/move_constructible "cpp/concepts/move constructible")
(C++20) | specifies that an object of a type can be move constructed (concept) |
| [move](../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
| [move\_if\_noexcept](../utility/move_if_noexcept "cpp/utility/move if noexcept")
(C++11) | obtains an rvalue reference if the move constructor does not throw (function template) |
cpp std::disjunction std::disjunction
================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template<class... B>
struct disjunction;
```
| | (since C++17) |
Forms the [logical disjunction](https://en.wikipedia.org/wiki/Logical_disjunction) of the type traits `B...`, effectively performing a logical OR on the sequence of traits.
The specialization `std::disjunction<B1, ..., BN>` has a public and unambiguous base that is.
* if `sizeof...(B) == 0`, `[std::false\_type](http://en.cppreference.com/w/cpp/types/integral_constant)`; otherwise
* the first type `Bi` in `B1, ..., BN` for which `bool(Bi::value) == true`, or `BN` if there is no such type.
The member names of the base class, other than `disjunction` and `operator=`, are not hidden and are unambiguously available in `disjunction`.
Disjunction is short-circuiting: if there is a template type argument `Bi` with `bool(Bi::value) != false`, then instantiating `disjunction<B1, ..., BN>::value` does not require the instantiation of `Bj::value` for `j > i`.
The behavior of a program that adds specializations for `disjunction` or `disjunction_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| B... | - | every template argument `Bi` for which `Bi::value` is instantiated must be usable as a base class and define member `value` that is convertible to `bool` |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template<class... B>
inline constexpr bool disjunction_v = disjunction<B...>::value;
```
| | (since C++17) |
### Possible implementation
| |
| --- |
|
```
template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };
```
|
### Notes
A specialization of `disjunction` does not necessarily inherit from of either `[std::true\_type](http://en.cppreference.com/w/cpp/types/integral_constant)` or `[std::false\_type](http://en.cppreference.com/w/cpp/types/integral_constant)`: it simply inherits from the first `B` whose `::value`, explicitly converted to `bool`, is true, or from the very last B when all of them convert to false. For example, `std::disjunction<[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, 2>, [std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, 4>>::value` is `2`.
The short-circuit instantiation differentiates `disjunction` from fold expressions: a fold expression like `(... || Bs::value)` instantiates every `B` in `Bs`, while `std::disjunction_v<Bs...>` stops instantiation once the value can be determined. This is particularly useful if the later type is expensive to instantiate or can cause a hard error when instantiated with the wrong type.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_logical_traits`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <type_traits>
#include <cstdint>
#include <string>
// values_equal<a, b, T>::value is true if and only if a == b.
template <auto V1, decltype(V1) V2, typename T>
struct values_equal : std::bool_constant<V1 == V2> {
using type = T;
};
// default_type<T>::value is always true
template <typename T>
struct default_type : std::true_type {
using type = T;
};
// Now we can use disjunction like a switch statement:
template <int I>
using int_of_size = typename std::disjunction< //
values_equal<I, 1, std::int8_t>, //
values_equal<I, 2, std::int16_t>, //
values_equal<I, 4, std::int32_t>, //
values_equal<I, 8, std::int64_t>, //
default_type<void> // must be last!
>::type;
static_assert(sizeof(int_of_size<1>) == 1);
static_assert(sizeof(int_of_size<2>) == 2);
static_assert(sizeof(int_of_size<4>) == 4);
static_assert(sizeof(int_of_size<8>) == 8);
static_assert(std::is_same_v<int_of_size<13>, void>);
// checking if Foo is constructible from double will cause a hard error
struct Foo {
template<class T>
struct sfinae_unfriendly_check { static_assert(!std::is_same_v<T, double>); };
template<class T>
Foo(T, sfinae_unfriendly_check<T> = {} );
};
template<class... Ts>
struct first_constructible {
template<class T, class...Args>
struct is_constructible_x : std::is_constructible<T, Args...> {
using type = T;
};
struct fallback {
static constexpr bool value = true;
using type = void; // type to return if nothing is found
};
template<class... Args>
using with = typename std::disjunction<is_constructible_x<Ts, Args...>...,
fallback>::type;
};
// OK, is_constructible<Foo, double> not instantiated
static_assert(std::is_same_v<first_constructible<std::string, int, Foo>::with<double>,
int>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<>, std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<const char*>,
std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<void*>, void>);
int main() { }
```
### See also
| | |
| --- | --- |
| [negation](negation "cpp/types/negation")
(C++17) | logical NOT metafunction (class template) |
| [conjunction](conjunction "cpp/types/conjunction")
(C++17) | variadic logical AND metafunction (class template) |
cpp std::is_scoped_enum std::is\_scoped\_enum
=====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_scoped_enum;
```
| | (since C++23) |
Checks whether `T` is a [scoped enumeration type](../language/enum#Scoped_enumerations "cpp/language/enum"). Provides the member constant `value` which is equal to `true`, if `T` is a scoped enumeration type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_scoped_enum` or `is_scoped_enum_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_scoped_enum_v = is_scoped_enum<T>::value;
```
| | (since C++23) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a scoped enumeration type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
As currently the standard allows the name of an enumeration type appears in its enum-base, for example, `enum class E : [std::enable\_if\_t](http://en.cppreference.com/w/cpp/types/enable_if)<std::is\_scoped\_enum\_v<E>, int> {};` is allowed, `std::is_scoped_enum` cannot be implemented without extensions, because scoped and unscoped enumeration types are indistinguishable in expressions when they are incomplete.
However, all known compilers consider an enumeration type is still undeclared in its enum-base. As a result, a scoped enumeration type can never be incomplete, and `std::is_scoped_enum` can be implemented like below. This is [CWG issue 2516](https://cplusplus.github.io/CWG/issues/2516.html).
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_scoped_enum`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
This implementation assumes that scoped enumeration types are always complete.
| |
| --- |
|
```
namespace detail {
namespace { // avoid ODR-violation
template<class T>
auto test_sizable(int) -> decltype(sizeof(T), std::true_type{});
template<class>
auto test_sizable(...) -> std::false_type;
template<class T>
auto test_nonconvertible_to_int(int)
-> decltype(static_cast<std::false_type (*)(int)>(nullptr)(std::declval<T>()));
template<class>
auto test_nonconvertible_to_int(...) -> std::true_type;
template<class T>
constexpr bool is_scoped_enum_impl = std::conjunction_v<
decltype(test_sizable<T>(0)),
decltype(test_nonconvertible_to_int<T>(0))
>;
}
} // namespace detail
template<class>
struct is_scoped_enum : std::false_type {};
template<class E>
requires std::is_enum_v<E>
struct is_scoped_enum<E> : std::bool_constant<detail::is_scoped_enum_impl<E>> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
enum E {};
enum struct Es { oz };
enum class Ec : int {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_scoped_enum_v<A> << '\n';
std::cout << std::is_scoped_enum_v<E> << '\n';
std::cout << std::is_scoped_enum_v<Es> << '\n';
std::cout << std::is_scoped_enum_v<Ec> << '\n';
std::cout << std::is_scoped_enum_v<int> << '\n';
}
```
Output:
```
false
false
true
true
false
```
### See also
| | |
| --- | --- |
| [is\_integral](is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
cpp std::type_identity std::type\_identity
===================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct type_identity;
```
| | (since C++20) |
Provides the member typedef `type` that names `T` (i.e., the identity transformation).
The behavior of a program that adds specializations for `type_identity` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using type_identity_t = typename type_identity<T>::type;
```
| | (since C++20) |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct type_identity {
using type = T;
};
```
|
### Notes
`type_identity` can be used to establish [non-deduced contexts](../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in template argument deduction.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_type_identity`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
template <class T>
T foo(T a, T b) {
return a + b;
}
template <class T>
T bar(T a, std::type_identity_t<T> b) {
return a + b;
}
int main() {
// foo(4.2, 1); // error, deduced conflicting types for 'T'
std::cout << bar(4.2, 1) << '\n'; // OK, calls bar<double>
}
```
Output:
```
5.2
```
cpp std::enable_if std::enable\_if
===============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< bool B, class T = void >
struct enable_if;
```
| | (since C++11) |
If `B` is `true`, `std::enable_if` has a public member typedef `type`, equal to `T`; otherwise, there is no member typedef.
This metafunction is a convenient way to leverage [SFINAE](../language/sfinae "cpp/language/sfinae") prior to C++20's [concepts](../language/constraints "cpp/language/constraints"), in particular for conditionally removing functions from the [candidate set](../language/overload_resolution "cpp/language/overload resolution") based on type traits, allowing separate function overloads or specializations based on those different type traits.
`std::enable_if` can be used in many forms, including:
* as an additional function argument (not applicable to operator overloads)
* as a return type (not applicable to constructors and destructors)
* as a class template or function template parameter
The behavior of a program that adds specializations for `enable_if` is undefined.
### Member types
| Type | Definition |
| --- | --- |
| `type` | either `T` or no such member, depending on the value of `B` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { typedef T type; };
```
|
### Notes
A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are treated as redeclarations of the same function template (default template arguments are not accounted for in [function template equivalence](../language/function_template#Function_template_overloading "cpp/language/function template")).
```
/* WRONG */
struct T {
enum { int_t, float_t } type;
template <typename Integer,
typename = std::enable_if_t<std::is_integral<Integer>::value>
>
T(Integer) : type(int_t) {}
template <typename Floating,
typename = std::enable_if_t<std::is_floating_point<Floating>::value>
>
T(Floating) : type(float_t) {} // error: treated as redefinition
};
/* RIGHT */
struct T {
enum { int_t, float_t } type;
template <typename Integer,
std::enable_if_t<std::is_integral<Integer>::value, bool> = true
>
T(Integer) : type(int_t) {}
template <typename Floating,
std::enable_if_t<std::is_floating_point<Floating>::value, bool> = true
>
T(Floating) : type(float_t) {} // OK
};
```
Care should be taken when using `enable_if` in the type of a template non-type parameter of a namespace-scope function template. Some ABI specifications like the Itanium ABI do not include the instantiation-dependent portions of non-type template parameters in the mangling, meaning that specializations of two distinct function templates might end up with the same mangled name and be erroneously linked together. For example:
```
// first translation unit
struct X {
enum { value1 = true, value2 = true };
};
template<class T, std::enable_if_t<T::value1, int> = 0>
void func() {} // #1
template void func<X>(); // #2
// second translation unit
struct X {
enum { value1 = true, value2 = true };
};
template<class T, std::enable_if_t<T::value2, int> = 0>
void func() {} // #3
template void func<X>(); //#4
```
The function templates #1 and #3 have different signatures and are distinct templates. Nonetheless, #2 and #4, despite being instantiations of different function templates, have the same mangled name [in the Itanium C++ ABI](https://github.com/itanium-cxx-abi/cxx-abi/issues/20) (`_Z4funcI1XLi0EEvv`), meaning that the linker will erroneously consider them to be the same entity.
### Example
```
#include <type_traits>
#include <new>
#include <iostream>
#include <string>
namespace detail {
void* voidify(const volatile void* ptr) noexcept { return const_cast<void*>(ptr); }
}
// #1, enabled via the return type
template<class T>
typename std::enable_if<std::is_trivially_default_constructible<T>::value>::type
construct(T*)
{
std::cout << "default constructing trivially default constructible T\n";
}
// same as above
template<class T>
typename std::enable_if<!std::is_trivially_default_constructible<T>::value>::type
construct(T* p)
{
std::cout << "default constructing non-trivially default constructible T\n";
::new(detail::voidify(p)) T;
}
// #2
template<class T, class... Args>
std::enable_if_t<std::is_constructible<T, Args&&...>::value> // Using helper type
construct(T* p, Args&&... args)
{
std::cout << "constructing T with operation\n";
::new(detail::voidify(p)) T(static_cast<Args&&>(args)...);
}
// #3, enabled via a parameter
template<class T>
void destroy(
T*,
typename std::enable_if<
std::is_trivially_destructible<T>::value
>::type* = 0
){
std::cout << "destroying trivially destructible T\n";
}
// #4, enabled via a non-type template parameter
template<class T,
typename std::enable_if<
!std::is_trivially_destructible<T>{} &&
(std::is_class<T>{} || std::is_union<T>{}),
bool>::type = true>
void destroy(T* t)
{
std::cout << "destroying non-trivially destructible T\n";
t->~T();
}
// #5, enabled via a type template parameter
template<class T,
typename = std::enable_if_t<std::is_array<T>::value> >
void destroy(T* t) // note: function signature is unmodified
{
for(std::size_t i = 0; i < std::extent<T>::value; ++i) {
destroy((*t)[i]);
}
}
/*
template<class T,
typename = std::enable_if_t<std::is_void<T>::value> >
void destroy(T* t){} // error: has the same signature with #5
*/
// the partial specialization of A is enabled via a template parameter
template<class T, class Enable = void>
class A {}; // primary template
template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
}; // specialization for floating point types
int main()
{
std::aligned_union_t<0,int,std::string> u;
construct(reinterpret_cast<int*>(&u));
destroy(reinterpret_cast<int*>(&u));
construct(reinterpret_cast<std::string*>(&u),"Hello");
destroy(reinterpret_cast<std::string*>(&u));
A<int>{}; // OK: matches the primary template
A<double>{}; // OK: matches the partial specialization
}
```
Output:
```
default constructing trivially default constructible T
destroying trivially destructible T
constructing T with operation
destroying non-trivially destructible T
```
### See also
| | |
| --- | --- |
| [void\_t](void_t "cpp/types/void t")
(C++17) | void variadic alias template (alias template) |
* [`static_assert`](../language/static_assert "cpp/language/static assert")
* [SFINAE](../language/sfinae "cpp/language/sfinae")
* [Constraints and Concepts](../language/constraints "cpp/language/constraints")
| programming_docs |
cpp std::is_function std::is\_function
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_function;
```
| | (since C++11) |
Checks whether `T` is a function type. Types like `[std::function](http://en.cppreference.com/w/cpp/utility/functional/function)`, lambdas, classes with overloaded `operator()` and pointers to functions don't count as function types. Provides the member constant `value` which is equal to `true`, if `T` is a function type. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_function` or `is_function_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_function_v = is_function<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a function type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
`std::is_function` can be implemented in much simpler ways. Implementations similar to the following one are used by new versions of [libc++](https://github.com/llvm-mirror/libcxx/blob/master/include/type_traits#L889), [libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/type_traits#L538) and [MS STL](https://github.com/microsoft/STL/pull/460):
```
template<class T>
struct is_function : std::integral_constant<
bool,
!std::is_const<const T>::value && !std::is_reference<T>::value
> {};
```
The implementation shown below is for pedagogical purposes, since it exhibits the myriad kinds of function types.
### Possible implementation
| |
| --- |
|
```
// primary template
template<class>
struct is_function : std::false_type { };
// specialization for regular functions
template<class Ret, class... Args>
struct is_function<Ret(Args...)> : std::true_type {};
// specialization for variadic functions such as std::printf
template<class Ret, class... Args>
struct is_function<Ret(Args......)> : std::true_type {};
// specialization for function types that have cv-qualifiers
template<class Ret, class... Args>
struct is_function<Ret(Args...) const> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile> : std::true_type {};
// specialization for function types that have ref-qualifiers
template<class Ret, class... Args>
struct is_function<Ret(Args...) &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile &> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile &&> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile &&> : std::true_type {};
// specializations for noexcept versions of all the above (C++17 and later)
template<class Ret, class... Args>
struct is_function<Ret(Args...) noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile & noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) volatile && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args...) const volatile && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) volatile && noexcept> : std::true_type {};
template<class Ret, class... Args>
struct is_function<Ret(Args......) const volatile && noexcept> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
struct A {
int fun() const&;
};
template<typename>
struct PM_traits {};
template<class T, class U>
struct PM_traits<U T::*> {
using member_type = U;
};
int f();
int main()
{
std::cout << std::boolalpha;
std::cout << "#1 " << std::is_function_v<A> << '\n';
std::cout << "#2 " << std::is_function_v<int(int)> << '\n';
std::cout << "#3 " << std::is_function_v<decltype(f)> << '\n';
std::cout << "#4 " << std::is_function_v<int> << '\n';
using T = PM_traits<decltype(&A::fun)>::member_type; // T is int() const&
std::cout << "#5 " << std::is_function_v<T> << '\n';
}
```
Output:
```
#1 false
#2 true
#3 true
#4 false
#5 true
```
### See also
| | |
| --- | --- |
| [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](is_invocable "cpp/types/is invocable")
(C++17) | checks if a type can be invoked (as if by `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`) with the given argument types (class template) |
| [is\_object](is_object "cpp/types/is object")
(C++11) | checks if a type is an object type (class template) |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
cpp std::is_unsigned std::is\_unsigned
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_unsigned;
```
| | (since C++11) |
If `T` is an integral type, provides the member constant `value` equal to `true` if `T(0) < T(-1)`: this results in `true` for the unsigned integer types and the type `bool` and in `false` for the signed integer types and the floating-point types.
For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_unsigned` or `is_unsigned_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_unsigned_v = is_unsigned<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an unsigned integral type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
namespace detail {
template<typename T,bool = std::is_arithmetic<T>::value>
struct is_unsigned : std::integral_constant<bool, T(0) < T(-1)> {};
template<typename T>
struct is_unsigned<T,false> : std::false_type {};
} // namespace detail
template<typename T>
struct is_unsigned : detail::is_unsigned<T>::type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
enum B : unsigned {};
enum class C : unsigned {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_unsigned<A>::value << '\n';
std::cout << std::is_unsigned<float>::value << '\n';
std::cout << std::is_unsigned<signed int>::value << '\n';
std::cout << std::is_unsigned<unsigned int>::value << '\n';
std::cout << std::is_unsigned<B>::value << '\n';
std::cout << std::is_unsigned<C>::value << '\n';
}
```
Output:
```
false
false
false
true
false
false
```
### See also
| | |
| --- | --- |
| [is\_signed](is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [make\_signed](make_signed "cpp/types/make signed")
(C++11) | makes the given integral type signed (class template) |
| [make\_unsigned](make_unsigned "cpp/types/make unsigned")
(C++11) | makes the given integral type unsigned (class template) |
cpp std::conjunction std::conjunction
================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template<class... B>
struct conjunction;
```
| | (since C++17) |
Forms the [logical conjunction](https://en.wikipedia.org/wiki/Logical_conjunction) of the type traits `B...`, effectively performing a logical AND on the sequence of traits.
The specialization `std::conjunction<B1, ..., BN>` has a public and unambiguous base that is.
* if `sizeof...(B) == 0`, `[std::true\_type](http://en.cppreference.com/w/cpp/types/integral_constant)`; otherwise
* the first type `Bi` in `B1, ..., BN` for which `bool(Bi::value) == false`, or `BN` if there is no such type.
The member names of the base class, other than `conjunction` and `operator=`, are not hidden and are unambiguously available in `conjunction`.
Conjunction is short-circuiting: if there is a template type argument `Bi` with `bool(Bi::value) == false`, then instantiating `conjunction<B1, ..., BN>::value` does not require the instantiation of `Bj::value` for `j > i`.
The behavior of a program that adds specializations for `conjunction` or `conjunction_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| B... | - | every template argument `Bi` for which `Bi::value` is instantiated must be usable as a base class and define member `value` that is convertible to `bool` |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template<class... B>
inline constexpr bool conjunction_v = conjunction<B...>::value;
```
| | (since C++17) |
### Possible implementation
| |
| --- |
|
```
template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), conjunction<Bn...>, B1> {};
```
|
### Notes
A specialization of `conjunction` does not necessarily inherit from either `[std::true\_type](http://en.cppreference.com/w/cpp/types/integral_constant)` or `[std::false\_type](http://en.cppreference.com/w/cpp/types/integral_constant)`: it simply inherits from the first `B` whose `::value`, explicitly converted to bool, is false, or from the very last `B` when all of them convert to true. For example, `std::conjunction<[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, 2>, [std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<int, 4>>::value` is `4`.
The short-circuit instantiation differentiates `conjunction` from fold expressions: a fold expression like `(... && Bs::value)` instantiates every `B` in `Bs`, while `std::conjunction_v<Bs...>` stops instantiation once the value can be determined. This is particularly useful if the later type is expensive to instantiate or can cause a hard error when instantiated with the wrong type.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_logical_traits`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
// func is enabled if all Ts... have the same type as T
template<typename T, typename... Ts>
std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...>>
func(T, Ts...) {
std::cout << "all types in pack are T\n";
}
// otherwise
template<typename T, typename... Ts>
std::enable_if_t<!std::conjunction_v<std::is_same<T, Ts>...>>
func(T, Ts...) {
std::cout << "not all types in pack are T\n";
}
int main() {
func(1, 2, 3);
func(1, 2, "hello!");
}
```
Output:
```
all types in pack are T
not all types in pack are T
```
### See also
| | |
| --- | --- |
| [negation](negation "cpp/types/negation")
(C++17) | logical NOT metafunction (class template) |
| [disjunction](disjunction "cpp/types/disjunction")
(C++17) | variadic logical OR metafunction (class template) |
cpp std::make_unsigned std::make\_unsigned
===================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct make_unsigned;
```
| | (since C++11) |
If `T` is an integral (except `bool`) or enumeration type, provides the member typedef `type` which is the unsigned integer type corresponding to `T`, with the same cv-qualifiers.
If `T` is signed or unsigned `char`, `short`, `int`, `long`, `long long`; the unsigned type from this list corresponding to `T` is provided.
If `T` is an enumeration type or `char`, `wchar_t`, `char8_t` (since C++20), `char16_t`, `char32_t`; the unsigned integer type with the smallest [rank](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") having the same `sizeof` as `T` is provided.
| | |
| --- | --- |
| Otherwise, the behavior is undefined. | (until C++20) |
| Otherwise, the program is ill-formed. | (since C++20) |
The behavior of a program that adds specializations for `make_unsigned` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the unsigned integer type corresponding to `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using make_unsigned_t = typename make_unsigned<T>::type;
```
| | (since C++14) |
### Example
```
#include <iostream>
#include <type_traits>
int main() {
typedef std::make_unsigned<char>::type char_type;
typedef std::make_unsigned<int>::type int_type;
typedef std::make_unsigned<volatile long>::type long_type;
bool ok1 = std::is_same<char_type, unsigned char>::value;
bool ok2 = std::is_same<int_type, unsigned int>::value;
bool ok3 = std::is_same<long_type, volatile unsigned long>::value;
std::cout << std::boolalpha
<< "char_type is 'unsigned char'? : " << ok1 << '\n'
<< "int_type is 'unsigned int'? : " << ok2 << '\n'
<< "long_type is 'volatile unsigned long'? : " << ok3 << '\n';
}
```
Output:
```
char_type is 'unsigned char'? : true
int_type is 'unsigned int'? : true
long_type is 'volatile unsigned long'? : true
```
### See also
| | |
| --- | --- |
| [is\_signed](is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
| [is\_unsigned](is_unsigned "cpp/types/is unsigned")
(C++11) | checks if a type is an unsigned arithmetic type (class template) |
| [make\_signed](make_signed "cpp/types/make signed")
(C++11) | makes the given integral type signed (class template) |
cpp std::is_member_pointer std::is\_member\_pointer
========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_member_pointer;
```
| | (since C++11) |
If `T` is pointer to non-static member object or a pointer to non-static member function, provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_member_pointer` or `is_member_pointer_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_member_pointer_v = is_member_pointer<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a member pointer type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_member_pointer_helper : std::false_type {};
template< class T, class U >
struct is_member_pointer_helper<T U::*> : std::true_type {};
template< class T >
struct is_member_pointer :
is_member_pointer_helper<typename std::remove_cv<T>::type> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main() {
class cls {};
std::cout << (std::is_member_pointer<int(cls::*)>::value
? "T is member pointer"
: "T is not a member pointer") << '\n';
std::cout << (std::is_member_pointer<int>::value
? "T is member pointer"
: "T is not a member pointer") << '\n';
}
```
Output:
```
T is member pointer
T is not a member pointer
```
### See also
| | |
| --- | --- |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [is\_member\_object\_pointer](is_member_object_pointer "cpp/types/is member object pointer")
(C++11) | checks if a type is a pointer to a non-static member object (class template) |
| [is\_member\_function\_pointer](is_member_function_pointer "cpp/types/is member function pointer")
(C++11) | checks if a type is a pointer to a non-static member function (class template) |
| programming_docs |
cpp std::is_same std::is\_same
=============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct is_same;
```
| | (since C++11) |
If `T` and `U` name the same type (taking into account const/volatile qualifications), provides the member constant `value` equal to `true`. Otherwise `value` is `false`.
Commutativity is satisfied, i.e. for any two types `T` and `U`, `is_same<T, U>::value == true` if and only if `is_same<U, T>::value == true`.
The behavior of a program that adds specializations for `is_same` or `is_same_v` (since C++17) is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, class U >
inline constexpr bool is_same_v = is_same<T, U>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` and `U` are the same type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T, class U>
struct is_same : std::false_type {};
template<class T>
struct is_same<T, T> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
#include <cstdint>
void print_separator()
{
std::cout << "-----\n";
}
int main()
{
std::cout << std::boolalpha;
// some implementation-defined facts
// usually true if 'int' is 32 bit
std::cout << std::is_same<int, std::int32_t>::value << ' '; // ~ true
// possibly true if ILP64 data model is used
std::cout << std::is_same<int, std::int64_t>::value << ' '; // ~ false
// same tests as above, except using C++17's `std::is_same_v<T, U>` format
std::cout << std::is_same_v<int, std::int32_t> << ' '; // ~ true
std::cout << std::is_same_v<int, std::int64_t> << '\n'; // ~ false
print_separator();
// compare the types of a couple variables
long double num1 = 1.0;
long double num2 = 2.0;
std::cout << std::is_same_v<decltype(num1), decltype(num2)> << '\n'; // true
print_separator();
// 'float' is never an integral type
std::cout << std::is_same<float, std::int32_t>::value << '\n'; // false
print_separator();
// 'int' is implicitly 'signed'
std::cout << std::is_same<int, int>::value << ' '; // true
std::cout << std::is_same<int, unsigned int>::value << ' '; // false
std::cout << std::is_same<int, signed int>::value << '\n'; // true
print_separator();
// unlike other types, 'char' is neither 'unsigned' nor 'signed'
std::cout << std::is_same<char, char>::value << ' '; // true
std::cout << std::is_same<char, unsigned char>::value << ' '; // false
std::cout << std::is_same<char, signed char>::value << '\n'; // false
// const-qualified type T is not same as non-const T
static_assert( not std::is_same<const int, int>() );
}
```
Possible output:
```
true false true false
-----
true
-----
false
-----
true false true
-----
true false false
```
### See also
| | |
| --- | --- |
| [same\_as](../concepts/same_as "cpp/concepts/same as")
(C++20) | specifies that a type is the same as another type (concept) |
| [`decltype` specifier](../language/decltype "cpp/language/decltype")(C++11) | obtains the type of an expression or an entity |
cpp std::negation std::negation
=============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template<class B>
struct negation;
```
| | (since C++17) |
Forms the [logical negation](https://en.wikipedia.org/wiki/Negation) of the type trait `B`.
The type `std::negation<B>` is a [UnaryTypeTrait](../named_req/unarytypetrait "cpp/named req/UnaryTypeTrait") with a base characteristic of `[std::bool\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<!bool(B::value)>`.
The behavior of a program that adds specializations for `negation` or `negation_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| B | - | any type such that the expression `bool(B::value)` is a valid constant expression |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template<class B>
inline constexpr bool negation_v = negation<B>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `B` has a member `::value` that is `false` when explicitly converted to `bool` , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class B>
struct negation : std::bool_constant<!bool(B::value)> { };
```
|
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_logical_traits`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
static_assert(
std::is_same<
std::bool_constant<false>,
typename std::negation<std::bool_constant<true>>::type>::value,
"");
static_assert(
std::is_same<
std::bool_constant<true>,
typename std::negation<std::bool_constant<false>>::type>::value,
"");
int main()
{
std::cout << std::boolalpha;
std::cout << std::negation<std::bool_constant<true>>::value << '\n';
std::cout << std::negation<std::bool_constant<false>>::value << '\n';
}
```
Output:
```
false
true
```
### See also
| | |
| --- | --- |
| [conjunction](conjunction "cpp/types/conjunction")
(C++17) | variadic logical AND metafunction (class template) |
| [disjunction](disjunction "cpp/types/disjunction")
(C++17) | variadic logical OR metafunction (class template) |
| [integral\_constantbool\_constant](integral_constant "cpp/types/integral constant")
(C++11)(C++17) | compile-time constant of specified type with specified value (class template) |
cpp std::add_pointer std::add\_pointer
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct add_pointer;
```
| | (since C++11) |
If `T` is a reference type, then provides the member typedef `type` which is a pointer to the referred type.
Otherwise, if T names an object type, a function type that is not cv- or ref-qualified, or a (possibly cv-qualified) void type, provides the member typedef `type` which is the type `T*`.
Otherwise (if T is a cv- or ref-qualified function type), provides the member typedef `type` which is the type `T`.
The behavior of a program that adds specializations for `add_pointer` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | pointer to `T` or to the type referenced by `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using add_pointer_t = typename add_pointer<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T>
auto try_add_pointer(int) -> type_identity<typename std::remove_reference<T>::type*>;
template <class T>
auto try_add_pointer(...) -> type_identity<T>;
} // namespace detail
template <class T>
struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
template<typename F, typename Class>
void ptr_to_member_func_cvref_test(F Class::*)
{
// F is an "abominable function type"
using FF = std::add_pointer_t<F>;
static_assert(std::is_same_v<F, FF>, "FF should be precisely F");
}
struct S
{
void f_ref() & {}
void f_const() const {}
};
int main()
{
int i = 123;
int& ri = i;
typedef std::add_pointer<decltype(i)>::type IntPtr;
typedef std::add_pointer<decltype(ri)>::type IntPtr2;
IntPtr pi = &i;
std::cout << "i = " << i << "\n";
std::cout << "*pi = " << *pi << "\n";
static_assert(std::is_pointer<IntPtr>::value, "IntPtr should be a pointer");
static_assert(std::is_same<IntPtr, int*>::value, "IntPtr should be a pointer to int");
static_assert(std::is_same<IntPtr2, IntPtr>::value, "IntPtr2 should be equal to IntPtr");
typedef std::remove_pointer<IntPtr>::type IntAgain;
IntAgain j = i;
std::cout << "j = " << j << "\n";
static_assert(!std::is_pointer<IntAgain>::value, "IntAgain should not be a pointer");
static_assert(std::is_same<IntAgain, int>::value, "IntAgain should be equal to int");
ptr_to_member_func_cvref_test(&S::f_ref);
ptr_to_member_func_cvref_test(&S::f_const);
}
```
Output:
```
i = 123
*pi = 123
j = 123
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2101](https://cplusplus.github.io/LWG/issue2101) | C++11 | `std::add_pointer` was required to producepointer to cv-/ref-qualified function types. | Produces cv-/ref-qualified function types themselves. |
### See also
| | |
| --- | --- |
| [is\_pointer](is_pointer "cpp/types/is pointer")
(C++11) | checks if a type is a pointer type (class template) |
| [remove\_pointer](remove_pointer "cpp/types/remove pointer")
(C++11) | removes a pointer from the given type (class template) |
cpp std::is_base_of std::is\_base\_of
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class Base, class Derived >
struct is_base_of;
```
| | (since C++11) |
If `Derived` is derived from `Base` or if both are the same non-union class (in both cases ignoring cv-qualification), provides the member constant `value` equal to `true`. Otherwise `value` is `false`.
If both `Base` and `Derived` are non-union class types, and they are not the same type (ignoring cv-qualification), `Derived` shall be a [complete type](../language/incomplete_type "cpp/language/incomplete type"); otherwise the behavior is undefined.
The behavior of a program that adds specializations for `is_base_of` or `is_base_of_v` (since C++17) is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class Base, class Derived >
inline constexpr bool is_base_of_v = is_base_of<Base, Derived>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `Derived` is derived from `Base` or if both are the same non-union class (in both cases ignoring cv-qualification), `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
`std::is_base_of<A, B>::value` is `true` even if `A` is a private, protected, or ambiguous base class of `B`. In many situations, `[std::is\_convertible](http://en.cppreference.com/w/cpp/types/is_convertible)<B\*, A\*>` is the more appropriate test.
Although no class is its own base, `std::is_base_of<T, T>::value` is true because the intent of the trait is to model the "is-a" relationship, and T is a T. Despite that, `std::is_base_of<int, int>::value` is false because only classes participate in the relationship that this trait models.
### Possible Implementation
| |
| --- |
|
```
namespace details {
template <typename B>
std::true_type test_pre_ptr_convertible(const volatile B*);
template <typename>
std::false_type test_pre_ptr_convertible(const volatile void*);
template <typename, typename>
auto test_pre_is_base_of(...) -> std::true_type;
template <typename B, typename D>
auto test_pre_is_base_of(int) ->
decltype(test_pre_ptr_convertible<B>(static_cast<D*>(nullptr)));
}
template <typename Base, typename Derived>
struct is_base_of :
std::integral_constant<
bool,
std::is_class<Base>::value && std::is_class<Derived>::value &&
decltype(details::test_pre_is_base_of<Base, Derived>(0))::value
> { };
```
|
### Example
```
#include <iostream>
#include <type_traits>
#define SHOW(...) \
std::cout << #__VA_ARGS__ << " : " \
<< std:: __VA_ARGS__ << '\n'
int main()
{
class A {};
class B : A {};
class C : B {};
class D {};
std::cout << std::boolalpha;
SHOW( is_base_of_v<A, A> );
SHOW( is_base_of_v<A, B> );
SHOW( is_base_of_v<A, C> );
SHOW( is_base_of_v<A, D> );
SHOW( is_base_of_v<B, A> );
SHOW( is_base_of_v<int, int> );
}
```
Output:
```
is_base_of_v<A, A> : true
is_base_of_v<A, B> : true
is_base_of_v<A, C> : true
is_base_of_v<A, D> : false
is_base_of_v<B, A> : false
is_base_of_v<int, int> : false
```
### See also
| | |
| --- | --- |
| [is\_convertibleis\_nothrow\_convertible](is_convertible "cpp/types/is convertible")
(C++11)(C++20) | checks if a type can be converted to the other type (class template) |
| [derived\_from](../concepts/derived_from "cpp/concepts/derived from")
(C++20) | specifies that a type is derived from another type (concept) |
cpp std::is_layout_compatible std::is\_layout\_compatible
===========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct is_layout_compatible;
```
| | (since C++20) |
If `T` and `U` are [*layout-compatible*](../language/data_members#Standard_layout "cpp/language/data members") types, provides the member constant `value` equal to `true`. Otherwise `value` is `false`.
Every type is layout-compatible with its any cv-qualified versions, even if it is not an object type.
`T` and `U` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for `is_layout_compatible` or `is_layout_compatible_v` is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, class U >
inline constexpr bool is_layout_compatible_v = is_layout_compatible<T, U>::value;
```
| | (since C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` and `U` are layout-compatible, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
A signed integer type and its unsigned counterpart are not layout-compatible. `char` is layout-compatible with neither `signed char` nor `unsigned char`.
[Similar types](../language/reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast") are not layout-compatible if they are not the same type after ignoring top-level cv-qualification.
An enumeration type and its underlying type are not layout-compatible.
Array types of layout-compatible but different element types (ignoring cv-qualification) are not layout-compatible, even if they are of equal length.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_layout_compatible`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <type_traits>
#include <iomanip>
#include <iostream>
struct Foo {
int x;
char y;
};
class Bar {
const int u = 42;
volatile char v = '*';
};
enum E0 : int {};
enum class E1 : int {};
#define SHOW(...) std::cout << std::setw(54) << #__VA_ARGS__ << " = " << __VA_ARGS__ << '\n'
int main()
{
std::cout << std::boolalpha << std::left;
SHOW(std::is_layout_compatible_v<const void, volatile void>);
SHOW(std::is_layout_compatible_v<Foo, Bar>);
SHOW(std::is_layout_compatible_v<Foo[2], Bar[2]>);
SHOW(std::is_layout_compatible_v<int, E0>);
SHOW(std::is_layout_compatible_v<E0, E1>);
SHOW(std::is_layout_compatible_v<long, unsigned long>);
SHOW(std::is_layout_compatible_v<char*, const char*>);
SHOW(std::is_layout_compatible_v<char*, char* const>);
}
```
Output:
```
std::is_layout_compatible_v<const void, volatile void> = true
std::is_layout_compatible_v<Foo, Bar> = true
std::is_layout_compatible_v<Foo[2], Bar[2]> = false
std::is_layout_compatible_v<int, E0> = false
std::is_layout_compatible_v<E0, E1> = true
std::is_layout_compatible_v<long, unsigned long> = false
std::is_layout_compatible_v<char*, const char*> = false
std::is_layout_compatible_v<char*, char* const> = true
```
### See also
| | |
| --- | --- |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
cpp std::is_corresponding_member std::is\_corresponding\_member
==============================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template<class S1, class S2, class M1, class M2>
constexpr bool is_corresponding_member( M1 S1::* mp, M2 S2::* mq ) noexcept;
```
| | (since C++20) |
Determines whether `mp` and `mq` refer corresponding members in the [common initial sequence](../language/data_members#Standard_layout "cpp/language/data members") of `S1` and `S2`. The program is ill-formed if either `S1` or `S2` is an [incomplete type](../language/type#Incomplete_type "cpp/language/type").
If either `S1` or `S2` is not a [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"), or either `M1` or `M2` is not an object type, or either `mp` or `mq` is equal to `nullptr`, the result is always `false`.
### Parameters
| | | |
| --- | --- | --- |
| mp, mq | - | pointers-to-member to detect |
### Return value
`true` if `mp` and `mq` refer corresponding members in the common initial sequence of `S1` and `S2`, otherwise `false`.
### Notes
The type of a pointer-to-member expression `&S::m` is not always `M S::*`, where `m` is of type `M`, because `m` may be a member inherited from a base class of `S`. The template arguments can be specified in order to avoid potentially surprising results.
### Example
```
#include <type_traits>
#include <iostream>
struct Foo { int x; };
struct Bar { int y; double z; };
struct Baz : Foo, Bar {}; // not standard-layout
int main()
{
std::cout << std::boolalpha
<< std::is_same_v<decltype(&Baz::x), int Foo::*> << '\n'
<< std::is_same_v<decltype(&Baz::y), int Bar::*> << '\n'
<< std::is_corresponding_member(&Foo::x, &Bar::y) << '\n'
<< std::is_corresponding_member(&Baz::x, &Baz::y) << '\n'
<< std::is_corresponding_member<Baz, Baz, int, int>(&Baz::x, &Baz::y) << '\n';
}
```
Output:
```
true
true
true
true
false
```
### See also
| | |
| --- | --- |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
| [is\_layout\_compatible](is_layout_compatible "cpp/types/is layout compatible")
(C++20) | checks if two types are [*layout-compatible*](../language/data_members#Standard_layout "cpp/language/data members") (class template) |
| [is\_member\_object\_pointer](is_member_object_pointer "cpp/types/is member object pointer")
(C++11) | checks if a type is a pointer to a non-static member object (class template) |
| programming_docs |
cpp std::is_copy_constructible, std::is_trivially_copy_constructible, std::is_nothrow_copy_constructible std::is\_copy\_constructible, std::is\_trivially\_copy\_constructible, std::is\_nothrow\_copy\_constructible
============================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_copy_constructible;
```
| (1) | (since C++11) |
|
```
template< class T >
struct is_trivially_copy_constructible;
```
| (2) | (since C++11) |
|
```
template< class T >
struct is_nothrow_copy_constructible;
```
| (3) | (since C++11) |
1) If `T` is not a referenceable type (i.e., possibly cv-qualified `void` or a function type with a *cv-qualifier-seq* or a *ref-qualifier*), provides a member constant `value` equal to `false`. Otherwise, provides a member constant `value` equal to `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const T&>::value`.
2) Same as (1), but uses `[std::is\_trivially\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const T&>`.
3) Same as (1), but uses `[std::is\_nothrow\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T, const T&>`. `T` shall be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_copy_constructible_v = is_copy_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_trivially_copy_constructible_v = is_trivially_copy_constructible<T>::value;
```
| | (since C++17) |
|
```
template< class T >
inline constexpr bool is_nothrow_copy_constructible_v = is_nothrow_copy_constructible<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is copy-constructible , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_copy_constructible :
std::is_constructible<T, typename std::add_lvalue_reference<
typename std::add_const<T>::type>::type> {};
template<class T>
struct is_trivially_copy_constructible :
std::is_trivially_constructible<T, typename std::add_lvalue_reference<
typename std::add_const<T>::type>::type> {};
template<class T>
struct is_nothrow_copy_constructible :
std::is_nothrow_constructible<T, typename std::add_lvalue_reference<
typename std::add_const<T>::type>::type> {};
```
|
### Notes
In many implementations, `is_nothrow_copy_constructible` also checks if the destructor throws because it is effectively `noexcept(T(arg))`. Same applies to `is_trivially_copy_constructible`, which, in these implementations, also requires that the destructor is trivial: [GCC bug 51452](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452), [LWG issue 2116](https://cplusplus.github.io/LWG/issue2116).
### Example
```
#include <iostream>
#include <type_traits>
struct Ex1 {
std::string str; // member has a non-trivial copy ctor
};
struct Ex2 {
int n;
Ex2(const Ex2&) = default; // trivial and non-throwing
};
int main() {
std::cout << std::boolalpha << "Ex1 is copy-constructible? "
<< std::is_copy_constructible<Ex1>::value << '\n'
<< "Ex1 is trivially copy-constructible? "
<< std::is_trivially_copy_constructible<Ex1>::value << '\n'
<< "Ex2 is trivially copy-constructible? "
<< std::is_trivially_copy_constructible<Ex2>::value << '\n'
<< "Ex2 is nothrow copy-constructible? "
<< std::is_nothrow_copy_constructible<Ex2>::value << '\n';
}
```
Output:
```
Ex1 is copy-constructible? true
Ex1 is trivially copy-constructible? false
Ex2 is trivially copy-constructible? true
Ex2 is nothrow copy-constructible? true
```
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
| [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](is_default_constructible "cpp/types/is default constructible")
(C++11)(C++11)(C++11) | checks if a type has a default constructor (class template) |
| [is\_move\_constructibleis\_trivially\_move\_constructibleis\_nothrow\_move\_constructible](is_move_constructible "cpp/types/is move constructible")
(C++11)(C++11)(C++11) | checks if a type can be constructed from an rvalue reference (class template) |
| [copy\_constructible](../concepts/copy_constructible "cpp/concepts/copy constructible")
(C++20) | specifies that an object of a type can be copy constructed and move constructed (concept) |
cpp std::is_empty std::is\_empty
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_empty;
```
| | (since C++11) |
If `T` is an empty type (that is, a non-union class type with no non-static data members other than bit-fields of size 0, no virtual functions, no virtual base classes, and no non-empty base classes), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
If `T` is a non-union class type, `T` shall be a complete type; otherwise, the behavior is undefined.
The behavior of a program that adds specializations for `is_empty` or `is_empty_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_empty_v = is_empty<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an empty class type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Inheriting from empty base classes usually does not increase the size of a class due to [empty base optimization](../language/ebo "cpp/language/ebo").
`std::is_empty<T>` and all other type traits are empty classes.
### Example
```
#include <iostream>
#include <type_traits>
struct A {};
struct B {
int m;
};
struct C {
static int m;
};
struct D {
virtual ~D();
};
union E {};
struct F {
[[no_unique_address]] E e;
};
struct G {
int:0;
// C++ standard allow "as a special case, an unnamed bit-field with a width of zero
// specifies alignment of the next bit-field at an allocation unit boundary.
// Only when declaring an unnamed bit-field may the width be zero."
};
int main()
{
std::cout << std::boolalpha;
std::cout << "A " << std::is_empty<A>::value << '\n';
std::cout << "B " << std::is_empty<B>::value << '\n';
std::cout << "C " << std::is_empty<C>::value << '\n';
std::cout << "D " << std::is_empty<D>::value << '\n';
std::cout << "E " << std::is_empty<E>::value << '\n';
std::cout << "F " << std::is_empty<F>::value << '\n'; // the result is ABI-dependent
std::cout << "G " << std::is_empty<G>::value << '\n'; // unnamed bit-fields of width of 0
}
```
Possible output:
```
A true
B false
C true
D false
E false
F true
G true
```
### See also
| | |
| --- | --- |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
cpp std::has_unique_object_representations std::has\_unique\_object\_representations
=========================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct has_unique_object_representations;
```
| | (since C++17) |
If `T` is [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") and if any two objects of type `T` with the same value have the same [object representation](../language/object#Object_representation_and_value_representation "cpp/language/object"), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
For the purpose of this trait, two arrays have the same value if their elements have the same values, two non-union classes have the same value if their direct subobjects have the same value, and two unions have the same value if they have the same active member and the value of that member is the same.
It is implementation-defined which scalar types satisfy this trait, but unsigned (until C++20) integer types that do not use padding bits are guaranteed to have unique object representations.
The behavior is undefined if `T` is an incomplete type other than (possibly cv-qualified) `void` or array of unknown bound.
The behavior of a program that adds specializations for `has_unique_object_representations` or `has_unique_object_representations_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool has_unique_object_representations_v = has_unique_object_representations<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` has unique object representations , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
This trait was introduced to make it possible to determine whether a type can be correctly hashed by hashing its object representation as a byte array.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_has_unique_object_representations`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
struct foo
{
char c;
float f;
short st;
int i;
};
struct bar
{
int a;
int b;
};
int main()
{
std::cout << std::boolalpha
<< "Does foo have unique object representations? "
<< std::has_unique_object_representations_v<foo> << '\n'
<< "Does bar have unique object representations? "
<< std::has_unique_object_representations_v<bar> << '\n';
}
```
Possible output:
```
Does foo have unique object representations? false
Does bar have unique object representations? true
```
### See also
| | |
| --- | --- |
| [is\_standard\_layout](is_standard_layout "cpp/types/is standard layout")
(C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) |
| [hash](../utility/hash "cpp/utility/hash")
(C++11) | hash function object (class template) |
cpp std::is_signed std::is\_signed
===============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_signed;
```
| | (since C++11) |
If `T` is an arithmetic type, provides the member constant `value` equal to `true` if `T(-1) < T(0)`: this results in `true` for the floating-point types and the signed integer types, and in `false` for the unsigned integer types and the type `bool`.
For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_signed` or `is_signed_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_signed_v = is_signed<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a signed arithmetic type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
namespace detail {
template<typename T,bool = std::is_arithmetic<T>::value>
struct is_signed : std::integral_constant<bool, T(-1) < T(0)> {};
template<typename T>
struct is_signed<T,false> : std::false_type {};
} // namespace detail
template<typename T>
struct is_signed : detail::is_signed<T>::type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
enum B : int {};
enum class C : int {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_signed<A>::value << '\n'; // false
std::cout << std::is_signed<float>::value << '\n'; // true
std::cout << std::is_signed<signed int>::value << '\n'; // true
std::cout << std::is_signed<unsigned int>::value << '\n'; // false
std::cout << std::is_signed<B>::value << '\n'; // false
std::cout << std::is_signed<C>::value << '\n'; // false
// shorter:
std::cout << std::is_signed_v<bool> << '\n'; // false
std::cout << std::is_signed<signed int>() << '\n'; // true
std::cout << std::is_signed<unsigned int>{} << '\n'; // false
}
```
Output:
```
false
true
true
false
false
false
false
true
false
```
### See also
| | |
| --- | --- |
| [is\_unsigned](is_unsigned "cpp/types/is unsigned")
(C++11) | checks if a type is an unsigned arithmetic type (class template) |
| [is\_signed](numeric_limits/is_signed "cpp/types/numeric limits/is signed")
[static] | identifies signed types (public static member constant of `std::numeric_limits<T>`) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [make\_signed](make_signed "cpp/types/make signed")
(C++11) | makes the given integral type signed (class template) |
| [make\_unsigned](make_unsigned "cpp/types/make unsigned")
(C++11) | makes the given integral type unsigned (class template) |
cpp std::remove_cv, std::remove_const, std::remove_volatile std::remove\_cv, std::remove\_const, std::remove\_volatile
==========================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_cv;
```
| (1) | (since C++11) |
|
```
template< class T >
struct remove_const;
```
| (2) | (since C++11) |
|
```
template< class T >
struct remove_volatile;
```
| (3) | (since C++11) |
Provides the member typedef `type` which is the same as `T`, except that its topmost cv-qualifiers are removed.
1) removes the topmost `const`, or the topmost `volatile`, or both, if present.
2) removes the topmost `const`
3) removes the topmost `volatile`
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type `T` without cv-qualifier |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_cv_t = typename remove_cv<T>::type;
```
| | (since C++14) |
|
```
template< class T >
using remove_const_t = typename remove_const<T>::type;
```
| | (since C++14) |
|
```
template< class T >
using remove_volatile_t = typename remove_volatile<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template< class T > struct remove_cv { typedef T type; };
template< class T > struct remove_cv<const T> { typedef T type; };
template< class T > struct remove_cv<volatile T> { typedef T type; };
template< class T > struct remove_cv<const volatile T> { typedef T type; };
template< class T > struct remove_const { typedef T type; };
template< class T > struct remove_const<const T> { typedef T type; };
template< class T > struct remove_volatile { typedef T type; };
template< class T > struct remove_volatile<volatile T> { typedef T type; };
```
|
### Example
Removing const/volatile from `const volatile int *` does not modify the type, because the pointer itself is neither const nor volatile.
```
#include <iostream>
#include <type_traits>
template<typename U, typename V> constexpr bool same = std::is_same_v<U, V>;
static_assert(
same< std::remove_cv_t< int >, int >
and same< std::remove_cv_t< const int >, int >
and same< std::remove_cv_t< volatile int >, int >
and same< std::remove_cv_t< const volatile int >, int >
and same< std::remove_cv_t< const volatile int* >, const volatile int* >
and same< std::remove_cv_t< const int* volatile >, const int* >
and same< std::remove_cv_t< int* const volatile >, int* >
);
int main() {
std::cout << std::boolalpha;
using type1 = std::remove_cv<const int>::type;
using type2 = std::remove_cv<volatile int>::type;
using type3 = std::remove_cv<const volatile int>::type;
using type4 = std::remove_cv<const volatile int*>::type;
using type5 = std::remove_cv<int* const volatile>::type;
std::cout << std::is_same<type1, int>::value << "\n";
std::cout << std::is_same<type2, int>::value << "\n";
std::cout << std::is_same<type3, int>::value << "\n";
std::cout << std::is_same<type4, int*>::value << " "
<< std::is_same<type4, const volatile int*>::value << "\n";
std::cout << std::is_same<type5, int*>::value << "\n";
}
```
Output:
```
true
true
true
false true
true
```
### See also
| | |
| --- | --- |
| [is\_const](is_const "cpp/types/is const")
(C++11) | checks if a type is const-qualified (class template) |
| [is\_volatile](is_volatile "cpp/types/is volatile")
(C++11) | checks if a type is volatile-qualified (class template) |
| [add\_cvadd\_constadd\_volatile](add_cv "cpp/types/add cv")
(C++11)(C++11)(C++11) | adds `const` or/and `volatile` specifiers to the given type (class template) |
| [remove\_cvref](remove_cvref "cpp/types/remove cvref")
(C++20) | combines `std::remove_cv` and `[std::remove\_reference](remove_reference "cpp/types/remove reference")` (class template) |
| programming_docs |
cpp std::nullptr_t std::nullptr\_t
===============
| Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | |
| --- | --- | --- |
|
```
using nullptr_t = decltype(nullptr);
```
| | (since C++11) |
`std::nullptr_t` is the type of the null pointer literal, [`nullptr`](../language/nullptr "cpp/language/nullptr"). It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are *null pointer constants* (see `[NULL](null "cpp/types/NULL")`), and may be [implicitly converted](../language/implicit_conversion "cpp/language/implicit conversion") to any pointer and pointer to member type.
`sizeof(std::nullptr_t)` is equal to `sizeof(void *)`.
### Notes
`nullptr_t` is available in the global namespace when `<stddef.h>` is included, even if it is not a part of C99~C17 (referenced by C++11~C++20).
`nullptr_t` is also a part of C since C23.
### Example
If two or more overloads accept different pointer types, an overload for `std::nullptr_t` is necessary to accept a null pointer argument.
```
#include <cstddef>
#include <iostream>
void f(int*)
{
std::cout << "Pointer to integer overload\n";
}
void f(double*)
{
std::cout << "Pointer to double overload\n";
}
void f(std::nullptr_t)
{
std::cout << "null pointer overload\n";
}
int main()
{
int* pi {}; double* pd {};
f(pi);
f(pd);
f(nullptr); // would be ambiguous without void f(nullptr_t)
// f(0); // ambiguous call: all three functions are candidates
// f(NULL); // ambiguous if NULL is an integral null pointer constant
// (as is the case in most implementations)
}
```
Output:
```
Pointer to integer overload
Pointer to double overload
null pointer overload
```
### See also
| | |
| --- | --- |
| [`nullptr`](../language/nullptr "cpp/language/nullptr")(C++11) | the pointer literal which specifies a null pointer value |
| [NULL](null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) |
| [is\_null\_pointer](is_null_pointer "cpp/types/is null pointer")
(C++14) | checks if a type is `std::nullptr_t` (class template) |
| [C documentation](https://en.cppreference.com/w/c/types/nullptr_t "c/types/nullptr t") for `nullptr_t` |
cpp std::add_cv, std::add_const, std::add_volatile std::add\_cv, std::add\_const, std::add\_volatile
=================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct add_cv;
```
| (1) | (since C++11) |
|
```
template< class T >
struct add_const;
```
| (2) | (since C++11) |
|
```
template< class T >
struct add_volatile;
```
| (3) | (since C++11) |
Provides the member typedef `type` which is the same as `T`, except it has a cv-qualifier added (unless `T` is a function, a reference, or already has this cv-qualifier).
1) adds both `const` and `volatile`
2) adds `const`
3) adds `volatile`
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type `T` with the cv-qualifier |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using add_cv_t = typename add_cv<T>::type;
```
| | (since C++14) |
|
```
template< class T >
using add_const_t = typename add_const<T>::type;
```
| | (since C++14) |
|
```
template< class T >
using add_volatile_t = typename add_volatile<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template<class T> struct add_cv { typedef const volatile T type; };
template<class T> struct add_const { typedef const T type; };
template<class T> struct add_volatile { typedef volatile T type; };
```
|
### Notes
These transformation traits can be used to establish [non-deduced contexts](../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in template argument deduction:
```
template<class T>
void f(const T&, const T&);
template<class T>
void g(const T&, std::add_const_t<T>&);
f(4.2, 0); // error, deduced conflicting types for 'T'
g(4.2, 0); // OK, calls g<double>
```
### Example
```
#include <iostream>
#include <type_traits>
struct foo
{
void m() { std::cout << "Non-cv\n"; }
void m() const { std::cout << "Const\n"; }
void m() volatile { std::cout << "Volatile\n"; }
void m() const volatile { std::cout << "Const-volatile\n"; }
};
int main()
{
foo{}.m();
std::add_const<foo>::type{}.m();
std::add_volatile<foo>::type{}.m();
std::add_cv<foo>::type{}.m();
}
```
Output:
```
Non-cv
Const
Volatile
Const-volatile
```
### See also
| | |
| --- | --- |
| [is\_const](is_const "cpp/types/is const")
(C++11) | checks if a type is const-qualified (class template) |
| [is\_volatile](is_volatile "cpp/types/is volatile")
(C++11) | checks if a type is volatile-qualified (class template) |
| [remove\_cvremove\_constremove\_volatile](remove_cv "cpp/types/remove cv")
(C++11)(C++11)(C++11) | removes `const` or/and `volatile` specifiers from the given type (class template) |
| [as\_const](../utility/as_const "cpp/utility/as const")
(C++17) | obtains a reference to const to its argument (function template) |
cpp std::is_const std::is\_const
==============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_const;
```
| | (since C++11) |
If `T` is a const-qualified type (that is, `const`, or `const volatile`), provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_const` or `is_const_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_const_v = is_const<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a const-qualified type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
If `T` is a reference type then `is_const<T>::value` is always `false`. The proper way to check a potentially-reference type for const-ness is to remove the reference: `is_const<typename remove_reference<T>::type>`.
### Possible implementation
| |
| --- |
|
```
template<class T> struct is_const : std::false_type {};
template<class T> struct is_const<const T> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha
<< std::is_const_v<int> << '\n' // false
<< std::is_const_v<const int> << '\n' // true
<< std::is_const_v<const int*> // false
<< " because the pointer itself can be changed but not the int pointed at\n"
<< std::is_const_v<int* const> // true
<< " because the pointer itself can't be changed but the int pointed at can\n"
<< std::is_const_v<const int&> << '\n' // false
<< std::is_const_v<std::remove_reference_t<const int&>> << '\n' // true
;
}
```
Output:
```
false
true
false because the pointer itself can be changed but not the int pointed at
true because the pointer itself can't be changed but the int pointed at can
false
true
```
### See also
| | |
| --- | --- |
| [is\_volatile](is_volatile "cpp/types/is volatile")
(C++11) | checks if a type is volatile-qualified (class template) |
| [as\_const](../utility/as_const "cpp/utility/as const")
(C++17) | obtains a reference to const to its argument (function template) |
cpp std::reference_constructs_from_temporary std::reference\_constructs\_from\_temporary
===========================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct reference_constructs_from_temporary;
```
| | (since C++23) |
Let `V` be `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<U>` if `U` is a scalar type or *cv* `void`, or `U` otherwise. If `T` is a reference type, and given a hypothetic expression `e` such that `decltype(e)` is `V`, the variable definition `T ref(e);` is well-formed and [binds a temporary object](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") to `ref`, then provides the member constant `value` equal to `true`. Otherwise, `value` is `false`.
If `T` is an lvalue reference type to a const- but not volatile-qualified object type or an rvalue reference type, both `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>` and `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<U>` shall be [complete types](../language/type#Incomplete_type "cpp/language/type"), *cv* `void`, or an [arrays of unknown bound](../language/array#Arrays_of_unknown_bound "cpp/language/array"); otherwise the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for `reference_constructs_from_temporary` or `reference_constructs_from_temporary_v` is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, class U >
inline constexpr reference_constructs_from_temporary_v =
std::reference_constructs_from_temporary<T, U>::value;
```
| | (since C++23) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a reference type, a `U` value can be bound to `T` in direct-initialization, and a temporary object would be bound to the reference, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
`reference_constructs_from_temporary` can be used for rejecting some cases that always produce dangling references.
It is also possible to use member initializer list to reject binding a temporary object to a reference if the compiler has implemented [CWG1696](https://cplusplus.github.io/CWG/issues/1696.html).
### Example
```
#include <type_traits>
#include <iostream>
int main()
{
std::cout << std::boolalpha
<< std::reference_constructs_from_temporary_v<int&&, int> << '\n'
<< std::reference_constructs_from_temporary_v<const int&, int> << '\n'
<< std::reference_constructs_from_temporary_v<int&&, int&&> << '\n'
<< std::reference_constructs_from_temporary_v<const int&, int&&> << '\n'
<< std::reference_constructs_from_temporary_v<int&&, long&&> << '\n';
<< std::reference_constructs_from_temporary_v<int&&, long> << '\n';
}
```
Output:
```
true
true
false
false
true
true
```
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
| [(constructor)](../utility/tuple/tuple "cpp/utility/tuple/tuple")
(C++11) | constructs a new `tuple` (public member function of `std::tuple<Types...>`) |
| [(constructor)](../utility/pair/pair "cpp/utility/pair/pair") | constructs new pair (public member function of `std::pair<T1,T2>`) |
| [make\_from\_tuple](../utility/make_from_tuple "cpp/utility/make from tuple")
(C++17) | Construct an object with a tuple of arguments (function template) |
cpp std::reference_converts_from_temporary std::reference\_converts\_from\_temporary
=========================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct reference_converts_from_temporary;
```
| | (since C++23) |
Let `V` be `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<U>` if `U` is a scalar type or *cv* `void`, or `U` otherwise. If `T` is a reference type, and given a hypothetic expression `e` such that `decltype(e)` is `V`, the variable definition `T ref = e;` is well-formed and [binds a temporary object](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") to `ref`, then provides the member constant `value` equal to `true`. Otherwise, `value` is `false`.
If `T` is an lvalue reference type to a const- but not volatile-qualified object type or an rvalue reference type, both `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T>` and `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<U>` shall be [complete types](../language/type#Incomplete_type "cpp/language/type"), *cv* `void`, or an [arrays of unknown bound](../language/array#Arrays_of_unknown_bound "cpp/language/array"); otherwise the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for `reference_converts_from_temporary` or `reference_converts_from_temporary_v` is undefined.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, class U >
inline constexpr reference_converts_from_temporary_v =
std::reference_converts_from_temporary<T, U>::value;
```
| | (since C++23) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a reference type, a `U` value can be bound to `T` in copy-initialization, and a temporary object would be bound to the reference, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
`reference_converts_from_temporary` can be used for rejecting some cases that always produce dangling references.
### Example
```
#include <type_traits>
#include <iostream>
int main()
{
std::cout << std::boolalpha
<< std::reference_converts_from_temporary_v<int&&, int> << '\n'
<< std::reference_converts_from_temporary_v<const int&, int> << '\n'
<< std::reference_converts_from_temporary_v<int&&, int&&> << '\n'
<< std::reference_converts_from_temporary_v<const int&, int&&> << '\n'
<< std::reference_converts_from_temporary_v<int&&, long&&> << '\n';
<< std::reference_converts_from_temporary_v<int&&, long> << '\n';
}
```
Output:
```
true
true
false
false
true
true
```
### See also
| | |
| --- | --- |
| [is\_convertibleis\_nothrow\_convertible](is_convertible "cpp/types/is convertible")
(C++11)(C++20) | checks if a type can be converted to the other type (class template) |
| [invokeinvoke\_r](../utility/functional/invoke "cpp/utility/functional/invoke")
(C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) |
| [bind](../utility/functional/bind "cpp/utility/functional/bind")
(C++11) | binds one or more arguments to a function object (function template) |
| [visit](../utility/variant/visit "cpp/utility/variant/visit")
(C++17) | calls the provided functor with the arguments held by one or more variants (function template) |
| [(constructor)](../utility/functional/function/function "cpp/utility/functional/function/function") | constructs a new `std::function` instance (public member function of `std::function<R(Args...)>`) |
| [(constructor)](../utility/functional/move_only_function/move_only_function "cpp/utility/functional/move only function/move only function")
(C++23) | constructs a new `std::move_only_function` object (public member function of `std::move_only_function`) |
| [(constructor)](../thread/packaged_task/packaged_task "cpp/thread/packaged task/packaged task") | constructs the task object (public member function of `std::packaged_task<R(Args...)>`) |
cpp std::is_bounded_array std::is\_bounded\_array
=======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_bounded_array;
```
| | (since C++20) |
Checks whether `T` is an array type of known bound. Provides the member constant `value` which is equal to `true`, if `T` is an array type of known bound. Otherwise, `value` is equal to `false`.
The behavior of a program that adds specializations for `is_bounded_array` or `is_bounded_array_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_bounded_array_v = is_bounded_array<T>::value;
```
| | (since C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an array type of known bound , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct is_bounded_array: std::false_type {};
template<class T, std::size_t N>
struct is_bounded_array<T[N]> : std::true_type {};
```
|
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bounded_array_traits`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <type_traits>
#define OUT(...) std::cout << #__VA_ARGS__ << " : " << __VA_ARGS__ << '\n'
class A {};
int main()
{
std::cout << std::boolalpha;
OUT( std::is_bounded_array_v<A> );
OUT( std::is_bounded_array_v<A[]> );
OUT( std::is_bounded_array_v<A[3]> );
OUT( std::is_bounded_array_v<float> );
OUT( std::is_bounded_array_v<int> );
OUT( std::is_bounded_array_v<int[]> );
OUT( std::is_bounded_array_v<int[3]> );
}
```
Output:
```
std::is_bounded_array_v<A> : false
std::is_bounded_array_v<A[]> : false
std::is_bounded_array_v<A[3]> : true
std::is_bounded_array_v<float> : false
std::is_bounded_array_v<int> : false
std::is_bounded_array_v<int[]> : false
std::is_bounded_array_v<int[3]> : true
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_unbounded\_array](is_unbounded_array "cpp/types/is unbounded array")
(C++20) | checks if a type is an array type of unknown bound (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
| programming_docs |
cpp std::is_literal_type std::is\_literal\_type
======================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_literal_type;
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
(This type trait has been deprecated[[1]](#cite_note-1) and removed[[2]](#cite_note-2) as offering negligible value to generic code.).
If `T` satisfies all requirements of [LiteralType](../named_req/literaltype "cpp/named req/LiteralType"), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type and not (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_literal_type` or `is_literal_type_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_literal_type_v = is_literal_type<T>::value;
```
| | (since C++17) (deprecated) (removed in C++20) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a literal type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Only literal types may be used as parameters to or returned from [constexpr functions](../language/constexpr "cpp/language/constexpr"). Only literal classes may have constexpr member functions.
### Example
```
#include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
virtual ~B();
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_literal_type<A>::value << '\n';
std::cout << std::is_literal_type<B>::value << '\n';
}
```
Output:
```
true
false
```
### External links
1. Alisdair Meredith. ["Deprecate the `is_literal` Trait"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0174r2.html#2.3). [*Deprecating Vestigial Library Parts in C++17*](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0174r2.html). "The `is_literal` type trait offers negligible value to generic code, as what is really needed is the ability to know that a specific construction would produce constant initialization."
2. Alisdair Meredith, Stephan T. Lavavej, Tomasz Kamiński. ["Deprecated type traits"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0619r4.html#3.12). [*Reviewing Deprecated Facilities of C++17 for C++20*](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0619r4.html). "**Strong recommendation:** Remove the traits that can live on as zombies. [...] **Toronto Review:** Accept strong recommendation, strike from C++20."
cpp std::decay std::decay
==========
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct decay;
```
| | (since C++11) |
Applies lvalue-to-rvalue, array-to-pointer, and function-to-pointer implicit conversions to the type `T`, removes cv-qualifiers, and defines the resulting type as the member typedef `type`. Formally:
* If `T` names the type "array of `U`" or "reference to array of `U`", the member typedef `type` is `U*`.
* Otherwise, if `T` is a function type `F` or a reference thereto, the member typedef `type` is `[std::add\_pointer](http://en.cppreference.com/w/cpp/types/add_pointer)<F>::type`.
* Otherwise, the member typedef `type` is `[std::remove\_cv](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_reference](http://en.cppreference.com/w/cpp/types/remove_reference)<T>::type>::type`.
These conversions model the type conversion applied to all function arguments when passed by value.
The behavior of a program that adds specializations for `decay` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the result of applying the decay type conversions to `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using decay_t = typename decay<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct decay {
private:
typedef typename std::remove_reference<T>::type U;
public:
typedef typename std::conditional<
std::is_array<U>::value,
typename std::remove_extent<U>::type*,
typename std::conditional<
std::is_function<U>::value,
typename std::add_pointer<U>::type,
typename std::remove_cv<U>::type
>::type
>::type type;
};
```
|
### Example
```
#include <type_traits>
template <typename T, typename U>
constexpr bool is_decay_equ = std::is_same_v<std::decay_t<T>, U>;
int main()
{
static_assert(
is_decay_equ<int, int> &&
! is_decay_equ<int, float> &&
is_decay_equ<int&, int> &&
is_decay_equ<int&&, int> &&
is_decay_equ<const int&, int> &&
is_decay_equ<int[2], int*> &&
! is_decay_equ<int[4][2], int*> &&
! is_decay_equ<int[4][2], int**> &&
is_decay_equ<int[4][2], int(*)[2]> &&
is_decay_equ<int(int), int(*)(int)>
);
}
```
### See also
| | |
| --- | --- |
| [remove\_cvref](remove_cvref "cpp/types/remove cvref")
(C++20) | combines `[std::remove\_cv](remove_cv "cpp/types/remove cv")` and `[std::remove\_reference](remove_reference "cpp/types/remove reference")` (class template) |
| [`implicit conversion`](../language/implicit_cast "cpp/language/implicit cast") | array-to-pointer, function-to-pointer, lvalue-to-rvalue conversions |
cpp std::conditional std::conditional
================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< bool B, class T, class F >
struct conditional;
```
| | (since C++11) |
Provides member typedef `type`, which is defined as `T` if `B` is `true` at compile time, or as `F` if `B` is `false`.
The behavior of a program that adds specializations for `conditional` is undefined.
### Member types
| Member type | Definition |
| --- | --- |
| `type` | `T` if `B == true`, `F` if `B == false` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< bool B, class T, class F >
using conditional_t = typename conditional<B,T,F>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template<bool B, class T, class F>
struct conditional { using type = T; };
template<class T, class F>
struct conditional<false, T, F> { using type = F; };
```
|
### Example
```
#include <iostream>
#include <type_traits>
#include <typeinfo>
int main()
{
typedef std::conditional<true, int, double>::type Type1;
typedef std::conditional<false, int, double>::type Type2;
typedef std::conditional<sizeof(int) >= sizeof(double), int, double>::type Type3;
std::cout << typeid(Type1).name() << '\n';
std::cout << typeid(Type2).name() << '\n';
std::cout << typeid(Type3).name() << '\n';
}
```
Possible output:
```
int
double
double
```
### See also
| | |
| --- | --- |
| [enable\_if](enable_if "cpp/types/enable if")
(C++11) | conditionally [removes](../language/sfinae "cpp/language/sfinae") a function overload or template specialization from overload resolution (class template) |
cpp std::common_type std::common\_type
=================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class... T >
struct common_type;
```
| | (since C++11) |
Determines the common type among all types `T...`, that is the type all `T...` can be implicitly converted to. If such a type exists (as determined according to the rules below), the member `type` names that type. Otherwise, there is no member `type`.
* If `sizeof...(T)` is zero, there is no member `type`.
* If `sizeof...(T)` is one (i.e., `T...` contains only one type `T0`), the member `type` names the same type as `std::common_type<T0, T0>::type` if it exists; otherwise there is no member `type`.
* If `sizeof...(T)` is two (i.e., `T...` contains exactly two types `T1` and `T2`),
+ If applying `[std::decay](decay "cpp/types/decay")` to at least one of `T1` and `T2` produces a different type, the member `type` names the same type as `std::common\_type<[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T1>::type, [std::decay](http://en.cppreference.com/w/cpp/types/decay)<T2>::type>::type`, if it exists; if not, there is no member `type`.
+ Otherwise, if there is a user specialization for `std::common_type<T1, T2>`, that specialization is used;
+ Otherwise, if `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<decltype(false ? [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T1>() : [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T2>())>::type` is a valid type, the member `type` denotes that type;
| | |
| --- | --- |
| * Otherwise, if `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<decltype(false ? [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<CR1>() : [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<CR2>())>::type` is a valid type, where `CR1` and `CR2` are `const [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T1>&` and `const [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<T2>&` respectively, the member `type` denotes that type;
| (since C++20) |
* Otherwise, there is no member `type`.
* If `sizeof...(T)` is greater than two (i.e., `T...` consists of the types `T1, T2, R...`), then if `std::common_type<T1, T2>::type` exists, the member `type` denotes `std::common_type<typename std::common_type<T1, T2>::type, R...>::type` if such a type exists. In all other cases, there is no member `type`.
The types in the parameter pack `T` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the common type for all `T...` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class... T >
using common_type_t = typename common_type<T...>::type;
```
| | (since C++14) |
### Specializations
Users may specialize `common_type` for types `T1` and `T2` if.
* At least one of `T1` and `T2` depends on a user-defined type, and
* `[std::decay](decay "cpp/types/decay")` is an identity transformation for both `T1` and `T2`.
If such a specialization has a member named `type`, it must be a public and unambiguous member that names a cv-unqualified non-reference type to which both `T1` and `T2` are explicitly convertible. Additionally, `std::common_type<T1, T2>::type` and `std::common_type<T2, T1>::type` must denote the same type.
A program that adds `common_type` specializations in violation of these rules has undefined behavior.
Note that the behavior of a program that adds a specialization to any other template (except for [`std::basic_common_reference`](common_reference "cpp/types/common reference")) (since C++20) from `<type_traits>` is undefined.
The following specializations are already provided by the standard library:
| | |
| --- | --- |
| [std::common\_type<std::chrono::duration>](../chrono/duration/common_type "cpp/chrono/duration/common type")
(C++11) | specializes the `std::common_type` trait (class template specialization) |
| [std::common\_type<std::chrono::time\_point>](../chrono/time_point/common_type "cpp/chrono/time point/common type")
(C++11) | specializes the `std::common_type` trait (class template specialization) |
| [std::common\_type<std::pair>](../utility/pair/common_type "cpp/utility/pair/common type")
(C++23) | determines the common type of two `pair`s (class template specialization) |
| [std::common\_type<*tuple-like*>](../utility/tuple/common_type "cpp/utility/tuple/common type")
(C++23) | determines the common type of a `tuple` and a tuple-like type (class template specialization) |
### Possible implementation
| |
| --- |
|
```
// primary template (used for zero types)
template<class...>
struct common_type {};
//////// one type
template <class T>
struct common_type<T> : common_type<T, T> {};
namespace detail {
template<class...>
using void_t = void;
template<class T1, class T2>
using conditional_result_t = decltype(false ? std::declval<T1>() : std::declval<T2>());
template<class, class, class = void>
struct decay_conditional_result {};
template<class T1, class T2>
struct decay_conditional_result<T1, T2, void_t<conditional_result_t<T1, T2>>>
: std::decay<conditional_result_t<T1, T2>> {};
template<class T1, class T2, class = void>
struct common_type_2_impl : decay_conditional_result<const T1&, const T2&> {};
// C++11 implementation:
// template<class, class, class = void>
// struct common_type_2_impl {};
template<class T1, class T2>
struct common_type_2_impl<T1, T2, void_t<conditional_result_t<T1, T2>>>
: decay_conditional_result<T1, T2> {};
}
//////// two types
template<class T1, class T2>
struct common_type<T1, T2>
: std::conditional<std::is_same<T1, typename std::decay<T1>::type>::value &&
std::is_same<T2, typename std::decay<T2>::type>::value,
detail::common_type_2_impl<T1, T2>,
common_type<typename std::decay<T1>::type,
typename std::decay<T2>::type>>::type {};
//////// 3+ types
namespace detail {
template<class AlwaysVoid, class T1, class T2, class...R>
struct common_type_multi_impl {};
template<class T1, class T2, class...R>
struct common_type_multi_impl<void_t<typename common_type<T1, T2>::type>, T1, T2, R...>
: common_type<typename common_type<T1, T2>::type, R...> {};
}
template<class T1, class T2, class... R>
struct common_type<T1, T2, R...>
: detail::common_type_multi_impl<void, T1, T2, R...> {};
```
|
### Notes
For arithmetic types not subject to promotion, the common type may be viewed as the type of the (possibly mixed-mode) arithmetic expression such as `T0() + T1() + ... + Tn()`.
### Examples
Demonstrates mixed-mode arithmetic on a user-defined class.
```
#include <iostream>
#include <type_traits>
template <class T>
struct Number { T n; };
template <class T, class U>
Number<typename std::common_type<T, U>::type> operator+(const Number<T>& lhs,
const Number<U>& rhs)
{
return {lhs.n + rhs.n};
}
int main()
{
Number<int> i1 = {1}, i2 = {2};
Number<double> d1 = {2.3}, d2 = {3.5};
std::cout << "i1i2: " << (i1 + i2).n << "\ni1d2: " << (i1 + d2).n << '\n'
<< "d1i2: " << (d1 + i2).n << "\nd1d2: " << (d1 + d2).n << '\n';
}
```
Output:
```
i1i2: 3
i1d2: 4.5
d1i2: 4.3
d1d2: 5.8
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2141](https://cplusplus.github.io/LWG/issue2141) | C++11 | `common_type<int, int>::type` is `int&&` | decayed result type |
| [LWG 2408](https://cplusplus.github.io/LWG/issue2408) | C++11 | `common_type` is not SFINAE-friendly | made SFINAE-friendly |
| [LWG 2460](https://cplusplus.github.io/LWG/issue2460) | C++11 | `common_type` specializations are nearly impossible to write | reduced number of specializations needed |
### See also
| | |
| --- | --- |
| [common\_with](../concepts/common_with "cpp/concepts/common with")
(C++20) | specifies that two types share a common type (concept) |
cpp std::underlying_type std::underlying\_type
=====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct underlying_type;
```
| | (since C++11) |
If `T` is a complete enumeration (enum) type, provides a member typedef `type` that names the underlying type of `T`.
| | |
| --- | --- |
| Otherwise, the behavior is undefined. | (until C++20) |
| Otherwise, if `T` is not an enumeration type, there is no member `type`. Otherwise (`T` is an incomplete enumeration type), the program is ill-formed. | (since C++20) |
The behavior of a program that adds specializations for `underlying_type` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the underlying type of `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using underlying_type_t = typename underlying_type<T>::type;
```
| | (since C++14) |
### Notes
Each [enumeration type](../language/enum "cpp/language/enum") has an *underlying type*, which can be.
1. Specified explicitly (both scoped and unscoped enumerations).
2. Omitted, in which case it is `int` for scoped enumerations or an implementation-defined integral type capable of representing all values of the enum (for unscoped enumerations).
### Example
```
#include <iostream>
#include <type_traits>
enum e1 {};
enum class e2 {};
enum class e3: unsigned {};
enum class e4: int {};
int main() {
constexpr bool e1_t = std::is_same_v< std::underlying_type_t<e1>, int >;
constexpr bool e2_t = std::is_same_v< std::underlying_type_t<e2>, int >;
constexpr bool e3_t = std::is_same_v< std::underlying_type_t<e3>, int >;
constexpr bool e4_t = std::is_same_v< std::underlying_type_t<e4>, int >;
std::cout
<< "underlying type for 'e1' is " << (e1_t ? "int" : "non-int") << '\n'
<< "underlying type for 'e2' is " << (e2_t ? "int" : "non-int") << '\n'
<< "underlying type for 'e3' is " << (e3_t ? "int" : "non-int") << '\n'
<< "underlying type for 'e4' is " << (e4_t ? "int" : "non-int") << '\n'
;
}
```
Possible output:
```
underlying type for 'e1' is non-int
underlying type for 'e2' is int
underlying type for 'e3' is non-int
underlying type for 'e4' is int
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2396](https://cplusplus.github.io/LWG/issue2396) | C++11 | incomplete enumeration types were allowed | complete enumeration type required |
### See also
| | |
| --- | --- |
| [is\_enum](is_enum "cpp/types/is enum")
(C++11) | checks if a type is an enumeration type (class template) |
| [is\_scoped\_enum](is_scoped_enum "cpp/types/is scoped enum")
(C++23) | checks if a type is a scoped enumeration type (class template) |
| [to\_underlying](../utility/to_underlying "cpp/utility/to underlying")
(C++23) | converts an enumeration to its underlying type (function template) |
| programming_docs |
cpp std::is_assignable, std::is_trivially_assignable, std::is_nothrow_assignable std::is\_assignable, std::is\_trivially\_assignable, std::is\_nothrow\_assignable
=================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct is_assignable;
```
| (1) | (since C++11) |
|
```
template< class T, class U >
struct is_trivially_assignable;
```
| (2) | (since C++11) |
|
```
template< class T, class U >
struct is_nothrow_assignable;
```
| (3) | (since C++11) |
1) If the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T>() = [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U>()` is well-formed in unevaluated context, provides the member constant `value` equal to `true`. Otherwise, `value` is `false`. [Access checks](../language/access "cpp/language/access") are performed as if from a context unrelated to either type.
2) same as (1), but the evaluation of the assignment expression will not call any operation that is not trivial. For the purposes of this check, a call to `[std::declval](../utility/declval "cpp/utility/declval")` is considered trivial and not considered an [odr-use](../language/definition#ODR-use "cpp/language/definition") of `[std::declval](../utility/declval "cpp/utility/declval")`.
3) same as (1), but the evaluation of the assignment expression will not call any operation that is not noexcept. `T` and `U` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template< class T, class U >
inline constexpr bool is_assignable_v = is_assignable<T, U>::value;
```
| | (since C++17) |
|
```
template< class T, class U >
inline constexpr bool is_trivially_assignable_v = is_trivially_assignable<T, U>::value;
```
| | (since C++17) |
|
```
template< class T, class U >
inline constexpr bool is_nothrow_assignable_v = is_nothrow_assignable<T, U>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is assignable from `U` , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
This trait does not check anything outside the immediate context of the assignment expression: if the use of `T` or `U` would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual assignment may not compile even if `std::is_assignable<T,U>::value` compiles and evaluates to `true`.
### Example
```
#include <iostream>
#include <string>
#include <type_traits>
struct Ex1 { int n; };
int main() {
std::cout << std::boolalpha
<< "int is assignable from int? "
<< std::is_assignable<int, int>::value << '\n' // 1 = 1; wouldn't compile
<< "int& is assignable from int? "
<< std::is_assignable<int&, int>::value << '\n' // int a; a = 1; works
<< "int is assignable from double? "
<< std::is_assignable<int, double>::value << '\n'
<< "int& is nothrow assignable from double? "
<< std::is_nothrow_assignable<int&, double>::value << '\n'
<< "string is assignable from double? "
<< std::is_assignable<std::string, double>::value << '\n'
<< "Ex1& is trivially assignable from const Ex1&? "
<< std::is_trivially_assignable<Ex1&, const Ex1&>::value << '\n';
}
```
Output:
```
int is assignable from int? false
int& is assignable from int? true
int is assignable from double? false
int& is nothrow assignable from double? true
string is assignable from double? true
Ex1& is trivially assignable from const Ex1&? true
```
### See also
| | |
| --- | --- |
| [is\_copy\_assignableis\_trivially\_copy\_assignableis\_nothrow\_copy\_assignable](is_copy_assignable "cpp/types/is copy assignable")
(C++11)(C++11)(C++11) | checks if a type has a copy assignment operator (class template) |
| [is\_move\_assignableis\_trivially\_move\_assignableis\_nothrow\_move\_assignable](is_move_assignable "cpp/types/is move assignable")
(C++11)(C++11)(C++11) | checks if a type has a move assignment operator (class template) |
| [assignable\_from](../concepts/assignable_from "cpp/concepts/assignable from")
(C++20) | specifies that a type is assignable from another type (concept) |
cpp std::remove_all_extents std::remove\_all\_extents
=========================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct remove_all_extents;
```
| | (since C++11) |
If `T` is a multidimensional array of some type `X`, provides the member typedef `type` equal to `X`, otherwise `type` is `T`.
The behavior of a program that adds specializations for `remove_all_extents` is undefined.
### Member types
| Name | Definition |
| --- | --- |
| `type` | the type of the element of `T` |
### Helper types
| | | |
| --- | --- | --- |
|
```
template< class T >
using remove_all_extents_t = typename remove_all_extents<T>::type;
```
| | (since C++14) |
### Possible implementation
| |
| --- |
|
```
template<class T>
struct remove_all_extents { typedef T type; };
template<class T>
struct remove_all_extents<T[]> {
typedef typename remove_all_extents<T>::type type;
};
template<class T, std::size_t N>
struct remove_all_extents<T[N]> {
typedef typename remove_all_extents<T>::type type;
};
```
|
### Example
```
#include <iostream>
#include <type_traits>
#include <typeinfo>
template<class A>
void info(const A&)
{
typedef typename std::remove_all_extents<A>::type Type;
std::cout << "underlying type: " << typeid(Type).name() << '\n';
}
int main()
{
float a0;
float a1[1][2][3];
float a2[1][1][1][1][2];
float* a3;
int a4[3][2];
double a5[2][3];
struct X { int m; } x0[3][3];
info(a0);
info(a1);
info(a2);
info(a3);
info(a4);
info(a5);
info(x0);
}
```
Possible output:
```
underlying type: float
underlying type: float
underlying type: float
underlying type: float*
underlying type: int
underlying type: double
underlying type: main::X
```
### See also
| | |
| --- | --- |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [rank](rank "cpp/types/rank")
(C++11) | obtains the number of dimensions of an array type (class template) |
| [extent](extent "cpp/types/extent")
(C++11) | obtains the size of an array type along a specified dimension (class template) |
| [remove\_extent](remove_extent "cpp/types/remove extent")
(C++11) | removes one extent from the given array type (class template) |
cpp std::is_invocable, std::is_invocable_r, std::is_nothrow_invocable, std::is_nothrow_invocable_r std::is\_invocable, std::is\_invocable\_r, std::is\_nothrow\_invocable, std::is\_nothrow\_invocable\_r
======================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template <class Fn, class... ArgTypes>
struct is_invocable;
```
| (1) | (since C++17) |
|
```
template <class R, class Fn, class... ArgTypes>
struct is_invocable_r;
```
| (2) | (since C++17) |
|
```
template <class Fn, class... ArgTypes>
struct is_nothrow_invocable;
```
| (3) | (since C++17) |
|
```
template <class R, class Fn, class... ArgTypes>
struct is_nothrow_invocable_r;
```
| (4) | (since C++17) |
1) Determines whether `Fn` can be invoked with the arguments `ArgTypes...`. Formally, determines whether `INVOKE([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Fn>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<ArgTypes>()...)` is well formed when treated as an unevaluated operand, where `*INVOKE*` is the operation defined in [Callable](../named_req/callable "cpp/named req/Callable").
2) Determines whether `Fn` can be invoked with the arguments `ArgTypes...` to yield a result that is convertible to `R` and the implicit conversion does not [bind a reference to a temporary object](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") (since C++23). If `R` is *cv* `void`, the result can be any type. Formally, determines whether `INVOKE<R>([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Fn>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<ArgTypes>()...)` is well formed when treated as an unevaluated operand, where `*INVOKE*` is the operation defined in [Callable](../named_req/callable "cpp/named req/Callable").
3) Determines whether `Fn` is callable with the arguments `ArgTypes...` (same as (1)), and that such call is known not to throw any exceptions.
4) Determines whether `Fn` can be invoked with the arguments `ArgTypes...` to yield a result that is convertible to `R` and the implicit conversion does not bind a reference to a temporary object (since C++23) (same as (2)), and that such call (including the conversion of the parameters and the result) is known not to throw any exceptions. If `R` is *cv* `void`, the result can be any type (same as (2)). The converson of the parameters and the call itself still has to be known not to throw any exceptions. `Fn, R` and all types in the parameter pack `ArgTypes` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template <class Fn, class... ArgTypes>
inline constexpr bool is_invocable_v =
std::is_invocable<Fn, ArgTypes...>::value;
```
| (1) | (since C++17) |
|
```
template <class R, class Fn, class... ArgTypes>
inline constexpr bool is_invocable_r_v =
std::is_invocable_r<R, Fn, ArgTypes...>::value;
```
| (2) | (since C++17) |
|
```
template <class Fn, class... ArgTypes>
inline constexpr bool is_nothrow_invocable_v =
std::is_nothrow_invocable<Fn, ArgTypes...>::value;
```
| (3) | (since C++17) |
|
```
template <class R, class Fn, class... ArgTypes>
inline constexpr bool is_nothrow_invocable_r_v =
std::is_nothrow_invocable_r<R, Fn, ArgTypes...>::value;
```
| (4) | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `INVOKE<R>(declval<Fn>(), declval<ArgTypes>()...)` is well formed when treated as an unevaluated operand , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Examples
```
#include <type_traits>
auto func2(char) -> int (*)()
{
return nullptr;
}
int main()
{
static_assert( std::is_invocable_v<int()> );
static_assert( not std::is_invocable_v<int(), int> );
static_assert( std::is_invocable_r_v<int, int()> );
static_assert( not std::is_invocable_r_v<int*, int()> );
static_assert( std::is_invocable_r_v<void, void(int), int> );
static_assert( not std::is_invocable_r_v<void, void(int), void> );
static_assert( std::is_invocable_r_v<int(*)(), decltype(func2), char> );
static_assert( not std::is_invocable_r_v<int(*)(), decltype(func2), void> );
}
```
### See also
| | |
| --- | --- |
| [invokeinvoke\_r](../utility/functional/invoke "cpp/utility/functional/invoke")
(C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) |
| [result\_ofinvoke\_result](result_of "cpp/types/result of")
(C++11)(removed in C++20)(C++17) | deduces the result type of invoking a callable object with a set of arguments (class template) |
| [declval](../utility/declval "cpp/utility/declval")
(C++11) | obtains a reference to its argument for use in unevaluated context (function template) |
| [invocableregular\_invocable](../concepts/invocable "cpp/concepts/invocable")
(C++20) | specifies that a callable type can be invoked with a given set of argument types (concept) |
cpp std::is_fundamental std::is\_fundamental
====================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_fundamental;
```
| | (since C++11) |
If `T` is a [fundamental type](../language/types "cpp/language/types") (that is, arithmetic type, `void`, or `nullptr_t`), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_fundamental` or `is_fundamental_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_fundamental_v = is_fundamental<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a fundamental type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_fundamental
: std::integral_constant<
bool,
std::is_arithmetic<T>::value ||
std::is_void<T>::value ||
std::is_same<std::nullptr_t, typename std::remove_cv<T>::type>::value
// you can also use 'std::is_null_pointer<T>::value' instead in C++14
> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha;
std::cout << "A\t" << std::is_fundamental<A>::value << '\n';
std::cout << "int\t" << std::is_fundamental<int>::value << '\n';
std::cout << "int&\t" << std::is_fundamental<int&>::value << '\n';
std::cout << "int*\t" << std::is_fundamental<int*>::value << '\n';
std::cout << "float\t" << std::is_fundamental<float>::value << '\n';
std::cout << "float&\t" << std::is_fundamental<float&>::value << '\n';
std::cout << "float*\t" << std::is_fundamental<float*>::value << '\n';
}
```
Output:
```
A false
int true
int& false
int* false
float true
float& false
float* false
```
### See also
| | |
| --- | --- |
| [is\_compound](is_compound "cpp/types/is compound")
(C++11) | checks if a type is a compound type (class template) |
| [is\_arithmetic](is_arithmetic "cpp/types/is arithmetic")
(C++11) | checks if a type is an arithmetic type (class template) |
| [is\_void](is_void "cpp/types/is void")
(C++11) | checks if a type is `void` (class template) |
| [is\_null\_pointer](is_null_pointer "cpp/types/is null pointer")
(C++14) | checks if a type is `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)` (class template) |
cpp std::is_swappable_with, std::is_swappable, std::is_nothrow_swappable_with, std::is_nothrow_swappable std::is\_swappable\_with, std::is\_swappable, std::is\_nothrow\_swappable\_with, std::is\_nothrow\_swappable
============================================================================================================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
struct is_swappable_with;
```
| (1) | (since C++17) |
|
```
template< class T >
struct is_swappable;
```
| (2) | (since C++17) |
|
```
template< class T, class U >
struct is_nothrow_swappable_with;
```
| (3) | (since C++17) |
|
```
template< class T >
struct is_nothrow_swappable;
```
| (4) | (since C++17) |
1) If the expressions `swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U>())` and `swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<U>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T>())` are both well-formed in unevaluated context after `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap);` (see [Swappable](../named_req/swappable "cpp/named req/Swappable")), provides the member constant `value` equal `true`. Otherwise, `value` is `false`. [Access checks](../language/access "cpp/language/access") are performed as if from a context unrelated to either type.
2) If `T` is not a referenceable type (i.e., possibly cv-qualified `void` or a function type with a *cv-qualifier-seq* or a *ref-qualifier*), provides a member constant `value` equal to `false`. Otherwise, provides a member constant `value` equal to `std::is_swappable_with<T&, T&>::value`
3) Same as (1), but evaluations of both expressions from (1) are known not to throw exceptions
4) Same as (2), but uses `is_nothrow_swappable_with`. `T` and `U` shall each be a complete type, (possibly cv-qualified) `void`, or an array of unknown bound. Otherwise, the behavior is undefined.
If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
The behavior of a program that adds specializations for any of the templates described on this page is undefined.
### Helper variable templates
| | | |
| --- | --- | --- |
|
```
template <class T, class U>
inline constexpr bool is_swappable_with_v = is_swappable_with<T, U>::value;
```
| | (since C++17) |
|
```
template <class T>
inline constexpr bool is_swappable_v = is_swappable<T>::value;
```
| | (since C++17) |
|
```
template <class T, class U>
inline constexpr bool is_nothrow_swappable_with_v = is_nothrow_swappable_with<T, U>::value;
```
| | (since C++17) |
|
```
template <class T>
inline constexpr bool is_nothrow_swappable_v = is_nothrow_swappable<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is swappable with `U` , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
This trait does not check anything outside the immediate context of the swap expressions: if the use of `T` or `U` would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual swap may not compile even if `std::is_swappable_with<T,U>::value` compiles and evaluates to `true`.
### Example
### See also
| | |
| --- | --- |
| [swap](../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [is\_move\_assignableis\_trivially\_move\_assignableis\_nothrow\_move\_assignable](is_move_assignable "cpp/types/is move assignable")
(C++11)(C++11)(C++11) | checks if a type has a move assignment operator (class template) |
| [swappableswappable\_with](../concepts/swappable "cpp/concepts/swappable")
(C++20) | specifies that a type can be swapped or that two types can be swapped with each other (concept) |
| programming_docs |
cpp std::is_reference std::is\_reference
==================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_reference;
```
| | (since C++11) |
If `T` is a reference type (lvalue reference or rvalue reference), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_reference` or `is_reference_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_reference_v = is_reference<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is a reference type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template <class T> struct is_reference : std::false_type {};
template <class T> struct is_reference<T&> : std::true_type {};
template <class T> struct is_reference<T&&> : std::true_type {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
int main()
{
# define REF(x) << #x " ?: " << x << '\n'
std::cout << std::boolalpha
REF( std::is_reference_v<A> )
REF( std::is_reference_v<A&> )
REF( std::is_reference_v<A&&> )
REF( std::is_reference_v<long> )
REF( std::is_reference_v<long&> )
REF( std::is_reference_v<long&&> )
REF( std::is_reference_v<double*> )
REF( std::is_reference_v<double*&> )
REF( std::is_reference_v<double*&&> );
# undef REF
}
```
Output:
```
std::is_reference_v<A> ?: false
std::is_reference_v<A&> ?: true
std::is_reference_v<A&&> ?: true
std::is_reference_v<long> ?: false
std::is_reference_v<long&> ?: true
std::is_reference_v<long&&> ?: true
std::is_reference_v<double*> ?: false
std::is_reference_v<double*&> ?: true
std::is_reference_v<double*&&> ?: true
```
### See also
| | |
| --- | --- |
| [is\_lvalue\_reference](is_lvalue_reference "cpp/types/is lvalue reference")
(C++11) | checks if a type is a *lvalue reference* (class template) |
| [is\_rvalue\_reference](is_rvalue_reference "cpp/types/is rvalue reference")
(C++11) | checks if a type is a *rvalue reference* (class template) |
cpp std::type_index std::type\_index
================
| Defined in header `[<typeindex>](../header/typeindex "cpp/header/typeindex")` | | |
| --- | --- | --- |
|
```
class type_index;
```
| | (since C++11) |
The `type_index` class is a wrapper class around a `[std::type\_info](type_info "cpp/types/type info")` object, that can be used as index in associative and unordered associative containers. The relationship with `type_info` object is maintained through a pointer, therefore `type_index` is [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable").
### Member functions
| | |
| --- | --- |
| [(constructor)](type_index/type_index "cpp/types/type index/type index") | constructs the object (public member function) |
| (destructor)
(implicitly declared) | destroys the `type_index` object (public member function) |
| operator=
(implicitly declared) | assigns a `type_index` object (public member function) |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](type_index/operator_cmp "cpp/types/type index/operator cmp")
(removed in C++20)(C++20) | compares the underlying `[std::type\_info](type_info "cpp/types/type info")` objects (public member function) |
| [hash\_code](type_index/hash_code "cpp/types/type index/hash code") | returns hashed code (public member function) |
| [name](type_index/name "cpp/types/type index/name") | returns implementation defined name of the type, associated with underlying [`type_info`](type_info "cpp/types/type info") object (public member function) |
### Helper classes
| | |
| --- | --- |
| [std::hash<std::type\_index>](type_index/hash "cpp/types/type index/hash")
(C++11) | hash support for `std::type_index` (class template specialization) |
### Example
The following program is an example of an efficient type-value mapping.
```
#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <string>
#include <memory>
struct A {
virtual ~A() {}
};
struct B : A {};
struct C : A {};
int main()
{
std::unordered_map<std::type_index, std::string> type_names;
type_names[std::type_index(typeid(int))] = "int";
type_names[std::type_index(typeid(double))] = "double";
type_names[std::type_index(typeid(A))] = "A";
type_names[std::type_index(typeid(B))] = "B";
type_names[std::type_index(typeid(C))] = "C";
int i;
double d;
A a;
// note that we're storing pointer to type A
std::unique_ptr<A> b(new B);
std::unique_ptr<A> c(new C);
std::cout << "i is " << type_names[std::type_index(typeid(i))] << '\n';
std::cout << "d is " << type_names[std::type_index(typeid(d))] << '\n';
std::cout << "a is " << type_names[std::type_index(typeid(a))] << '\n';
std::cout << "*b is " << type_names[std::type_index(typeid(*b))] << '\n';
std::cout << "*c is " << type_names[std::type_index(typeid(*c))] << '\n';
}
```
Output:
```
i is int
d is double
a is A
*b is B
*c is C
```
### See also
| | |
| --- | --- |
| [type\_info](type_info "cpp/types/type info") | contains some type's information, generated by the implementation. This is the class returned by the [`typeid`](../language/typeid "cpp/language/typeid") operator. (class) |
cpp std::type_info std::type\_info
===============
| Defined in header `[<typeinfo>](../header/typeinfo "cpp/header/typeinfo")` | | |
| --- | --- | --- |
|
```
class type_info;
```
| | |
The class `type_info` holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the [`typeid`](../language/typeid "cpp/language/typeid") operator.
The `type_info` class is neither [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") nor [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable").
### Member functions
| | |
| --- | --- |
| (constructor)
[deleted] | has neither default nor copy constructors (public member function) |
| [(destructor)](type_info/~type_info "cpp/types/type info/~type info")
[virtual] | the virtual destructor makes `type_info` a polymorphic class (virtual public member function) |
| operator=
[deleted] | can not be copy-assigned (public member function) |
| [operator==operator!=](type_info/operator_cmp "cpp/types/type info/operator cmp")
(removed in C++20) | checks whether the objects refer to the same type (public member function) |
| [before](type_info/before "cpp/types/type info/before") | checks whether the referred type precedes referred type of another `type_info` object in the implementation defined order, i.e. orders the referred types (public member function) |
| [hash\_code](type_info/hash_code "cpp/types/type info/hash code")
(C++11) | returns a value which is identical for the same types (public member function) |
| [name](type_info/name "cpp/types/type info/name") | implementation defined name of the type (public member function) |
### See also
| | |
| --- | --- |
| [type\_index](type_index "cpp/types/type index")
(C++11) | wrapper around a `type_info` object, that can be used as index in associative and unordered associative containers (class) |
cpp std::is_object std::is\_object
===============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_object;
```
| | (since C++11) |
If `T` is an [object type](../language/type "cpp/language/type") (that is any possibly cv-qualified type other than function, reference, or `void` types), provides the member constant `value` equal `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_object` or `is_object_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_object_v = is_object<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an object type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Possible implementation
| |
| --- |
|
```
template< class T>
struct is_object : std::integral_constant<bool,
std::is_scalar<T>::value ||
std::is_array<T>::value ||
std::is_union<T>::value ||
std::is_class<T>::value> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
int main() {
class cls {};
std::cout << std::boolalpha;
std::cout << std::is_object<int>::value << '\n';
std::cout << std::is_object<int&>::value << '\n';
std::cout << std::is_object<cls>::value << '\n';
std::cout << std::is_object<cls&>::value << '\n';
}
```
Output:
```
true
false
true
false
```
### See also
| | |
| --- | --- |
| [is\_scalar](is_scalar "cpp/types/is scalar")
(C++11) | checks if a type is a scalar type (class template) |
| [is\_array](is_array "cpp/types/is array")
(C++11) | checks if a type is an array type (class template) |
| [is\_union](is_union "cpp/types/is union")
(C++11) | checks if a type is an union type (class template) |
| [is\_class](is_class "cpp/types/is class")
(C++11) | checks if a type is a non-union class type (class template) |
cpp std::is_arithmetic std::is\_arithmetic
===================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_arithmetic;
```
| | (since C++11) |
If `T` is an arithmetic type (that is, an integral type or a floating-point type) or a `cv-qualified` version thereof, provides the member constant `value` equal to `true`. For any other type, `value` is `false`.
The behavior of a program that adds specializations for `is_arithmetic` or `is_arithmetic_v` (since C++17) is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_arithmetic_v = is_arithmetic<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an arithmetic type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
Arithmetic types are the built-in types for which the [arithmetic operators](../language/operator_arithmetic "cpp/language/operator arithmetic") (+, -, \*, /) are defined (possibly in combination with the usual arithmetic conversions).
Specializations of `[std::numeric\_limits](numeric_limits "cpp/types/numeric limits")` are provided for all arithmetic types.
### Possible implementation
| |
| --- |
|
```
template< class T >
struct is_arithmetic : std::integral_constant<bool,
std::is_integral<T>::value ||
std::is_floating_point<T>::value> {};
```
|
### Example
```
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha
<< "A: " << std::is_arithmetic_v<A> << '\n' // false
<< "bool: " << std::is_arithmetic_v<bool> << '\n' // true
<< "int: " << std::is_arithmetic_v<int> << '\n' // true
<< "int const: " << std::is_arithmetic_v<int const> << '\n' // true
<< "int &: " << std::is_arithmetic_v<int&> << '\n' // false
<< "int *: " << std::is_arithmetic_v<int*> << '\n' // false
<< "float: " << std::is_arithmetic_v<float> << '\n' // true
<< "float const: " << std::is_arithmetic_v<float const> << '\n' // true
<< "float &: " << std::is_arithmetic_v<float&> << '\n' // false
<< "float *: " << std::is_arithmetic_v<float*> << '\n' // false
<< "char: " << std::is_arithmetic_v<char> << '\n' // true
<< "char const: " << std::is_arithmetic_v<char const> << '\n' // true
<< "char &: " << std::is_arithmetic_v<char&> << '\n' // false
<< "char *: " << std::is_arithmetic_v<char*> << '\n' // false
;
}
```
Output:
```
A: false
bool: true
int: true
int const: true
int &: false
int *: false
float: true
float const: true
float &: false
float *: false
char: true
char const: true
char &: false
char *: false
```
### See also
| | |
| --- | --- |
| [is\_integral](is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_floating\_point](is_floating_point "cpp/types/is floating point")
(C++11) | checks if a type is a floating-point type (class template) |
cpp std::void_t std::void\_t
============
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class... >
using void_t = void;
```
| | (since C++17) |
Utility metafunction that maps a sequence of any types to the type `void`. This metafunction is a convenient way to leverage [SFINAE](../language/sfinae "cpp/language/sfinae") prior to C++20's [concepts](../language/constraints "cpp/language/constraints"), in particular for conditionally removing functions from the [candidate set](../language/overload_resolution "cpp/language/overload resolution") based on whether an expression is valid in the [unevaluated context](../language/expressions#Unevaluated_expressions "cpp/language/expressions") (such as operand to [`decltype`](../language/decltype "cpp/language/decltype") expression), allowing to exist separate function overloads or specializations, based on supported operations.
### Notes
This metafunction is used in template metaprogramming to detect ill-formed types in SFINAE context:
```
// primary template handles types that have no nested ::type member:
template< class, class = void >
struct has_type_member : std::false_type { };
// specialization recognizes types that do have a nested ::type member:
template< class T >
struct has_type_member<T, std::void_t<typename T::type>> : std::true_type { };
```
It can also be used to detect validity of an expression:
```
// primary template handles types that do not support pre-increment:
template< class, class = void >
struct has_pre_increment_member : std::false_type { };
// specialization recognizes types that do support pre-increment:
template< class T >
struct has_pre_increment_member<T,
std::void_t<decltype( ++std::declval<T&>() )>
> : std::true_type { };
```
Until the resolution of [CWG issue 1558](https://cplusplus.github.io/CWG/issues/1558.html) (a C++11 defect), unused parameters in [alias templates](../language/type_alias "cpp/language/type alias") were not guaranteed to ensure SFINAE and could be ignored, so earlier compilers require a more complex definition of `void_t`, such as.
```
template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
```
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_void_t`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iomanip>
#include <iostream>
#include <map>
#include <type_traits>
#include <vector>
// Variable template that checks if a type has begin() and end() member functions
template <typename, typename = void>
constexpr bool is_iterable{};
template <typename T>
constexpr bool is_iterable<
T,
std::void_t< decltype(std::declval<T>().begin()),
decltype(std::declval<T>().end())
>
> = true;
// An iterator trait those value_type is the value_type of the iterated container,
// supports even back_insert_iterator (where value_type is void)
template <typename T, typename = void>
struct iterator_trait
: std::iterator_traits<T> {};
template <typename T>
struct iterator_trait<T, std::void_t<typename T::container_type>>
: std::iterator_traits<typename T::container_type::iterator> {};
class A {};
#define SHOW(...) std::cout << std::setw(34) << #__VA_ARGS__ << " = " << __VA_ARGS__ << '\n'
int main()
{
std::cout << std::boolalpha << std::left;
SHOW(is_iterable<std::vector<double>>);
SHOW(is_iterable<std::map<int, double>>);
SHOW(is_iterable<double>);
SHOW(is_iterable<A>);
using container_t = std::vector<int>;
container_t v;
static_assert(std::is_same_v<
container_t::value_type,
iterator_trait<decltype(std::begin(v))>::value_type
>);
static_assert(std::is_same_v<
container_t::value_type,
iterator_trait<decltype(std::back_inserter(v))>::value_type
>);
}
```
Output:
```
is_iterable<std::vector<double>> = true
is_iterable<std::map<int, double>> = true
is_iterable<double> = false
is_iterable<A> = false
```
### See also
| | |
| --- | --- |
| [enable\_if](enable_if "cpp/types/enable if")
(C++11) | conditionally [removes](../language/sfinae "cpp/language/sfinae") a function overload or template specialization from overload resolution (class template) |
cpp std::is_aggregate std::is\_aggregate
==================
| Defined in header `[<type\_traits>](../header/type_traits "cpp/header/type traits")` | | |
| --- | --- | --- |
|
```
template< class T >
struct is_aggregate;
```
| | (since C++17) |
Checks if `T` is an [aggregate type](../language/aggregate_initialization "cpp/language/aggregate initialization"). The member constant `value` is equal to `true` if `T` is an aggregate type and `false` otherwise.
The behavior is undefined if `[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>` is an incomplete type other than (possibly cv-qualified) `void`.
The behavior of a program that adds specializations for `is_aggregate` or `is_aggregate_v` is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| T | - | a type to check |
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T >
inline constexpr bool is_aggregate_v = is_aggregate<T>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` is an aggregate type , `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_is_aggregate`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <type_traits>
#include <new>
#include <utility>
// constructs a T at the uninitialized memory pointed to by p
// using list-initialization for aggregates and non-list initialization otherwise
template<class T, class... Args>
T* construct(T* p, Args&&... args) {
if constexpr(std::is_aggregate_v<T>) {
return ::new (static_cast<void*>(p)) T{std::forward<Args>(args)...};
}
else {
return ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
}
}
struct A { int x, y; };
struct B { B(int, const char*) { } };
int main() {
std::aligned_union_t<1, A, B> storage;
[[maybe_unused]] A* a = construct(reinterpret_cast<A*>(&storage), 1, 2);
[[maybe_unused]] B* b = construct(reinterpret_cast<B*>(&storage), 1, "hello");
}
```
| programming_docs |
cpp std::numeric_limits<T>::digits10 std::numeric\_limits<T>::digits10
=================================
| | | |
| --- | --- | --- |
|
```
static const int digits10;
```
| | (until C++11) |
|
```
static constexpr int digits10
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits10` is the number of base-10 digits that can be represented by the type `T` without change, that is, any number with this many significant decimal digits can be converted to a value of type `T` and back to decimal form, without change due to rounding or overflow. For base-[radix](radix "cpp/types/numeric limits/radix") types, it is the value of [digits](digits "cpp/types/numeric limits/digits") (`digits-1` for floating-point types) multiplied by \(\small \log\_{10}{radix}\)log
10(radix) and rounded down.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits10` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `0` |
| `char` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<char>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `signed char` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<signed char>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `unsigned char` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned char>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `wchar_t` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<wchar\_t>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `char8_t` (C++20) | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<char8_t>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `char16_t` (C++11) | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<char16\_t>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `char32_t` (C++11) | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<char32\_t>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `short` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<short>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `unsigned short` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned short>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `int` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<int>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `unsigned int` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned int>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `long` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<long>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `unsigned long` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned long>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `long long` (C++11) | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<long long>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `unsigned long long` (C++11) | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned long long>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` |
| `float` | `[FLT\_DIG](../climits "cpp/types/climits")` `/* 6 for IEEE float */` |
| `double` | `[DBL\_DIG](../climits "cpp/types/climits")` `/* 15 for IEEE double */` |
| `long double` | `[LDBL\_DIG](../climits "cpp/types/climits")` `/* 18 for 80-bit Intel long double; 33 for IEEE quadruple */` |
### Example
An 8-bit binary type can represent any two-digit decimal number exactly, but 3-digit decimal numbers 256..999 cannot be represented. The value of `digits10` for an 8-bit type is 2 (`8 \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` is 2.41).
The standard 32-bit IEEE 754 floating-point type has a 24 bit fractional part (23 bits written, one implied), which may suggest that it can represent 7 digit decimals (`24 \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)` is 7.22), but relative rounding errors are non-uniform and some floating-point values with 7 decimal digits do not survive conversion to 32-bit float and back: the smallest positive example is `8.589973e9`, which becomes `8.589974e9` after the roundtrip. These rounding errors cannot exceed one bit in the representation, and `digits10` is calculated as `(24-1)\*[std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2)`, which is 6.92. Rounding down results in the value 6.
Likewise, the 16-digit string `9007199254740993` does not survive text->double->text roundtrip, becoming `9007199254740992`: the 64-bit IEEE 754 type double guarantees this roundtrip only for 15 decimal digits.
### See also
| | |
| --- | --- |
| [max\_digits10](max_digits10 "cpp/types/numeric limits/max digits10")
[static] (C++11) | number of decimal digits necessary to differentiate all values of this type (public static member constant) |
| [radix](radix "cpp/types/numeric limits/radix")
[static] | the radix or integer base used by the representation of the given type (public static member constant) |
| [digits](digits "cpp/types/numeric limits/digits")
[static] | number of `radix` digits that can be represented without change (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::infinity std::numeric\_limits<T>::infinity
=================================
| | | |
| --- | --- | --- |
|
```
static T infinity() throw();
```
| | (until C++11) |
|
```
static constexpr T infinity() noexcept;
```
| | (since C++11) |
Returns the special value "positive infinity", as represented by the floating-point type `T`. Only meaningful if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_infinity == true`. In IEEE 754, the most common binary representation of floating-point numbers, the positive infinity is the value with all bits of the exponent set and all bits of the fraction cleared.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::infinity()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[HUGE\_VALF](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` |
| `double` | `[HUGE\_VAL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` |
| `long double` | `[HUGE\_VALL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` |
### Example
```
#include <iostream>
#include <limits>
int main()
{
double max = std::numeric_limits<double>::max();
double inf = std::numeric_limits<double>::infinity();
if(inf > max)
std::cout << inf << " is greater than " << max << '\n';
}
```
Output:
```
inf is greater than 1.79769e+308
```
### See also
| | |
| --- | --- |
| [has\_infinity](has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant) |
cpp std::numeric_limits<T>::has_denorm_loss std::numeric\_limits<T>::has\_denorm\_loss
==========================================
| | | |
| --- | --- | --- |
|
```
static const bool has_denorm_loss;
```
| | (until C++11) |
|
```
static constexpr bool has_denorm_loss;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_denorm\_loss` is `true` for all floating-point types `T` that detect loss of precision when creating a subnormal number as denormalization loss rather than as inexact result (see below).
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_denorm\_loss` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | implementation-defined |
| `double` | implementation-defined |
| `long double` | implementation-defined |
### Notes
Standard-compliant IEEE 754 floating-point implementations of subnormal numbers are required to detect the loss of accuracy associated with the creation of such number, if it occurs, and may do so in one of the two distinct ways:
1. Denormalization loss: the delivered result differs from what would have been computed were exponent range unbounded.
2. Inexact result: the delivered result differs from what would have been computed were both exponent range and precision unbounded.
No implementation of denormalization loss mechanism exists (accuracy loss is detected after rounding, as inexact result), and this option was removed in the 2008 revision of IEEE Std 754.
libstdc++, libc++, libCstd, and stlport4 define this constant as `false` for all floating-point types. Microsoft Visual Studio defines it as `true` for all floating-point types.
As with any floating-point computations, accuracy loss may raise `[FE\_INEXACT](../../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`.
### Example
### See also
| | |
| --- | --- |
| [tinyness\_before](tinyness_before "cpp/types/numeric limits/tinyness before")
[static] | identifies floating-point types that detect tinyness before rounding (public static member constant) |
| [has\_denorm](has_denorm "cpp/types/numeric limits/has denorm")
[static] | identifies the denormalization style used by the floating-point type (public static member constant) |
cpp std::numeric_limits<T>::has_infinity std::numeric\_limits<T>::has\_infinity
======================================
| | | |
| --- | --- | --- |
|
```
static const bool has_infinity;
```
| | (until C++11) |
|
```
static constexpr bool has_infinity;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_infinity` is `true` for all types `T` capable of representing the positive infinity as a distinct special value. This constant is meaningful for all floating-point types and is guaranteed to be `true` if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559 == true`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_infinity` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | usually `true` |
| `double` | usually `true` |
| `long double` | usually `true` |
### See also
| | |
| --- | --- |
| [infinity](infinity "cpp/types/numeric limits/infinity")
[static] | returns the positive infinity value of the given floating-point type (public static member function) |
| [has\_quiet\_NaN](has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant) |
| [has\_signaling\_NaN](has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant) |
cpp std::numeric_limits<T>::digits std::numeric\_limits<T>::digits
===============================
| | | |
| --- | --- | --- |
|
```
static const int digits;
```
| | (until C++11) |
|
```
static constexpr int digits;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits` is the number of digits in base-[radix](radix "cpp/types/numeric limits/radix") that can be represented by the type `T` without change. For integer types, this is the number of bits not counting the sign bit and the padding bits (if any). For floating-point types, this is the digits of the mantissa (for [IEC 559/IEEE 754](is_iec559 "cpp/types/numeric limits/is iec559") implementations, this is the number of digits stored for the mantissa plus one, because the mantissa has an implicit leading 1 and binary point).
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits` (assuming no padding bits) |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `1` |
| `char` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits) - [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<char>::is\_signed` |
| `signed char` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits) - 1` |
| `unsigned char` | `[CHAR\_BIT](../climits "cpp/types/climits")` |
| `wchar_t` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(wchar\_t) - [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<wchar\_t>::is\_signed` |
| `char8_t` (C++20) | `[CHAR\_BIT](../climits "cpp/types/climits")` |
| `char16_t` (C++11) | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(char16\_t)` |
| `char32_t` (C++11) | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(char32\_t)` |
| `short` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(short)-1` |
| `unsigned short` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(short)` |
| `int` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(int)-1` |
| `unsigned int` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(int)` |
| `long` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(long)-1` |
| `unsigned long` | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(long)` |
| `long long` (C++11) | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(long long)-1` |
| `unsigned long long` (C++11) | `[CHAR\_BIT](http://en.cppreference.com/w/cpp/types/climits)\*sizeof(long long)` |
| `float` | `[FLT\_MANT\_DIG](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MANT\_DIG](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MANT\_DIG](../climits "cpp/types/climits")` |
### See also
| | |
| --- | --- |
| [radix](radix "cpp/types/numeric limits/radix")
[static] | the radix or integer base used by the representation of the given type (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::is_integer std::numeric\_limits<T>::is\_integer
====================================
| | | |
| --- | --- | --- |
|
```
static const bool is_integer;
```
| | (until C++11) |
|
```
static constexpr bool is_integer;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_integer` is `true` for all integer arithmetic types `T` and `false` otherwise. This constant is meaningful for all specializations.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_integer` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `true` |
| `char` | `true` |
| `signed char` | `true` |
| `unsigned char` | `true` |
| `wchar_t` | `true` |
| `char8_t` (C++20) | `true` |
| `char16_t` (C++11) | `true` |
| `char32_t` (C++11) | `true` |
| `short` | `true` |
| `unsigned short` | `true` |
| `int` | `true` |
| `unsigned int` | `true` |
| `long` | `true` |
| `unsigned long` | `true` |
| `long long` (C++11) | `true` |
| `unsigned long long` (C++11) | `true` |
| `float` | `false` |
| `double` | `false` |
| `long double` | `false` |
### Example
```
#include <cstddef>
#include <cstdint>
#include <numeric>
int main()
{
static_assert(
std::numeric_limits<bool>::is_integer
&& std::numeric_limits<std::size_t>::is_integer
&& std::numeric_limits<std::int32_t>::is_integer
&& std::numeric_limits<std::int64_t>::is_integer
&& std::numeric_limits<decltype(42)>::is_integer
&& !std::numeric_limits<float>::is_integer
&& !std::numeric_limits<double>::is_integer
&& !std::numeric_limits<long double>::is_integer
&& !std::numeric_limits<decltype([](){})>::is_integer // P0315R4
);
}
```
### See also
| | |
| --- | --- |
| [is\_integral](../is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_signed](is_signed "cpp/types/numeric limits/is signed")
[static] | identifies signed types (public static member constant) |
| [is\_exact](is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
| [is\_bounded](is_bounded "cpp/types/numeric limits/is bounded")
[static] | identifies types that represent a finite set of values (public static member constant) |
cpp std::numeric_limits<T>::tinyness_before std::numeric\_limits<T>::tinyness\_before
=========================================
| | | |
| --- | --- | --- |
|
```
static const bool tinyness_before;
```
| | (until C++11) |
|
```
static constexpr bool tinyness_before;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::tinyness\_before` is `true` for all floating-point types `T` that test results of floating-point expressions for underflow before rounding.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::tinyness\_before` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | implementation-defined |
| `double` | implementation-defined |
| `long double` | implementation-defined |
### Notes
Standard-compliant IEEE 754 floating-point implementations are required to detect the floating-point underflow, and have two alternative situations where this can be done.
1. Underflow occurs (and `[FE\_UNDERFLOW](../../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised) if a computation produces a result whose absolute value, computed as though both the exponent range and the precision were unbounded, is smaller than `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()`. Such implementation detects tinyness before rounding (e.g. UltraSparc, POWER).
2. Underflow occurs (and `[FE\_UNDERFLOW](../../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised) if after the rounding of the result to the target floating-point type (that is, rounding to `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits` bits), the result's absolute value is smaller than `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()`. Formally, the absolute value of a nonzero result computed as though the exponent range were unbounded is smaller than `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()`. Such implementation detects tinyness after rounding (e.g. SuperSparc)
### Example
Multiplication of the largest subnormal number by the number one machine epsilon greater than 1.0 gives the tiny value 0x0.fffffffffffff8p-1022 before rounding, but normal value 1p-1022 after rounding. The implementation used to execute this test ([IBM Power7](https://en.wikipedia.org/wiki/IBM_Power_microprocessors#POWER7 "enwiki:IBM Power microprocessors")) detects tinyness before rounding.
```
#include <iostream>
#include <limits>
#include <cmath>
#include <cfenv>
int main()
{
std::cout << "Tinyness before: " << std::boolalpha
<< std::numeric_limits<double>::tinyness_before << '\n';
double denorm_max = std::nextafter(std::numeric_limits<double>::min(), 0);
double multiplier = 1 + std::numeric_limits<double>::epsilon();
std::feclearexcept(FE_ALL_EXCEPT);
double result = denorm_max*multiplier; // Underflow only if tinyness_before
if(std::fetestexcept(FE_UNDERFLOW))
std::cout << "Underflow detected\n";
std::cout << std::hexfloat << denorm_max << " x " << multiplier << " = "
<< result << '\n';
}
```
Possible output:
```
Tinyness before: true
Underflow detected
0xf.ffffffffffffp-1030 x 0x1.0000000000001p+0 = 0x1p-1022
```
### See also
| | |
| --- | --- |
| [has\_denorm\_loss](has_denorm_loss "cpp/types/numeric limits/has denorm loss")
[static] | identifies the floating-point types that detect loss of precision as denormalization loss rather than inexact result (public static member constant) |
| [has\_denorm](has_denorm "cpp/types/numeric limits/has denorm")
[static] | identifies the denormalization style used by the floating-point type (public static member constant) |
| programming_docs |
cpp std::numeric_limits<T>::has_denorm std::numeric\_limits<T>::has\_denorm
====================================
| | | |
| --- | --- | --- |
|
```
static const std::float_denorm_style has_denorm;
```
| | (until C++11) |
|
```
static constexpr std::float_denorm_style has_denorm;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_denorm` identifies the floating-point types that support [subnormal values](https://en.wikipedia.org/wiki/Denormal_number "enwiki:Denormal number").
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_denorm` |
| --- | --- |
| /\* non-specialized \*/ | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `bool` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `char` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `signed char` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `unsigned char` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `wchar_t` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `char8_t` (C++20) | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `char16_t` (C++11) | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `char32_t` (C++11) | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `short` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `unsigned short` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `int` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `unsigned int` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `long` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `unsigned long` | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `long long` (C++11) | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `unsigned long long` (C++11) | `[std::denorm\_absent](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `float` | usually `[std::denorm\_present](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `double` | usually `[std::denorm\_present](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
| `long double` | usually `[std::denorm\_present](float_denorm_style "cpp/types/numeric limits/float denorm style")` |
### See also
| | |
| --- | --- |
| [denorm\_min](denorm_min "cpp/types/numeric limits/denorm min")
[static] | returns the smallest positive subnormal value of the given floating-point type (public static member function) |
| [float\_denorm\_style](float_denorm_style "cpp/types/numeric limits/float denorm style") | indicates floating-point denormalization modes (enum) |
cpp std::numeric_limits<T>::max_digits10 std::numeric\_limits<T>::max\_digits10
======================================
| | | |
| --- | --- | --- |
|
```
static constexpr int max_digits10
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_digits10` is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type `T`, such as necessary for serialization/deserialization to text. This constant is meaningful for all floating-point types.
### Standard specializations
| `T` | Value of [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_digits10 |
| --- | --- |
| /\* non-specialized \*/ (C++11) | `0` |
| `bool` (C++11) | `0` |
| `char` (C++11) | `0` |
| `signed char` (C++11) | `0` |
| `unsigned char` (C++11) | `0` |
| `wchar_t` (C++11) | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` (C++11) | `0` |
| `unsigned short` (C++11) | `0` |
| `int` (C++11) | `0` |
| `unsigned int` (C++11) | `0` |
| `long` (C++11) | `0` |
| `unsigned long` (C++11) | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` (C++11) | `[FLT\_DECIMAL\_DIG](../climits "cpp/types/climits")` or `[std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)([std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<float>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2) + 1)` |
| `double` (C++11) | `[DBL\_DECIMAL\_DIG](../climits "cpp/types/climits")` or`[std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)([std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<double>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2) + 1)` |
| `long double` (C++11) | `[DECIMAL\_DIG](../climits "cpp/types/climits")` or `[LDBL\_DECIMAL\_DIG](../climits "cpp/types/climits")` or`[std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)([std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<long double>::digits \* [std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)(2) + 1)` |
### Notes
Unlike most mathematical operations, the conversion of a floating-point value to text and back is *exact* as long as at least `max_digits10` were used (`9` for `float`, `17` for `double`): it is guaranteed to produce the same floating-point value, even though the intermediate text representation is not exact. It may take over a hundred decimal digits to represent the precise value of a `float` in decimal notation.
### Example
```
#include <limits>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <iostream>
int main()
{
float value = 10.0000086;
constexpr auto digits10 = std::numeric_limits<decltype(value)>::digits10;
constexpr auto max_digits10 = std::numeric_limits<decltype(value)>::max_digits10;
constexpr auto submax_digits10 = max_digits10 - 1;
std::cout
<< "float:\n"
<< " digits10 is " << digits10 << " digits" << '\n'
<< " max_digits10 is " << max_digits10 << " digits" << '\n'
<< "submax_digits10 is " << submax_digits10 << " digits" << '\n'
<< '\n';
const auto original_precision = std::cout.precision();
for( auto i = 0; i < 5; ++i )
{
std::cout
<< " max_digits10: " << std::setprecision(max_digits10) << value << '\n'
<< "submax_digits10: " << std::setprecision(submax_digits10) << value << '\n'
<< '\n';
value = std::nextafter( value, std::numeric_limits<decltype(value)>::max() );
}
std::cout.precision( original_precision );
}
```
Output:
```
float:
digits10 is 6 digits
max_digits10 is 9 digits
submax_digits10 is 8 digits
max_digits10: 10.0000086
submax_digits10: 10.000009
max_digits10: 10.0000095
submax_digits10: 10.00001
max_digits10: 10.0000105
submax_digits10: 10.00001
max_digits10: 10.0000114
submax_digits10: 10.000011
max_digits10: 10.0000124
submax_digits10: 10.000012
```
### See also
| | |
| --- | --- |
| [radix](radix "cpp/types/numeric limits/radix")
[static] | the radix or integer base used by the representation of the given type (public static member constant) |
| [digits](digits "cpp/types/numeric limits/digits")
[static] | number of `radix` digits that can be represented without change (public static member constant) |
| [digits10](digits10 "cpp/types/numeric limits/digits10")
[static] | number of decimal digits that can be represented without change (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::lowest std::numeric\_limits<T>::lowest
===============================
| | | |
| --- | --- | --- |
|
```
static constexpr T lowest() noexcept;
```
| | (since C++11) |
Returns the lowest finite value representable by the numeric type `T`, that is, a finite value `x` such that there is no other finite value `y` where `y < x`. This is different from `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()` for floating-point types. Only meaningful for bounded types.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::lowest()` |
| --- | --- |
| /\* non-specialized \*/ (C++11) | `T()` |
| `bool` (C++11) | `false` |
| `char` (C++11) | `[CHAR\_MIN](../climits "cpp/types/climits")` |
| `signed char` (C++11) | `[SCHAR\_MIN](../climits "cpp/types/climits")` |
| `unsigned char` (C++11) | `0` |
| `wchar_t` (C++11) | `[WCHAR\_MIN](../climits "cpp/types/climits")` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` (C++11) | `[SHRT\_MIN](../climits "cpp/types/climits")` |
| `unsigned short` (C++11) | `0` |
| `int` (C++11) | `[INT\_MIN](../climits "cpp/types/climits")` |
| `unsigned int` (C++11) | `0` |
| `long` (C++11) | `[LONG\_MIN](../climits "cpp/types/climits")` |
| `unsigned long` (C++11) | `0` |
| `long long` (C++11) | `[LLONG\_MIN](../climits "cpp/types/climits")` |
| `unsigned long long` (C++11) | `0` |
| `float` (C++11) | `-[FLT\_MAX](http://en.cppreference.com/w/cpp/types/climits)` |
| `double` (C++11) | `-[DBL\_MAX](http://en.cppreference.com/w/cpp/types/climits)` |
| `long double` (C++11) | `-[LDBL\_MAX](http://en.cppreference.com/w/cpp/types/climits)` |
### Notes
For every standard C++ floating-point type `T` `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::lowest() == -[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max()`, but this does not necessarily have to be the case for any third-party specialization.
### Example
Demonstrates min, max, and lowest for floating-point types.
```
#include <limits>
#include <iostream>
int main()
{
std::cout << "std::numeric_limits<T>::min():\n"
<< "\tfloat: " << std::numeric_limits<float>::min()
<< " or " << std::hexfloat << std::numeric_limits<float>::min() << '\n'
<< "\tdouble: " << std::defaultfloat << std::numeric_limits<double>::min()
<< " or " << std::hexfloat << std::numeric_limits<double>::min() << '\n';
std::cout << "std::numeric_limits<T>::lowest():\n"
<< "\tfloat: " << std::defaultfloat << std::numeric_limits<float>::lowest()
<< " or " << std::hexfloat << std::numeric_limits<float>::lowest() << '\n'
<< "\tdouble: " << std::defaultfloat << std::numeric_limits<double>::lowest()
<< " or " << std::hexfloat << std::numeric_limits<double>::lowest() << '\n';
std::cout << "std::numeric_limits<T>::max():\n"
<< "\tfloat: " << std::defaultfloat << std::numeric_limits<float>::max()
<< " or " << std::hexfloat << std::numeric_limits<float>::max() << '\n'
<< "\tdouble: " << std::defaultfloat << std::numeric_limits<double>::max()
<< " or " << std::hexfloat << std::numeric_limits<double>::max() << '\n';
}
```
Output:
```
std::numeric_limits<T>::min():
float: 1.17549e-38 or 0x1p-126
double: 2.22507e-308 or 0x1p-1022
std::numeric_limits<T>::lowest():
float: -3.40282e+38 or -0x1.fffffep+127
double: -1.79769e+308 or -0x1.fffffffffffffp+1023
std::numeric_limits<T>::max():
float: 3.40282e+38 or 0x1.fffffep+127
double: 1.79769e+308 or 0x1.fffffffffffffp+1023
```
### See also
| | |
| --- | --- |
| [min](min "cpp/types/numeric limits/min")
[static] | returns the smallest finite value of the given type (public static member function) |
| [denorm\_min](denorm_min "cpp/types/numeric limits/denorm min")
[static] | returns the smallest positive subnormal value of the given floating-point type (public static member function) |
| [max](max "cpp/types/numeric limits/max")
[static] | returns the largest finite value of the given type (public static member function) |
cpp std::float_round_style std::float\_round\_style
========================
| Defined in header `[<limits>](../../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
enum float_round_style {
round_indeterminate = -1,
round_toward_zero = 0,
round_to_nearest = 1,
round_toward_infinity = 2,
round_toward_neg_infinity = 3
};
```
| | |
Enumeration constants of type `std::float_round_style` indicate the rounding style used by floating-point arithmetics whenever a result of an expression is stored in an object of a floating-point type. The values are:
### Enumeration constants
| Name | Definition |
| --- | --- |
| `std::round_indeterminate` | Rounding style cannot be determined |
| `std::round_toward_zero` | Rounding toward zero |
| `std::round_to_nearest` | Rounding toward nearest representable value |
| `std::round_toward_infinity` | Rounding toward positive infinity |
| `std::round_toward_neg_infinity` | Rounding toward negative infinity |
### See also
| | |
| --- | --- |
| [round\_style](round_style "cpp/types/numeric limits/round style")
[static] | identifies the rounding style used by the type (public static member constant) |
| [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")
(C++11) | floating-point rounding direction (macro constant) |
cpp std::numeric_limits<T>::has_quiet_NaN std::numeric\_limits<T>::has\_quiet\_NaN
========================================
| | | |
| --- | --- | --- |
|
```
static const bool has_quiet_NaN;
```
| | (until C++11) |
|
```
static constexpr bool has_quiet_NaN;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_quiet\_NaN` is `true` for all types `T` capable of representing the special value "Quiet [Not-A-Number](https://en.wikipedia.org/wiki/NaN "enwiki:NaN")". This constant is meaningful for all floating-point types and is guaranteed to be `true` if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559 == true`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_quiet\_NaN` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | usually `true` |
| `double` | usually `true` |
| `long double` | usually `true` |
### See also
| | |
| --- | --- |
| [quiet\_NaN](quiet_nan "cpp/types/numeric limits/quiet NaN")
[static] | returns a quiet NaN value of the given floating-point type (public static member function) |
| [has\_infinity](has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant) |
| [has\_signaling\_NaN](has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant) |
cpp std::float_denorm_style std::float\_denorm\_style
=========================
| Defined in header `[<limits>](../../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
enum float_denorm_style {
denorm_indeterminate = -1,
denorm_absent = 0,
denorm_present = 1
};
```
| | |
Enumeration constants of type `std::float_denorm_style` indicate support of subnormal values by floating-point types.
### Enumeration constants
| Name | Definition |
| --- | --- |
| `std::denorm_indeterminate` | Support of subnormal values cannot be determined |
| `std::denorm_absent` | The type does not support subnormal values |
| `std::denorm_present` | The type allows subnormal values |
### See also
| | |
| --- | --- |
| [has\_denorm](has_denorm "cpp/types/numeric limits/has denorm")
[static] | identifies the denormalization style used by the floating-point type (public static member constant) |
cpp std::numeric_limits<T>::min_exponent std::numeric\_limits<T>::min\_exponent
======================================
| | | |
| --- | --- | --- |
|
```
static const int min_exponent;
```
| | (until C++11) |
|
```
static constexpr int min_exponent;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min\_exponent` is the lowest negative number `n` such that \(\scriptsize r^{n-1}\)rn-1
, where `r` is `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix`, is a valid normalized value of the floating-point type `T`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min\_exponent` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `0` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_MIN\_EXP](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MIN\_EXP](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MIN\_EXP](../climits "cpp/types/climits")` |
### Example
Demonstrates the relationships of `min_exponent`, `min_exponent10`, `min`, and `radix` for the type `float`:
```
#include <iostream>
int main()
{
std::cout << "min() = " << std::numeric_limits<float>::min() << '\n'
<< "min_exponent10 = " << std::numeric_limits<float>::min_exponent10 << '\n'
<< std::hexfloat
<< "min() = " << std::numeric_limits<float>::min() << '\n'
<< "min_exponent = " << std::numeric_limits<float>::min_exponent << '\n';
}
```
Output:
```
min() = 1.17549e-38
min_exponent10 = -37
min() = 0x1p-126
min_exponent = -125
```
### See also
| | |
| --- | --- |
| [radix](radix "cpp/types/numeric limits/radix")
[static] | the radix or integer base used by the representation of the given type (public static member constant) |
| [min\_exponent10](min_exponent10 "cpp/types/numeric limits/min exponent10")
[static] | the smallest negative power of ten that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
| [max\_exponent10](max_exponent10 "cpp/types/numeric limits/max exponent10")
[static] | the largest integer power of 10 that is a valid finite floating-point value (public static member constant) |
| programming_docs |
cpp std::numeric_limits<T>::radix std::numeric\_limits<T>::radix
==============================
| | | |
| --- | --- | --- |
|
```
static const int radix;
```
| | (until C++11) |
|
```
static constexpr int radix;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix` is the base of the number system used in the representation of the type. It is 2 for all binary numeric types, but it may be, for example, 10 for IEEE 754 [decimal floating-point types](https://en.wikipedia.org/wiki/Decimal64_floating-point_format "enwiki:Decimal64 floating-point format") or for third-party [binary-coded decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal "enwiki:Binary-coded decimal") integers. This constant is meaningful for all specializations.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `2` |
| `char` | `2` |
| `signed char` | `2` |
| `unsigned char` | `2` |
| `wchar_t` | `2` |
| `char8_t` (C++20) | `2` |
| `char16_t` (C++11) | `2` |
| `char32_t` (C++11) | `2` |
| `short` | `2` |
| `unsigned short` | `2` |
| `int` | `2` |
| `unsigned int` | `2` |
| `long` | `2` |
| `unsigned long` | `2` |
| `long long` (C++11) | `2` |
| `unsigned long long` (C++11) | `2` |
| `float` | `[FLT\_RADIX](../climits "cpp/types/climits")` |
| `double` | `[FLT\_RADIX](../climits "cpp/types/climits")` |
| `long double` | `[FLT\_RADIX](../climits "cpp/types/climits")` |
### See also
| | |
| --- | --- |
| [digits](digits "cpp/types/numeric limits/digits")
[static] | number of `radix` digits that can be represented without change (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::is_modulo std::numeric\_limits<T>::is\_modulo
===================================
| | | |
| --- | --- | --- |
|
```
static const bool is_modulo;
```
| | (until C++11) |
|
```
static constexpr bool is_modulo;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_modulo` is `true` for all arithmetic types `T` that are possible to (until C++11)handle overflows with modulo arithmetic, that is, if the result of addition, subtraction, multiplication, or division of this type would fall outside the range `[min(), max()]`, the value returned by such operation differs from the expected value by a multiple of `max()-min()+1`.
| | |
| --- | --- |
| `is_modulo` is `false` for signed integer types, unless the implementation defines signed integer overflow to wrap. | (since C++11) |
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_modulo` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | implementation-defined |
| `signed char` | implementation-defined |
| `unsigned char` | `true` |
| `wchar_t` | implementation-defined |
| `char8_t` (C++20) | `true` |
| `char16_t` (C++11) | `true` |
| `char32_t` (C++11) | `true` |
| `short` | implementation-defined |
| `unsigned short` | `true` |
| `int` | implementation-defined |
| `unsigned int` | `true` |
| `long` | implementation-defined |
| `unsigned long` | `true` |
| `long long` (C++11) | implementation-defined |
| `unsigned long long` (C++11) | `true` |
| `float` | `false` |
| `double` | `false` |
| `long double` | `false` |
### Notes
Although the C++11 standard still says "On most machines, this is true for signed integers.", it is a defect and has been corrected. The exact wording changed from C++03 to C++11 in such a way that the `true` value is no longer compatible with [undefined behavior on signed integer overflow](../../language/operator_arithmetic#Overflows "cpp/language/operator arithmetic"). Because of that, the implementations that rely on signed overflow being undefined (for optimization opportunities) now set `is_modulo` to `false` for signed integers. See for example [GCC PR 22200](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=22200).
### Example
Demonstrates the behavior of modulo types.
```
#include <iostream>
#include <type_traits>
#include <limits>
template<class T>
typename std::enable_if<std::numeric_limits<T>::is_modulo>::type
check_overflow()
{
std::cout << "\nmax value is " << std::numeric_limits<T>::max() << '\n'
<< "min value is " << std::numeric_limits<T>::min() << '\n'
<< "max value + 1 is " << std::numeric_limits<T>::max()+1 << '\n';
}
int main()
{
check_overflow<int>();
check_overflow<unsigned long>();
// check_overflow<float>(); // compile-time error, not a modulo type
}
```
Possible output:
```
max value is 2147483647
min value is -2147483648
max value + 1 is -2147483648
max value is 18446744073709551615
min value is 0
max value + 1 is 0
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2422](https://cplusplus.github.io/LWG/issue2422) | C++11 | `is_modulo` was required to `true`for signed integer types on most machines | required to be `false` for signed integer typesunless signed integer overflow is defined to wrap |
### See also
| | |
| --- | --- |
| [is\_integer](is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_iec559](is_iec559 "cpp/types/numeric limits/is iec559")
[static] | identifies the IEC 559/IEEE 754 floating-point types (public static member constant) |
| [is\_exact](is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
cpp std::numeric_limits<T>::round_error std::numeric\_limits<T>::round\_error
=====================================
| | | |
| --- | --- | --- |
|
```
static T round_error() throw();
```
| | (until C++11) |
|
```
static constexpr T round_error() noexcept;
```
| | (since C++11) |
Returns the largest possible rounding error in ULPs (units in the last place) as defined by ISO 10967, which can vary from 0.5 (rounding to the nearest digit) to 1.0 (rounding to zero or to infinity). It is only meaningful if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_integer == false`.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::round\_error()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `0.5F` |
| `double` | `0.5` |
| `long double` | `0.5L` |
### See also
| | |
| --- | --- |
| [round\_style](round_style "cpp/types/numeric limits/round style")
[static] | identifies the rounding style used by the type (public static member constant) |
cpp std::numeric_limits<T>::max std::numeric\_limits<T>::max
============================
| Defined in header `[<limits>](../../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
static T max() throw();
```
| | (until C++11) |
|
```
static constexpr T max() noexcept;
```
| | (since C++11) |
Returns the maximum finite value representable by the numeric type `T`. Meaningful for all bounded types.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `true` |
| `char` | `[CHAR\_MAX](../climits "cpp/types/climits")` |
| `signed char` | `[SCHAR\_MAX](../climits "cpp/types/climits")` |
| `unsigned char` | `[UCHAR\_MAX](../climits "cpp/types/climits")` |
| `wchar_t` | `[WCHAR\_MAX](../climits "cpp/types/climits")` |
| `char8_t` (C++20) | `[UCHAR\_MAX](../climits "cpp/types/climits")` |
| `char16_t` (C++11) | `[UINT\_LEAST16\_MAX](../integer "cpp/types/integer")` |
| `char32_t` (C++11) | `[UINT\_LEAST32\_MAX](../integer "cpp/types/integer")` |
| `short` | `[SHRT\_MAX](../climits "cpp/types/climits")` |
| `unsigned short` | `[USHRT\_MAX](../climits "cpp/types/climits")` |
| `int` | `[INT\_MAX](../climits "cpp/types/climits")` |
| `unsigned int` | `[UINT\_MAX](../climits "cpp/types/climits")` |
| `long` | `[LONG\_MAX](../climits "cpp/types/climits")` |
| `unsigned long` | `[ULONG\_MAX](../climits "cpp/types/climits")` |
| `long long` (C++11) | `[LLONG\_MAX](../climits "cpp/types/climits")` |
| `unsigned long long` (C++11) | `[ULLONG\_MAX](../climits "cpp/types/climits")` |
| `float` | `[FLT\_MAX](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MAX](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MAX](../climits "cpp/types/climits")` |
### Example
Demonstrates the use of max() with some fundamental types and some standard library typedefs (the output is system-specific).
```
#include <limits>
#include <cstddef>
#include <iostream>
int main()
{
std::cout << "short: " << std::dec << std::numeric_limits<short>::max()
<< " or " << std::hex << std::showbase << std::numeric_limits<short>::max() << '\n'
<< "int: " << std::dec << std::numeric_limits<int>::max()
<< " or " << std::hex << std::numeric_limits<int>::max() << '\n' << std::dec
<< "streamsize: " << std::dec << std::numeric_limits<std::streamsize>::max()
<< " or " << std::hex << std::numeric_limits<std::streamsize>::max() << '\n'
<< "size_t: " << std::dec << std::numeric_limits<std::size_t>::max()
<< " or " << std::hex << std::numeric_limits<std::size_t>::max() << '\n'
<< "float: " << std::numeric_limits<float>::max()
<< " or " << std::hexfloat << std::numeric_limits<float>::max() << '\n'
<< "double: " << std::defaultfloat << std::numeric_limits<double>::max()
<< " or " << std::hexfloat << std::numeric_limits<double>::max() << '\n';
}
```
Possible output:
```
short: 32767 or 0x7fff
int: 2147483647 or 0x7fffffff
streamsize: 9223372036854775807 or 0x7fffffffffffffff
size_t: 18446744073709551615 or 0xffffffffffffffff
float: 3.40282e+38 or 0x1.fffffep+127
double: 1.79769e+308 or 0x1.fffffffffffffp+1023
```
### See also
| | |
| --- | --- |
| [lowest](lowest "cpp/types/numeric limits/lowest")
[static] (C++11) | returns the lowest finite value of the given type (public static member function) |
| [min](min "cpp/types/numeric limits/min")
[static] | returns the smallest finite value of the given type (public static member function) |
cpp std::numeric_limits<T>::max_exponent std::numeric\_limits<T>::max\_exponent
======================================
| | | |
| --- | --- | --- |
|
```
static const int max_exponent;
```
| | (until C++11) |
|
```
static constexpr int max_exponent;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_exponent` is the largest positive number `n` such that \(\scriptsize r^{n-1}\)rn-1
, where `r` is `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix`, is a representable finite value of the floating-point type `T`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_exponent` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `0` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_MAX\_EXP](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MAX\_EXP](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MAX\_EXP](../climits "cpp/types/climits")` |
### Example
Demonstrates the relationships of `max_exponent`, `max_exponent10`, and `max()` for the type `float`:
```
#include <iostream>
#include <limits>
int main()
{
std::cout << "max() = " << std::numeric_limits<float>::max() << '\n'
<< "max_exponent10 = " << std::numeric_limits<float>::max_exponent10 << '\n'
<< std::hexfloat
<< "max() = " << std::numeric_limits<float>::max() << '\n'
<< "max_exponent = " << std::numeric_limits<float>::max_exponent << '\n';
}
```
Output:
```
max() = 3.40282e+38
max_exponent10 = 38
max() = 0x1.fffffep+127
max_exponent = 128
```
### See also
| | |
| --- | --- |
| [min\_exponent10](min_exponent10 "cpp/types/numeric limits/min exponent10")
[static] | the smallest negative power of ten that is a valid normalized floating-point value (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent10](max_exponent10 "cpp/types/numeric limits/max exponent10")
[static] | the largest integer power of 10 that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::min std::numeric\_limits<T>::min
============================
| Defined in header `[<limits>](../../header/limits "cpp/header/limits")` | | |
| --- | --- | --- |
|
```
static T min() throw();
```
| | (until C++11) |
|
```
static constexpr T min() noexcept;
```
| | (since C++11) |
Returns the minimum finite value representable by the numeric type `T`.
For floating-point types with denormalization, `min` returns the minimum positive normalized value. *Note that this behavior may be unexpected*, especially when compared to the behavior of `min` for integral types. To find the value that has no values less than it, use [`numeric_limits::lowest`](lowest "cpp/types/numeric limits/lowest").
`min` is only meaningful for bounded types and for unbounded unsigned types, that is, types that represent an infinite set of negative values have no meaningful minimum.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `[CHAR\_MIN](../climits "cpp/types/climits")` |
| `signed char` | `[SCHAR\_MIN](../climits "cpp/types/climits")` |
| `unsigned char` | `0` |
| `wchar_t` | `[WCHAR\_MIN](../climits "cpp/types/climits")` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `[SHRT\_MIN](../climits "cpp/types/climits")` |
| `unsigned short` | `0` |
| `int` | `[INT\_MIN](../climits "cpp/types/climits")` |
| `unsigned int` | `0` |
| `long` | `[LONG\_MIN](../climits "cpp/types/climits")` |
| `unsigned long` | `0` |
| `long long` (C++11) | `[LLONG\_MIN](../climits "cpp/types/climits")` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_MIN](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MIN](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MIN](../climits "cpp/types/climits")` |
### Example
Demonstrates the use with typedef types, and the difference in the sign of the result between integer and floating-point types.
```
#include <limits>
#include <cstddef>
#include <iostream>
int main()
{
std::cout
<< "short: " << std::dec << std::numeric_limits<short>::min()
<< " or " << std::hex << std::showbase
<< std::numeric_limits<short>::min() << '\n'
<< "int: " << std::dec << std::numeric_limits<int>::min() << std::showbase
<< " or " << std::hex << std::numeric_limits<int>::min() << '\n' << std::dec
<< "ptrdiff_t: " << std::numeric_limits<std::ptrdiff_t>::min() << std::showbase
<< " or " << std::hex << std::numeric_limits<std::ptrdiff_t>::min() << '\n'
<< "float: " << std::numeric_limits<float>::min()
<< " or " << std::hexfloat << std::numeric_limits<float>::min() << '\n'
<< "double: " << std::defaultfloat << std::numeric_limits<double>::min()
<< " or " << std::hexfloat << std::numeric_limits<double>::min() << '\n';
}
```
Possible output:
```
short: -32768 or 0x8000
int: -2147483648 or 0x80000000
ptrdiff_t: -9223372036854775808 or 0x8000000000000000
float: 1.17549e-38 or 0x1p-126
double: 2.22507e-308 or 0x1p-1022
```
### See also
| | |
| --- | --- |
| [lowest](lowest "cpp/types/numeric limits/lowest")
[static] (C++11) | returns the lowest finite value of the given type (public static member function) |
| [denorm\_min](denorm_min "cpp/types/numeric limits/denorm min")
[static] | returns the smallest positive subnormal value of the given floating-point type (public static member function) |
| [max](max "cpp/types/numeric limits/max")
[static] | returns the largest finite value of the given type (public static member function) |
cpp std::numeric_limits<T>::epsilon std::numeric\_limits<T>::epsilon
================================
| | | |
| --- | --- | --- |
|
```
static T epsilon() throw();
```
| | (until C++11) |
|
```
static constexpr T epsilon() noexcept;
```
| | (since C++11) |
Returns the machine epsilon, that is, the difference between `1.0` and the next value representable by the floating-point type `T`. It is only meaningful if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_integer == false`.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::epsilon()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long`(C++11) | `0` |
| `float` | `[FLT\_EPSILON](../climits "cpp/types/climits")` |
| `double` | `[DBL\_EPSILON](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_EPSILON](../climits "cpp/types/climits")` |
### Example
Demonstrates the use of machine epsilon to compare floating-point values for equality.
```
#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <algorithm>
template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
almost_equal(T x, T y, int ulp)
{
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp
// unless the result is subnormal
|| std::fabs(x-y) < std::numeric_limits<T>::min();
}
int main()
{
double d1 = 0.2;
double d2 = 1 / std::sqrt(5) / std::sqrt(5);
std::cout << std::fixed << std::setprecision(20)
<< "d1=" << d1 << "\nd2=" << d2 << '\n';
if(d1 == d2)
std::cout << "d1 == d2\n";
else
std::cout << "d1 != d2\n";
if(almost_equal(d1, d2, 2))
std::cout << "d1 almost equals d2\n";
else
std::cout << "d1 does not almost equal d2\n";
}
```
Output:
```
d1=0.20000000000000001110
d2=0.19999999999999998335
d1 != d2
d1 almost equals d2
```
### See also
| | |
| --- | --- |
| [nextafternextafterfnextafterlnexttowardnexttowardfnexttowardl](../../numeric/math/nextafter "cpp/numeric/math/nextafter")
(C++11)(C++11) (C++11)(C++11)(C++11)(C++11) | next representable floating point value towards the given value (function) |
| programming_docs |
cpp std::numeric_limits<T>::is_specialized std::numeric\_limits<T>::is\_specialized
========================================
| | | |
| --- | --- | --- |
|
```
static const bool is_specialized;
```
| | (until C++11) |
|
```
static constexpr bool is_specialized;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_specialized` is `true` for all `T` for which there exists a specialization of `[std::numeric\_limits](../numeric_limits "cpp/types/numeric limits")`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_specialized` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `true` |
| `char` | `true` |
| `signed char` | `true` |
| `unsigned char` | `true` |
| `wchar_t` | `true` |
| `char8_t` (C++20) | `true` |
| `char16_t` (C++11) | `true` |
| `char32_t` (C++11) | `true` |
| `short` | `true` |
| `unsigned short` | `true` |
| `int` | `true` |
| `unsigned int` | `true` |
| `long` | `true` |
| `unsigned long` | `true` |
| `long long` (C++11) | `true` |
| `unsigned long long` (C++11) | `true` |
| `float` | `true` |
| `double` | `true` |
| `long double` | `true` |
### See also
| | |
| --- | --- |
| [is\_integer](is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_iec559](is_iec559 "cpp/types/numeric limits/is iec559")
[static] | identifies the IEC 559/IEEE 754 floating-point types (public static member constant) |
| [is\_exact](is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
| [is\_bounded](is_bounded "cpp/types/numeric limits/is bounded")
[static] | identifies types that represent a finite set of values (public static member constant) |
cpp std::numeric_limits<T>::is_bounded std::numeric\_limits<T>::is\_bounded
====================================
| | | |
| --- | --- | --- |
|
```
static const bool is_bounded;
```
| | (until C++11) |
|
```
static constexpr bool is_bounded;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_bounded` is `true` for all arithmetic types `T` that represent a finite set of values. While all fundamental types are bounded, this constant would be `false` in a specialization of `[std::numeric\_limits](../numeric_limits "cpp/types/numeric limits")` for a library-provided arbitrary precision arithmetic type.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_bounded` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `true` |
| `char` | `true` |
| `signed char` | `true` |
| `unsigned char` | `true` |
| `wchar_t` | `true` |
| `char8_t` (C++20) | `true` |
| `char16_t` (C++11) | `true` |
| `char32_t` (C++11) | `true` |
| `short` | `true` |
| `unsigned short` | `true` |
| `int` | `true` |
| `unsigned int` | `true` |
| `long` | `true` |
| `unsigned long` | `true` |
| `long long` (C++11) | `true` |
| `unsigned long long` (C++11) | `true` |
| `float` | `true` |
| `double` | `true` |
| `long double` | `true` |
### See also
| | |
| --- | --- |
| [is\_integer](is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_signed](is_signed "cpp/types/numeric limits/is signed")
[static] | identifies signed types (public static member constant) |
| [is\_exact](is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
cpp std::numeric_limits<T>::max_exponent10 std::numeric\_limits<T>::max\_exponent10
========================================
| | | |
| --- | --- | --- |
|
```
static const int max_exponent10;
```
| | (until C++11) |
|
```
static constexpr int max_exponent10;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_exponent10` is the largest positive number `n` such that \(\scriptsize 10^n\)10n
is a representable finite value of the floating-point type `T`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max\_exponent10` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `0` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_MAX\_10\_EXP](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MAX\_10\_EXP](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MAX\_10\_EXP](../climits "cpp/types/climits")` |
### Example
Demonstrates the relationships of `max_exponent`, `max_exponent10`, and `max()` for the type `float`:
```
#include <iostream>
int main()
{
std::cout << "max() = " << std::numeric_limits<float>::max() << '\n'
<< "max_exponent10 = " << std::numeric_limits<float>::max_exponent10 << '\n'
<< std::hexfloat
<< "max() = " << std::numeric_limits<float>::max() << '\n'
<< "max_exponent = " << std::numeric_limits<float>::max_exponent << '\n';
}
```
Output:
```
max() = 3.40282e+38
max_exponent10 = 38
max() = 0x1.fffffep+127
max_exponent = 128
```
### See also
| | |
| --- | --- |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [min\_exponent10](min_exponent10 "cpp/types/numeric limits/min exponent10")
[static] | the smallest negative power of ten that is a valid normalized floating-point value (public static member constant) |
cpp std::numeric_limits<T>::is_signed std::numeric\_limits<T>::is\_signed
===================================
| | | |
| --- | --- | --- |
|
```
static const bool is_signed;
```
| | (until C++11) |
|
```
static constexpr bool is_signed;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_signed` is `true` for all signed arithmetic types `T` and `false` for the unsigned types. This constant is meaningful for all specializations.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_signed` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | implementation-defined |
| `signed char` | `true` |
| `unsigned char` | `false` |
| `wchar_t` | implementation-defined |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `true` |
| `unsigned short` | `false` |
| `int` | `true` |
| `unsigned int` | `false` |
| `long` | `true` |
| `unsigned long` | `false` |
| `long long` (C++11) | `true` |
| `unsigned long long` (C++11) | `false` |
| `float` | `true` |
| `double` | `true` |
| `long double` | `true` |
### Example
```
#include <iostream>
#include <iomanip>
#include <limits>
template <typename T> struct test {
test(const char* name, int w = 15) {
std::cout
<< std::left << std::setw(w)
<< (std::numeric_limits<T>::is_specialized ? name : "non-specialized")
<< " : "
<< (std::numeric_limits<T>::is_signed ? "" : "un") << "signed\n";
}
};
int main()
{
test<bool>{"bool"};
test<char>{"char"};
test<wchar_t>{"wchar_t"};
test<char16_t>{"char16_t"};
test<char32_t>{"char32_t"};
test<float>{"float"};
struct delusion{};
test<delusion>{"delusion"};
test<decltype(42)>{"decltype(42)"};
}
```
Possible output:
```
bool : unsigned
char : signed
wchar_t : signed
char16_t : unsigned
char32_t : unsigned
float : signed
non-specialized : unsigned
decltype(42) : signed
```
### See also
| | |
| --- | --- |
| [is\_signed](../is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
| [is\_integer](is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_exact](is_exact "cpp/types/numeric limits/is exact")
[static] | identifies exact types (public static member constant) |
| [is\_bounded](is_bounded "cpp/types/numeric limits/is bounded")
[static] | identifies types that represent a finite set of values (public static member constant) |
cpp std::numeric_limits<T>::signaling_NaN std::numeric\_limits<T>::signaling\_NaN
=======================================
| | | |
| --- | --- | --- |
|
```
static T signaling_NaN() throw();
```
| | (until C++11) |
|
```
static constexpr T signaling_NaN() noexcept;
```
| | (since C++11) |
Returns the special value "signaling [not-a-number](https://en.wikipedia.org/wiki/NaN "enwiki:NaN")", as represented by the floating-point type `T`. Only meaningful if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_signaling\_NaN == true`. In IEEE 754, the most common binary representation of floating-point numbers, any value with all bits of the exponent set and at least one bit of the fraction set represents a NaN. It is implementation-defined which values of the fraction represent quiet or signaling NaNs, and whether the sign bit is meaningful.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::signaling\_NaN()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | implementation-defined (may be `FLT_SNAN`) |
| `double` | implementation-defined (may be `DBL_SNAN`) |
| `long double` | implementation-defined (may be `LDBL_SNAN`) |
### Notes
A NaN never compares equal to itself. Copying a NaN is not required, by IEEE-754, to preserve its bit representation (sign and [payload](../../numeric/math/nan "cpp/numeric/math/nan")), though most implementation do.
When a signaling NaN is used as an argument to an arithmetic expression, the appropriate floating-point exception may be raised and the NaN is "quieted", that is, the expression returns a quiet NaN.
### Example
Demonstrates the use of a signaling NaN to raise a floating-point exception.
```
#include <iostream>
#include <limits>
#include <cfenv>
#pragma STDC_FENV_ACCESS on
void show_fe_exceptions()
{
int n = std::fetestexcept(FE_ALL_EXCEPT);
if(n & FE_INVALID) std::cout << "FE_INVALID is raised\n";
else if(n == 0) std::cout << "no exceptions are raised\n";
std::feclearexcept(FE_ALL_EXCEPT);
}
int main()
{
double snan = std::numeric_limits<double>::signaling_NaN();
std::cout << "After sNaN was obtained ";
show_fe_exceptions();
double qnan = snan * 2.0;
std::cout << "After sNaN was multiplied by 2 ";
show_fe_exceptions();
double qnan2 = qnan * 2.0;
std::cout << "After the quieted NaN was multiplied by 2 ";
show_fe_exceptions();
std::cout << "The result is " << qnan2 << '\n';
}
```
Output:
```
After sNaN was obtained no exceptions are raised
After sNaN was multiplied by 2 FE_INVALID is raised
After the quieted NaN was multiplied by 2 no exceptions are raised
The result is nan
```
### See also
| | |
| --- | --- |
| [has\_signaling\_NaN](has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant) |
| [quiet\_NaN](quiet_nan "cpp/types/numeric limits/quiet NaN")
[static] | returns a quiet NaN value of the given floating-point type (public static member function) |
| [isnan](../../numeric/math/isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
cpp std::numeric_limits<T>::min_exponent10 std::numeric\_limits<T>::min\_exponent10
========================================
| | | |
| --- | --- | --- |
|
```
static const int min_exponent10;
```
| | (until C++11) |
|
```
static constexpr int min_exponent10;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min\_exponent10` is the lowest negative number `n` such that \(\scriptsize 10^n\)10n
is a valid normalized value of the floating-point type `T`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min\_exponent10` |
| --- | --- |
| /\* non-specialized \*/ | `0` |
| `bool` | `0` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_MIN\_10\_EXP](../climits "cpp/types/climits")` |
| `double` | `[DBL\_MIN\_10\_EXP](../climits "cpp/types/climits")` |
| `long double` | `[LDBL\_MIN\_10\_EXP](../climits "cpp/types/climits")` |
### Example
Demonstrates the relationships of `min_exponent`, `min_exponent10`, `min`, and `radix` for the type `float`:
```
#include <iostream>
int main()
{
std::cout << "min() = " << std::numeric_limits<float>::min() << '\n'
<< "min_exponent10 = " << std::numeric_limits<float>::min_exponent10 << '\n'
<< std::hexfloat
<< "min() = " << std::numeric_limits<float>::min() << '\n'
<< "min_exponent = " << std::numeric_limits<float>::min_exponent << '\n';
}
```
Output:
```
min() = 1.17549e-38
min_exponent10 = -37
min() = 0x1p-126
min_exponent = -125
```
### See also
| | |
| --- | --- |
| [min\_exponent](min_exponent "cpp/types/numeric limits/min exponent")
[static] | one more than the smallest negative power of the radix that is a valid normalized floating-point value (public static member constant) |
| [max\_exponent](max_exponent "cpp/types/numeric limits/max exponent")
[static] | one more than the largest integer power of the radix that is a valid finite floating-point value (public static member constant) |
| [max\_exponent10](max_exponent10 "cpp/types/numeric limits/max exponent10")
[static] | the largest integer power of 10 that is a valid finite floating-point value (public static member constant) |
cpp std::numeric_limits<T>::traps std::numeric\_limits<T>::traps
==============================
| | | |
| --- | --- | --- |
|
```
static const bool traps;
```
| | (until C++11) |
|
```
static constexpr bool traps;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::traps` is `true` for all arithmetic types `T` that have at least one value that, if used as an argument to an arithmetic operation, will generate a [trap](https://en.wikipedia.org/wiki/Trap_(computing) "enwiki:Trap (computing)").
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::traps` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | usually `true` |
| `signed char` | usually `true` |
| `unsigned char` | usually `true` |
| `wchar_t` | usually `true` |
| `char8_t` (C++20) | usually `true` |
| `char16_t` (C++11) | usually `true` |
| `char32_t` (C++11) | usually `true` |
| `short` | usually `true` |
| `unsigned short` | usually `true` |
| `int` | usually `true` |
| `unsigned int` | usually `true` |
| `long` | usually `true` |
| `unsigned long` | usually `true` |
| `long long` (C++11) | usually `true` |
| `unsigned long long` (C++11) | usually `true` |
| `float` | usually `false` |
| `double` | usually `false` |
| `long double` | usually `false` |
### Notes
On most platforms integer division by zero always traps, and `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::traps` is `true` for all integer types that support the value 0. The exception is the type `bool`: even though division by `false` traps due to integral promotion from `bool` to `int`, it is the zero-valued `int` that traps. Zero is not a value of type `bool`.
On most platforms, floating-point exceptions may be turned on and off at run time (e.g. `feenableexcept()` on Linux or `_controlfp` on Windows), in which case the value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::traps` for floating-point types reflects the state of floating-point trapping facility at the time of program startup, which is `false` on most modern systems. An exception would be a [DEC Alpha](https://en.wikipedia.org/wiki/DEC_Alpha "enwiki:DEC Alpha") program, where it is `true` if compiled without `-ieee`.
### See also
| |
| --- |
| [Floating-point environment](../../numeric/fenv "cpp/numeric/fenv") |
| [tinyness\_before](tinyness_before "cpp/types/numeric limits/tinyness before")
[static] | identifies floating-point types that detect tinyness before rounding (public static member constant) |
| [has\_denorm\_loss](has_denorm_loss "cpp/types/numeric limits/has denorm loss")
[static] | identifies the floating-point types that detect loss of precision as denormalization loss rather than inexact result (public static member constant) |
cpp std::numeric_limits<T>::denorm_min std::numeric\_limits<T>::denorm\_min
====================================
| | | |
| --- | --- | --- |
|
```
static T denorm_min() throw();
```
| | (until C++11) |
|
```
static constexpr T denorm_min() noexcept;
```
| | (since C++11) |
Returns the minimum positive [subnormal value](https://en.wikipedia.org/wiki/Denormal_number "enwiki:Denormal number") of the type `T`, if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_denorm != [std::denorm\_absent](http://en.cppreference.com/w/cpp/types/numeric_limits/float_denorm_style)`, otherwise returns `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()` for floating point types and `T()` for all other types. Only meaningful for floating-point types.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::denorm\_min()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | `[FLT\_TRUE\_MIN](../climits "cpp/types/climits")` (\(\scriptsize 2^{-149}\)2-149 if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<float>::is\_iec559` is `true`) |
| `double` | `[DBL\_TRUE\_MIN](../climits "cpp/types/climits")` (\(\scriptsize 2^{-1074}\)2-1074 if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<double>::is\_iec559` is `true`) |
| `long double` | `[LDBL\_TRUE\_MIN](../climits "cpp/types/climits")` |
### Example
Demonstates the underlying bit structure of the `denorm_min()` and prints the values.
```
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
int main()
{
// the smallest subnormal value has sign bit = 0, exponent = 0
// and only the least significant bit of the fraction is 1
std::uint32_t denorm_bits = 0x0001;
float denorm_float;
std::memcpy(&denorm_float, &denorm_bits, sizeof(float));
assert(denorm_float == std::numeric_limits<float>::denorm_min());
std::cout << "float\tmin()\t\tdenorm_min()\n";
std::cout << "\t" << std::numeric_limits<float>::min() << '\t';
std::cout << std::numeric_limits<float>::denorm_min() << '\n';
std::cout << "double\tmin()\t\tdenorm_min()\n";
std::cout << "\t" << std::numeric_limits<double>::min() << '\t';
std::cout << std::numeric_limits<double>::denorm_min() << '\n';
}
```
Possible output:
```
float min() denorm_min()
1.17549e-38 1.4013e-45
double min() denorm_min()
2.22507e-308 4.94066e-324
```
### See also
| | |
| --- | --- |
| [min](min "cpp/types/numeric limits/min")
[static] | returns the smallest finite value of the given type (public static member function) |
| [has\_denorm](has_denorm "cpp/types/numeric limits/has denorm")
[static] | identifies the denormalization style used by the floating-point type (public static member constant) |
| [lowest](lowest "cpp/types/numeric limits/lowest")
[static] (C++11) | returns the lowest finite value of the given type (public static member function) |
| programming_docs |
cpp std::numeric_limits<T>::has_signaling_NaN std::numeric\_limits<T>::has\_signaling\_NaN
============================================
| | | |
| --- | --- | --- |
|
```
static const bool has_signaling_NaN;
```
| | (until C++11) |
|
```
static constexpr bool has_signaling_NaN;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_signaling\_NaN` is `true` for all types `T` capable of representing the special value "Signaling [Not-A-Number](https://en.wikipedia.org/wiki/NaN "enwiki:NaN")". This constant is meaningful for all floating-point types and is guaranteed to be `true` if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559 == true`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_signaling\_NaN` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | usually `true` |
| `double` | usually `true` |
| `long double` | usually `true` |
### See also
| | |
| --- | --- |
| [quiet\_NaN](quiet_nan "cpp/types/numeric limits/quiet NaN")
[static] | returns a quiet NaN value of the given floating-point type (public static member function) |
| [has\_infinity](has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant) |
| [has\_quiet\_NaN](has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant) |
cpp std::numeric_limits<T>::is_iec559 std::numeric\_limits<T>::is\_iec559
===================================
| | | |
| --- | --- | --- |
|
```
static const bool is_iec559;
```
| | (until C++11) |
|
```
static constexpr bool is_iec559;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559` is `true` for all floating-point types `T` which fulfill the requirements of IEC 559 ([IEEE 754](https://en.wikipedia.org/wiki/IEEE_754-2008 "enwiki:IEEE 754-2008")) standard. If `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559` is `true`, then `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_infinity`, `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_quiet\_NaN`, and `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_signaling\_NaN` are also `true`.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_iec559` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `false` |
| `char` | `false` |
| `signed char` | `false` |
| `unsigned char` | `false` |
| `wchar_t` | `false` |
| `char8_t` (C++20) | `false` |
| `char16_t` (C++11) | `false` |
| `char32_t` (C++11) | `false` |
| `short` | `false` |
| `unsigned short` | `false` |
| `int` | `false` |
| `unsigned int` | `false` |
| `long` | `false` |
| `unsigned long` | `false` |
| `long long` (C++11) | `false` |
| `unsigned long long` (C++11) | `false` |
| `float` | usually `true` |
| `double` | usually `true` |
| `long double` | usually `true` |
### See also
| | |
| --- | --- |
| [has\_infinity](has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant) |
| [has\_quiet\_NaN](has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant) |
| [has\_signaling\_NaN](has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant) |
cpp std::numeric_limits<T>::round_style std::numeric\_limits<T>::round\_style
=====================================
| | | |
| --- | --- | --- |
|
```
static const std::float_round_style round_style;
```
| | (until C++11) |
|
```
static constexpr std::float_round_style round_style;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::round\_style` identifies the rounding style used by the floating-point type `T` whenever a value that is not one of the exactly repesentable values of `T` is stored in an object of that type.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::round\_style` |
| --- | --- |
| /\* non-specialized \*/ | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `bool` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `char` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `signed char` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `unsigned char` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `wchar_t` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `char8_t` (C++20) | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `char16_t` (C++11) | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `char32_t` (C++11) | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `short` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `unsigned short` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `int` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `unsigned int` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `long` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `unsigned long` | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `long long` (C++11) | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `unsigned long long` (C++11) | `[std::round\_toward\_zero](float_round_style "cpp/types/numeric limits/float round style")` |
| `float` | usually `[std::round\_to\_nearest](float_round_style "cpp/types/numeric limits/float round style")` |
| `double` | usually `[std::round\_to\_nearest](float_round_style "cpp/types/numeric limits/float round style")` |
| `long double` | usually `[std::round\_to\_nearest](float_round_style "cpp/types/numeric limits/float round style")` |
### Notes
These values are constants, and do not reflect the changes to the rounding made by `[std::fesetround](../../numeric/fenv/feround "cpp/numeric/fenv/feround")`. The changed values may be obtained from `[FLT\_ROUNDS](../climits/flt_rounds "cpp/types/climits/FLT ROUNDS")` or `[std::fegetround](../../numeric/fenv/feround "cpp/numeric/fenv/feround")`.
### Example
The decimal value `0.1` cannot be represented by a binary floating-point type. When stored in an IEEE-754 `double`, it falls between 0x1.9999999999999\*2-4
and 0x1.999999999999a\*2-4
. Rounding to nearest representable value results in 0x1.999999999999a\*2-4
.
Similarly, the decimal value 0.3, which is between 0x1.3333333333333\*2-2
and 0x1.3333333333334\*2-2
is rounded to nearest and is stored as 0x1.3333333333333\*2-2
.
```
#include <iostream>
#include <limits>
int main()
{
std::cout << std::hexfloat << "The decimal 0.1 is stored in a double as "
<< 0.1 << '\n'
<< "The decimal 0.3 is stored in a double as "
<< 0.3 << '\n'
<< "The rounding style is " << std::numeric_limits<double>::round_style << '\n';
}
```
Output:
```
The decimal 0.1 is stored in a double as 0x1.999999999999ap-4
The decimal 0.3 is stored in a double as 0x1.3333333333333p-2
The rounding style is 1
```
### See also
| | |
| --- | --- |
| [float\_round\_style](float_round_style "cpp/types/numeric limits/float round style") | indicates floating-point rounding modes (enum) |
cpp std::numeric_limits<T>::is_exact std::numeric\_limits<T>::is\_exact
==================================
| | | |
| --- | --- | --- |
|
```
static const bool is_exact;
```
| | (until C++11) |
|
```
static constexpr bool is_exact;
```
| | (since C++11) |
The value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_exact` is `true` for all arithmetic types `T` that use exact representation.
### Standard specializations
| `T` | value of `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_exact` |
| --- | --- |
| /\* non-specialized \*/ | `false` |
| `bool` | `true` |
| `char` | `true` |
| `signed char` | `true` |
| `unsigned char` | `true` |
| `wchar_t` | `true` |
| `char8_t` (C++20) | `true` |
| `char16_t` (C++11) | `true` |
| `char32_t` (C++11) | `true` |
| `short` | `true` |
| `unsigned short` | `true` |
| `int` | `true` |
| `unsigned int` | `true` |
| `long` | `true` |
| `unsigned long` | `true` |
| `long long` (C++11) | `true` |
| `unsigned long long` (C++11) | `true` |
| `float` | `false` |
| `double` | `false` |
| `long double` | `false` |
### Notes
While all fundamental types `T` for which `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::is\_exact==true` are integer types, a library may define exact types that aren't integers, e.g. a rational arithmetics type representing fractions.
### See also
| | |
| --- | --- |
| [is\_integer](is_integer "cpp/types/numeric limits/is integer")
[static] | identifies integer types (public static member constant) |
| [is\_signed](is_signed "cpp/types/numeric limits/is signed")
[static] | identifies signed types (public static member constant) |
| [is\_bounded](is_bounded "cpp/types/numeric limits/is bounded")
[static] | identifies types that represent a finite set of values (public static member constant) |
cpp std::numeric_limits<T>::quiet_NaN std::numeric\_limits<T>::quiet\_NaN
===================================
| | | |
| --- | --- | --- |
|
```
static T quiet_NaN() throw();
```
| | (until C++11) |
|
```
static constexpr T quiet_NaN() noexcept;
```
| | (since C++11) |
Returns the special value "quiet [not-a-number](https://en.wikipedia.org/wiki/NaN "enwiki:NaN")", as represented by the floating-point type `T`. Only meaningful if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::has\_quiet\_NaN == true`. In IEEE 754, the most common binary representation of floating-point numbers, any value with all bits of the exponent set and at least one bit of the fraction set represents a NaN. It is implementation-defined which values of the fraction represent quiet or signaling NaNs, and whether the sign bit is meaningful.
### Return value
| `T` | `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::quiet\_NaN()` |
| --- | --- |
| /\* non-specialized \*/ | `T()` |
| `bool` | `false` |
| `char` | `0` |
| `signed char` | `0` |
| `unsigned char` | `0` |
| `wchar_t` | `0` |
| `char8_t` (C++20) | `0` |
| `char16_t` (C++11) | `0` |
| `char32_t` (C++11) | `0` |
| `short` | `0` |
| `unsigned short` | `0` |
| `int` | `0` |
| `unsigned int` | `0` |
| `long` | `0` |
| `unsigned long` | `0` |
| `long long` (C++11) | `0` |
| `unsigned long long` (C++11) | `0` |
| `float` | implementation-defined (may be `[NAN](../../numeric/math/nan "cpp/numeric/math/NAN")`) |
| `double` | implementation-defined |
| `long double` | implementation-defined |
### Notes
A NaN never compares equal to itself. Copying a NaN may not preserve its bit representation.
### Example
Several ways to generate a NaN (the output string is compiler-specific).
```
#include <iostream>
#include <limits>
#include <cmath>
int main()
{
std::cout << std::numeric_limits<double>::quiet_NaN() << ' ' // nan
<< std::numeric_limits<double>::signaling_NaN() << ' ' // nan
<< std::acos(2) << ' ' // nan
<< std::tgamma(-1) << ' ' // nan
<< std::log(-1) << ' ' // nan
<< std::sqrt(-1) << ' ' // -nan
<< 0 / 0.0 << '\n'; // -nan
std::cout << "NaN == NaN? " << std::boolalpha
<< ( std::numeric_limits<double>::quiet_NaN() ==
std::numeric_limits<double>::quiet_NaN() ) << '\n';
}
```
Possible output:
```
nan nan nan nan nan -nan -nan
NaN == NaN? false
```
### See also
| | |
| --- | --- |
| [has\_quiet\_NaN](has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant) |
| [signaling\_NaN](signaling_nan "cpp/types/numeric limits/signaling NaN")
[static] | returns a signaling NaN value of the given floating-point type (public static member function) |
| [nannanfnanl](../../numeric/math/nan "cpp/numeric/math/nan")
(C++11)(C++11)(C++11) | not-a-number (NaN) (function) |
| [isnan](../../numeric/math/isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
cpp std::type_info::hash_code std::type\_info::hash\_code
===========================
| | | |
| --- | --- | --- |
|
```
std::size_t hash_code() const noexcept;
```
| | (since C++11) |
Returns an unspecified value (here denoted by *hash code*) such that for all `[std::type\_info](../type_info "cpp/types/type info")` objects referring to the same type, their *hash code* is the same.
No other guarantees are given: `[std::type\_info](../type_info "cpp/types/type info")` objects referring to different types may have the same *hash code* (although the standard recommends that implementations avoid this as much as possible), and *hash code* for the same type can change between invocations of the same program.
### Parameters
(none).
### Return value
A value that is identical for all `[std::type\_info](../type_info "cpp/types/type info")` objects referring to the same type.
### Example
The following program is an example of an efficient type-value mapping without using `[std::type\_index](../type_index "cpp/types/type index")`.
```
#include <iostream>
#include <typeinfo>
#include <unordered_map>
#include <string>
#include <functional>
#include <memory>
struct A {
virtual ~A() {}
};
struct B : A {};
struct C : A {};
using TypeInfoRef = std::reference_wrapper<const std::type_info>;
struct Hasher {
std::size_t operator()(TypeInfoRef code) const
{
return code.get().hash_code();
}
};
struct EqualTo {
bool operator()(TypeInfoRef lhs, TypeInfoRef rhs) const
{
return lhs.get() == rhs.get();
}
};
int main()
{
std::unordered_map<TypeInfoRef, std::string, Hasher, EqualTo> type_names;
type_names[typeid(int)] = "int";
type_names[typeid(double)] = "double";
type_names[typeid(A)] = "A";
type_names[typeid(B)] = "B";
type_names[typeid(C)] = "C";
int i;
double d;
A a;
// note that we're storing pointer to type A
std::unique_ptr<A> b(new B);
std::unique_ptr<A> c(new C);
std::cout << "i is " << type_names[typeid(i)] << '\n';
std::cout << "d is " << type_names[typeid(d)] << '\n';
std::cout << "a is " << type_names[typeid(a)] << '\n';
std::cout << "*b is " << type_names[typeid(*b)] << '\n';
std::cout << "*c is " << type_names[typeid(*c)] << '\n';
}
```
Output:
```
i is int
d is double
a is A
*b is B
*c is C
```
### See also
| | |
| --- | --- |
| [operator==operator!=](operator_cmp "cpp/types/type info/operator cmp")
(removed in C++20) | checks whether the objects refer to the same type (public member function) |
| [name](name "cpp/types/type info/name") | implementation defined name of the type (public member function) |
cpp std::type_info::name std::type\_info::name
=====================
| | | |
| --- | --- | --- |
|
```
const char* name() const;
```
| | (until C++11) |
|
```
const char* name() const noexcept;
```
| | (since C++11) |
Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.
### Parameters
(none).
### Return value
null-terminated character string containing the name of the type.
### Notes
The lifetime of the array pointed to by the returned pointer is not specified, but in practice it persist as long as the RTTI data structure for the given type exists, which has application lifetime unless loaded from a dynamic library (that can be unloaded).
Some implementations (such as MSVC, IBM, Oracle) produce a human-readable type name. Others, most notably gcc and clang, return the mangled name, which is specified by the [Itanium C++ ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#typeid). The mangled name can be converted to human-readable form using implementation-specific API such as [`abi::__cxa_demangle`](https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html) directly or through [`boost::core::demangle`](http://www.boost.org/doc/libs/release/libs/core/doc/html/core/demangle.html). It can also be piped through the commandline utility `c++filt -t`.
### Example
```
#include <boost/core/demangle.hpp>
#include <iostream>
#include <typeinfo>
struct Base { virtual ~Base() = default; };
struct Derived : Base {};
int main() {
Base b1;
Derived d1;
const Base *pb = &b1;
std::cout << typeid(*pb).name() << '\n';
pb = &d1;
std::cout << typeid(*pb).name() << '\n';
std::string real_name = boost::core::demangle(typeid(pb).name());
std::cout << typeid(pb).name() << " => " << real_name << '\n';
}
```
Possible output:
```
// GCC/Clang:
4Base
7Derived
PK4Base => Base const*
// MSVC:
struct Base
struct Derived
struct Base const * __ptr64 => struct Base const * __ptr64
```
### See also
| | |
| --- | --- |
| [hash\_code](hash_code "cpp/types/type info/hash code")
(C++11) | returns a value which is identical for the same types (public member function) |
cpp std::type_info::operator==, std::type_info::operator!= std::type\_info::operator==, std::type\_info::operator!=
========================================================
| | | |
| --- | --- | --- |
|
```
bool operator==( const type_info& rhs ) const;
```
| | (until C++11) |
|
```
bool operator==( const type_info& rhs ) const noexcept;
```
| | (since C++11) (until C++23) |
|
```
constexpr bool operator==( const type_info& rhs ) const noexcept;
```
| | (since C++23) |
|
```
bool operator!=( const type_info& rhs ) const;
```
| | (until C++11) |
|
```
bool operator!=( const type_info& rhs ) const noexcept;
```
| | (since C++11) (until C++20) |
Checks if the objects refer to the same types.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| rhs | - | another type information object to compare to |
### Return value
`true` if the comparison operation holds true, `false` otherwise.
### Notes
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_constexpr_typeinfo`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
```
#include <iostream>
#include <typeinfo>
#include <string>
#include <utility>
class person
{
public:
person(std::string n) : name_(std::move(n)) {}
virtual const std::string& name() const{ return name_; }
private:
std::string name_;
};
class employee : public person
{
public:
employee(std::string n, std::string p)
: person(std::move(n)), profession_(std::move(p)) {}
const std::string& profession() const { return profession_; }
private:
std::string profession_;
};
void print_info(const person& p)
{
if(typeid(person) == typeid(p))
{
std::cout << p.name() << " is not an employee\n";
}
else if(typeid(employee) == typeid(p))
{
std::cout << p.name() << " is an employee ";
auto& emp = dynamic_cast<const employee&>(p);
std::cout << "who works in " << emp.profession() << '\n';
}
}
int main()
{
print_info(employee{"Paul","Economics"});
print_info(person{"Kate"});
if constexpr (typeid(employee) != typeid(person)) // C++23
{
std::cout << "class `employee` != class `person`\n";
}
}
```
Output:
```
Paul is an employee who works in Economics
Kate is not an employee
class `employee` != class `person`
```
### See also
| | |
| --- | --- |
| [before](before "cpp/types/type info/before") | checks whether the referred type precedes referred type of another `type_info` object in the implementation defined order, i.e. orders the referred types (public member function) |
| programming_docs |
cpp std::type_info::~type_info std::type\_info::~type\_info
============================
| | | |
| --- | --- | --- |
|
```
virtual ~type_info();
```
| | |
Destructs an object of type `[std::type\_info](../type_info "cpp/types/type info")`. This destructor is public virtual, making the `[std::type\_info](../type_info "cpp/types/type info")` a polymorphic class.
### Notes
The dynamic type of a `[std::type\_info](../type_info "cpp/types/type info")` subobject may be examined by the [`typeid`](../../language/typeid "cpp/language/typeid") operator.
It is unspecified whether the implementation calls this destructor for any `[std::type\_info](../type_info "cpp/types/type info")` object at the end of the program.
cpp std::type_info::before std::type\_info::before
=======================
| | | |
| --- | --- | --- |
|
```
bool before( const type_info& rhs ) const;
```
| | (until C++11) |
|
```
bool before( const type_info& rhs ) const noexcept;
```
| | (since C++11) |
Returns `true` if the type of this `type_info` precedes the type of `rhs` in the implementation's collation order. No guarantees are given; in particular, the collation order can change between the invocations of the same program.
### Parameters
| | | |
| --- | --- | --- |
| rhs | - | another type information object to compare to |
### Return value
`true` if the type of this `type_info` precedes the type of `rhs` in the implementation's collation order.
### Example
```
#include <iostream>
#include <typeinfo>
int main()
{
if(typeid(int).before(typeid(char)))
std::cout << "int goes before char in this implementation.\n";
else
std::cout << "char goes before int in this implementation.\n";
}
```
Possible output:
```
char goes before int in this implementation.
```
### See also
| | |
| --- | --- |
| [operator==operator!=](operator_cmp "cpp/types/type info/operator cmp")
(removed in C++20) | checks whether the objects refer to the same type (public member function) |
cpp FLT_EVAL_METHOD FLT\_EVAL\_METHOD
=================
| Defined in header `[<cfloat>](../../header/cfloat "cpp/header/cfloat")` | | |
| --- | --- | --- |
|
```
#define FLT_EVAL_METHOD /* implementation defined */
```
| | (since C++11) |
Specifies the precision in which all floating-point arithmetic operations other than assignment and cast are done.
| Value | Explanation |
| --- | --- |
| negative values except `-1` | implementation-defined behavior |
| `-1` | the default precision is not known |
| `0` | all operations and constants evaluate in the range and precision of the type used. Additionally, `float_t` and `double_t` are equivalent to `float` and `double` respectively |
| `1` | all operations and constants evaluate in the range and precision of `double`. Additionally, both `float_t` and `double_t` are equivalent to `double` |
| `2` | all operations and constants evaluate in the range and precision of `long double`. Additionally, both `float_t` and `double_t` are equivalent to `long double` |
### Notes
Regardless of the value of `FLT_EVAL_METHOD`, any floating-point expression may be *contracted*, that is, calculated as if all intermediate results have infinite range and precision (unless [#pragma](../../preprocessor/impl "cpp/preprocessor/impl") `STDC FP_CONTRACT` is off).
Cast and assignment strip away any extraneous range and precision: this models the action of storing a value from an extended-precision FPU register into a standard-sized memory location.
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/types/limits/FLT_EVAL_METHOD "c/types/limits/FLT EVAL METHOD") for `FLT_EVAL_METHOD` |
cpp FLT_ROUNDS FLT\_ROUNDS
===========
| Defined in header `[<cfloat>](../../header/cfloat "cpp/header/cfloat")` | | |
| --- | --- | --- |
|
```
#define FLT_ROUNDS /* implementation defined */
```
| | |
Specifies the current rounding direction of floating-point arithmetic operations.
| Value | Explanation |
| --- | --- |
| `-1` | the default rounding direction is not known |
| `0` | toward zero; same meaning as `[FE\_TOWARDZERO](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")` |
| `1` | to nearest; same meaning as `[FE\_TONEAREST](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")` |
| `2` | towards positive infinity; same meaning as `[FE\_UPWARD](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")` |
| `3` | towards negative infinity; same meaning as `[FE\_DOWNWARD](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")` |
| other values | implementation-defined behavior |
### Notes
The rounding mode can be changed with `[std::fesetround](../../numeric/fenv/feround "cpp/numeric/fenv/feround")` and `FLT_ROUNDS` reflects that change.
The possible values of FLT\_ROUNDS match the possible values of `[std::float\_round\_style](../numeric_limits/float_round_style "cpp/types/numeric limits/float round style")`, returned by `[std::numeric\_limits::round\_style](../numeric_limits/round_style "cpp/types/numeric limits/round style")`.
### See also
| | |
| --- | --- |
| [float\_round\_style](../numeric_limits/float_round_style "cpp/types/numeric limits/float round style") | indicates floating-point rounding modes (enum) |
| [fegetroundfesetround](../../numeric/fenv/feround "cpp/numeric/fenv/feround")
(C++11)(C++11) | gets or sets rounding direction (function) |
| [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](../../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")
(C++11) | floating-point rounding direction (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/types/limits/FLT_ROUNDS "c/types/limits/FLT ROUNDS") for `FLT_ROUNDS` |
cpp std::type_index::hash_code std::type\_index::hash\_code
============================
| | | |
| --- | --- | --- |
|
```
std::size_t hash_code() const noexcept;
```
| | (since C++11) |
Returns the hash code of the associated `[std::type\_info](../type_info "cpp/types/type info")` object. Equivalent to calling [`type_info::hash_code`](../type_info/hash_code "cpp/types/type info/hash code") directly.
### Parameters
(none).
### Return value
The hash code of the associated `[std::type\_info](../type_info "cpp/types/type info")` object.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2144](https://cplusplus.github.io/LWG/issue2144) | C++11 | `type_index::hash_code` was not required to be noexcept | required |
### See also
| | |
| --- | --- |
| [std::hash<std::type\_index>](hash "cpp/types/type index/hash")
(C++11) | hash support for `[std::type\_index](../type_index "cpp/types/type index")` (class template specialization) |
cpp std::type_index::name std::type\_index::name
======================
| | | |
| --- | --- | --- |
|
```
const char* name() const noexcept;
```
| | (since C++11) |
Returns the name of the associated `[std::type\_info](../type_info "cpp/types/type info")` object. Equivalent to calling `[std::type\_info::name()](../type_info/name "cpp/types/type info/name")` directly.
### Parameters
(none).
### Return value
The name of the associated `[std::type\_info](../type_info "cpp/types/type info")` object.
### Example
```
#include <iostream>
#include <typeindex>
int main() {
std::cout << std::type_index(typeid(std::cout)).name();
}
```
Possible output:
```
NSt3__113basic_ostreamIcNS_11char_traitsIcEEEE
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2144](https://cplusplus.github.io/LWG/issue2144) | C++11 | `type_index::name` was not required to be noexcept | required |
cpp std::type_index::operator==,!=,<,<=,>,>=,<=> std::type\_index::operator==,!=,<,<=,>,>=,<=>
=============================================
| | | |
| --- | --- | --- |
|
```
bool operator==( const type_index& rhs ) const noexcept;
```
| (1) | (since C++11) |
|
```
bool operator!=( const type_index& rhs ) const noexcept;
```
| (2) | (since C++11) (until C++20) |
|
```
bool operator<( const type_index& rhs ) const noexcept;
```
| (3) | (since C++11) |
|
```
bool operator<=( const type_index& rhs ) const noexcept;
```
| (4) | (since C++11) |
|
```
bool operator>( const type_index& rhs ) const noexcept;
```
| (5) | (since C++11) |
|
```
bool operator>=( const type_index& rhs ) const noexcept;
```
| (6) | (since C++11) |
|
```
std::strong_ordering operator<=>( const type_index& rhs ) const noexcept;
```
| (7) | (since C++20) |
Compares the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects.
1-2) Checks whether the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects refer to the same type.
3-7) Compares the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects as defined by an implementation-defined ordering. The comparison is done by [`type_info::before`](../type_info/before "cpp/types/type info/before").
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| rhs | - | another `type_index` object to compare to |
### Return value
1) `true` if the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects refer to the same type, `false` otherwise
2) `true` if the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects refer not to the same type, `false` otherwise
3-6) `true` if the types referred by the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects are ordered by corresponding order, `false` otherwise.
7) `std::strong_ordering::equal` if the underlying `[std::type\_info](../type_info "cpp/types/type info")` objects refer to the same type, otherwise `std::strong_ordering::less` if `*this`'s underlying `[std::type\_info](../type_info "cpp/types/type info")` object precedes `rhs`'s in the implementation-defined ordering, otherwise `std::strong_ordering::greater`.
cpp std::type_index::type_index std::type\_index::type\_index
=============================
| | | |
| --- | --- | --- |
|
```
type_index( const std::type_info& info ) noexcept;
```
| | (since C++11) |
Constructs the type index from `[std::type\_info](../type_info "cpp/types/type info")` object.
### Parameters
| | | |
| --- | --- | --- |
| info | - | type information object |
### Example
cpp std::use_facet std::use\_facet
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class Facet >
const Facet& use_facet( const std::locale& loc );
```
| | |
Obtains a reference to a facet implemented by `loc`. `Facet` should be a facet class whose definition contains the public static member `id`.
### Parameters
| | | |
| --- | --- | --- |
| loc | - | the locale object to query |
### Return value
Returns a reference to the facet. The reference returned by this function is valid as long as any `[std::locale](locale "cpp/locale/locale")` object refers to that facet.
### Exceptions
`[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")` if `[std::has\_facet](http://en.cppreference.com/w/cpp/locale/has_facet)<Facet>(loc) == false`.
### Example
Display the 3-letter currency name used by the user's preferred locale.
```
#include <iostream>
#include <locale>
int main()
{
for (const char* name: {"en_US.UTF-8", "de_DE.UTF-8", "en_GB.UTF-8"})
{
std::locale loc = std::locale(name); // user's preferred locale
std::cout << "Your currency string is "
<< std::use_facet<std::moneypunct<char, true>>(loc).
curr_symbol() << '\n';
}
}
```
Output:
```
Your currency string is USD
Your currency string is EUR
Your currency string is GBP
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 31](https://cplusplus.github.io/LWG/issue31) | C++98 | the returned reference remained usableas long as the locale value itself exists | the returned reference remains usable aslong as some locale object refers to that facet |
| [LWG 38](https://cplusplus.github.io/LWG/issue38) | C++98 | there was no requirement on `Facet` | requirement added |
### See also
| | |
| --- | --- |
| [locale](locale "cpp/locale/locale") | set of polymorphic facets that encapsulate cultural differences (class) |
| [has\_facet](has_facet "cpp/locale/has facet") | checks if a locale implements a specific facet (function template) |
cpp std::isxdigit(std::locale) std::isxdigit(std::locale)
==========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isxdigit( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as a hexadecimal digit by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as a hexadecimal digit, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isxdigit( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::xdigit, ch);
}
```
|
### Example
### See also
| | |
| --- | --- |
| [isxdigit](../string/byte/isxdigit "cpp/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) |
| [iswxdigit](../string/wide/iswxdigit "cpp/string/wide/iswxdigit") | checks if a character is a hexadecimal character (function) |
cpp std::codecvt_mode std::codecvt\_mode
==================
| Defined in header `[<codecvt>](../header/codecvt "cpp/header/codecvt")` | | |
| --- | --- | --- |
|
```
enum codecvt_mode {
consume_header = 4,
generate_header = 2,
little_endian = 1
};
```
| | (since C++11) (deprecated in C++17) |
The facets `[std::codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")`, `[std::codecvt\_utf16](codecvt_utf16 "cpp/locale/codecvt utf16")`, and `[std::codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")` accept an optional value of type `std::codecvt_mode` as a template argument, which specifies optional features of the unicode string conversion.
### Constants
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| Value | Meaning |
| `little_endian` | assume the input is in little-endian byte order (applies to UTF-16 input only, the default is big-endian) |
| `consume_header` | consume the byte order mark, if present at the start of input sequence, and (in case of UTF-16), rely on the byte order it specifies for decoding the rest of the input |
| `generate_header` | output the byte order mark at the start of the output sequence |
The recognized byte order marks are:
| | |
| --- | --- |
| `0xfe 0xff` | UTF-16 big-endian |
| `0xff 0xfe` | UTF-16 little-endian |
| `0xef 0xbb 0xbf` | UTF-8 (no effect on endianness) |
If `std::consume_header` is not selected when reading a file beginning with byte order mark, the Unicode character U+FEFF (Zero width non-breaking space) will be read as the first character of the string content.
### Example
The following example demonstrates consuming the UTF-8 BOM.
```
#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main()
{
// UTF-8 data with BOM
std::ofstream("text.txt") << u8"\ufeffz\u6c34\U0001d10b";
// read the UTF8 file, skipping the BOM
std::wifstream fin("text.txt");
fin.imbue(std::locale(fin.getloc(),
new std::codecvt_utf8<wchar_t, 0x10ffff, std::consume_header>));
for (wchar_t c; fin.get(c); )
std::cout << std::hex << std::showbase << c << '\n';
}
```
Output:
```
0x7a
0x6c34
0x1d10b
```
### See also
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf16](codecvt_utf16 "cpp/locale/codecvt utf16")
(C++11)(deprecated in C++17) | converts between UTF-16 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
cpp std::toupper(std::locale) std::toupper(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
charT toupper( charT ch, const locale& loc );
```
| | |
Converts the character `ch` to uppercase if possible, using the conversion rules specified by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns the uppercase form of `ch` if one is listed in the locale, otherwise returns `ch` unchanged.
### Notes
Only 1:1 character mapping can be performed by this function, e.g. the uppercase form of 'ß' is (with some exceptions) the two-character string "SS", which cannot be obtained by `std::toupper`.
### Possible implementation
| |
| --- |
|
```
template< class charT >
charT toupper( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).toupper(ch);
}
```
|
### Example
```
#include <iostream>
#include <cwctype>
#include <locale>
int main()
{
wchar_t c = L'\u017f'; // Latin small letter Long S ('ſ')
std::cout << std::hex << std::showbase;
std::cout << "in the default locale, toupper(" << (std::wint_t)c << ") = "
<< std::toupper(c, std::locale()) << '\n';
std::cout << "in Unicode locale, toupper(" << (std::wint_t)c << ") = "
<< std::toupper(c, std::locale("en_US.utf8")) << '\n';
}
```
Output:
```
in the default locale, toupper(0x17f) = 0x17f
in Unicode locale, toupper(0x17f) = 0x53
```
### See also
| | |
| --- | --- |
| [tolower(std::locale)](tolower "cpp/locale/tolower") | converts a character to lowercase using the ctype facet of a locale (function template) |
| [toupper](../string/byte/toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) |
| [towupper](../string/wide/towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) |
cpp std::money_put std::money\_put
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class OutputIt = std::ostreambuf_iterator<CharT>
> class money_put;
```
| | |
Class `std::money_put` encapsulates the rules for formatting monetary values as strings. The standard I/O manipulator `[std::put\_money](../io/manip/put_money "cpp/io/manip/put money")` uses the `std::money_put` facet of the I/O stream's locale.
![std-money put-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::money_put<char>` | creates narrow string representations of monetary values |
| `std::money_put<wchar_t>` | creates wide string representations of monetary values |
| `std::money_put<char, OutputIt>` | creates narrow string representations of monetary values using custom output iterator |
| `std::money_put<wchar_t, OutputIt>` | creates wide string representations of monetary values using custom output iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `std::basic_string<CharT>` |
| `iter_type` | `OutputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](money_put/money_put "cpp/locale/money put/money put") | constructs a new money\_put facet (public member function) |
| [(destructor)](money_put/~money_put "cpp/locale/money put/~money put") | destructs a money\_put facet (protected member function) |
| [put](money_put/put "cpp/locale/money put/put") | invokes `do_put` (public member function) |
### Protected member functions
| | |
| --- | --- |
| [do\_put](money_put/put "cpp/locale/money put/put")
[virtual] | formats a monetary value and writes to output stream (virtual protected member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Example
```
#include <iostream>
#include <locale>
#include <iomanip>
#include <iterator>
int main()
{
// using the IO manipulator
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "american locale: "
<< std::showbase << std::put_money(12345678.9)<< '\n';
// using the facet directly
std::cout.imbue(std::locale("de_DE.UTF-8"));
std::cout << "german locale: " ;
auto& f = std::use_facet<std::money_put<char>>(std::cout.getloc());
f.put({std::cout}, false, std::cout, std::cout.fill(), 12345678.9 );
std::cout << '\n';
}
```
Output:
```
american locale: $123,456.79
german locale: 123.456,79 €
```
### See also
| | |
| --- | --- |
| [moneypunct](moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](money_get "cpp/locale/money get")` and `std::money_put` (class template) |
| [money\_get](money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) |
| [put\_money](../io/manip/put_money "cpp/io/manip/put money")
(C++11) | formats and outputs a monetary value (function template) |
| programming_docs |
cpp std::moneypunct std::moneypunct
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT, bool International = false >
class moneypunct;
```
| | |
The facet `std::moneypunct` encapsulates monetary value format preferences. Stream I/O manipulators `[std::get\_money](../io/manip/get_money "cpp/io/manip/get money")` and `[std::put\_money](../io/manip/put_money "cpp/io/manip/put money")` use `std::moneypunct` through `[std::money\_get](money_get "cpp/locale/money get")` and `[std::money\_put](money_put "cpp/locale/money put")` for parsing monetary value input and formatting monetary value output.
![std-moneypunct-inheritance.svg]()
Inheritance diagram.
Four standalone (locale-independent) specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::moneypunct<char>` | provides equivalents of the "C" locale preferences |
| `std::moneypunct<wchar_t>` | provides wide character equivalents of the "C" locale preferences |
| `std::moneypunct<char, true>` | provides equivalents of the "C" locale preferences, with international currency symbols |
| `std::moneypunct<wchar_t, true>` | provides wide character equivalents of the "C" locale preferences, with international currency symbols |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](moneypunct/moneypunct "cpp/locale/moneypunct/moneypunct") | constructs a new moneypunct facet (public member function) |
| [(destructor)](moneypunct/~moneypunct "cpp/locale/moneypunct/~moneypunct") | destructs a moneypunct facet (protected member function) |
| [decimal\_point](moneypunct/decimal_point "cpp/locale/moneypunct/decimal point") | invokes `do_decimal_point` (public member function) |
| [thousands\_sep](moneypunct/thousands_sep "cpp/locale/moneypunct/thousands sep") | invokes `do_thousands_sep` (public member function) |
| [grouping](moneypunct/grouping "cpp/locale/moneypunct/grouping") | invokes `do_grouping` (public member function) |
| [curr\_symbol](moneypunct/curr_symbol "cpp/locale/moneypunct/curr symbol") | invokes `do_curr_symbol` (public member function) |
| [positive\_signnegative\_sign](moneypunct/positive_sign "cpp/locale/moneypunct/positive sign") | invokes `do_positive_sign` or `do_negative_sign` (public member function) |
| [frac\_digits](moneypunct/frac_digits "cpp/locale/moneypunct/frac digits") | invokes `do_frac_digits` (public member function) |
| [pos\_formatneg\_format](moneypunct/pos_format "cpp/locale/moneypunct/pos format") | invokes `do_pos_format`/`do_neg_format` (public member function) |
### Protected member functions
| | |
| --- | --- |
| [do\_decimal\_point](moneypunct/decimal_point "cpp/locale/moneypunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function) |
| [do\_thousands\_sep](moneypunct/thousands_sep "cpp/locale/moneypunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function) |
| [do\_grouping](moneypunct/grouping "cpp/locale/moneypunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function) |
| [do\_curr\_symbol](moneypunct/curr_symbol "cpp/locale/moneypunct/curr symbol")
[virtual] | provides the string to use as the currency identifier (virtual protected member function) |
| [do\_positive\_signdo\_negative\_sign](moneypunct/positive_sign "cpp/locale/moneypunct/positive sign")
[virtual] | provides the string to indicate a positive or negative value (virtual protected member function) |
| [do\_frac\_digits](moneypunct/frac_digits "cpp/locale/moneypunct/frac digits")
[virtual] | provides the number of digits to display after the decimal point (virtual protected member function) |
| [do\_pos\_formatdo\_neg\_format](moneypunct/pos_format "cpp/locale/moneypunct/pos format")
[virtual] | provides the formatting pattern for currency values (virtual protected member function) |
### Member constants
| Member | Definition |
| --- | --- |
| const bool `intl` (static) | `International` |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
Inherited from [std::money\_base](money_base "cpp/locale/money base")
----------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum part { none, space, symbol, sign, value };` | unscoped enumeration type |
| `struct pattern { char field[4]; };` | the monetary format type |
| Enumeration constant | Definition |
| --- | --- |
| `none` | whitespace is permitted but not required except in the last position, where whitespace is not permitted |
| `space` | one or more whitespace characters are required |
| `symbol` | the sequence of characters returned by moneypunct::curr\_symbol is required |
| `sign` | the first of the characters returned by moneypunct::positive\_sign or moneypunct::negative\_sign is required |
| `value` | the absolute numeric monetary value is required |
### See also
| | |
| --- | --- |
| [money\_base](money_base "cpp/locale/money base") | defines monetary formatting patterns (class) |
| [moneypunct\_byname](moneypunct_byname "cpp/locale/moneypunct byname") | represents the system-supplied `std::moneypunct` for the named locale (class template) |
| [money\_get](money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) |
| [money\_put](money_put "cpp/locale/money put") | formats a monetary value for output as a character sequence (class template) |
cpp std::time_get std::time\_get
==============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class InputIt = std::istreambuf_iterator<CharT>
> class time_get;
```
| | |
Class template `std::time_get` encapsulates date and time parsing rules. The I/O manipulator `[std::get\_time](../io/manip/get_time "cpp/io/manip/get time")` uses the `std::time_get` facet of the I/O stream's locale to convert text input to a `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object.
![std-time get-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::time_get<char>` | parses narrow string representations of date and time |
| `std::time_get<wchar_t>` | parses wide string representations of date and time |
| `std::time_get<char, InputIt>` | parses narrow string representations of date and time using custom input iterator |
| `std::time_get<wchar_t, InputIt>` | parses wide string representations of date and time using custom input iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `InputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](time_get/time_get "cpp/locale/time get/time get") | constructs a new time\_get facet (public member function) |
| [(destructor)](time_get/~time_get "cpp/locale/time get/~time get") | destructs a time\_get facet (protected member function) |
| [date\_order](time_get/date_order "cpp/locale/time get/date order") | invokes `do_date_order` (public member function) |
| [get\_time](time_get/get_time "cpp/locale/time get/get time") | invokes `do_get_time` (public member function) |
| [get\_date](time_get/get_date "cpp/locale/time get/get date") | invokes `do_get_date` (public member function) |
| [get\_weekday](time_get/get_weekday "cpp/locale/time get/get weekday") | invokes `do_get_weekday` (public member function) |
| [get\_monthname](time_get/get_monthname "cpp/locale/time get/get monthname") | invokes `do_get_monthname` (public member function) |
| [get\_year](time_get/get_year "cpp/locale/time get/get year") | invokes `do_get_year` (public member function) |
| [get](time_get/get "cpp/locale/time get/get")
(C++11) | invokes `do_get` (public member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Protected member functions
| | |
| --- | --- |
| [do\_date\_order](time_get/date_order "cpp/locale/time get/date order")
[virtual] | obtains preferred ordering of day, month, and year (virtual protected member function) |
| [do\_get\_time](time_get/get_time "cpp/locale/time get/get time")
[virtual] | extracts hours, minutes, and seconds from input stream (virtual protected member function) |
| [do\_get\_date](time_get/get_date "cpp/locale/time get/get date")
[virtual] | extracts month, day, and year from input stream (virtual protected member function) |
| [do\_get\_weekday](time_get/get_weekday "cpp/locale/time get/get weekday")
[virtual] | extracts the name of a day of the week from input stream (virtual protected member function) |
| [do\_get\_monthname](time_get/get_monthname "cpp/locale/time get/get monthname")
[virtual] | extacts a month name from input stream (virtual protected member function) |
| [do\_get\_year](time_get/get_year "cpp/locale/time get/get year")
[virtual] | extracts a year from input stream (virtual protected member function) |
| [do\_get](time_get/get "cpp/locale/time get/get")
[virtual] (C++11) | extracts date/time components from input stream, according to the specified format (virtual protected member function) |
Inherited from std::time\_base
-------------------------------
| Type | Definition |
| --- | --- |
| `dateorder` | date order enumeration type, defining the values `no_order`, `dmy`, `mdy`, `ymd`, and `ydm` |
### Example
note: choose clang to observe the output. libstdc++ does not correctly implement the %b specifier: [bug 78714](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78714).
```
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::tm t = {};
std::istringstream ss("2011-Februar-18 23:12:34");
ss.imbue(std::locale("de_DE.utf-8"));
ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S");
if (ss.fail()) {
std::cout << "Parse failed\n";
} else {
std::cout << std::put_time(&t, "%c") << '\n';
}
}
```
Possible output:
```
Sun Feb 18 23:12:34 2011
```
### See also
| | |
| --- | --- |
| [time\_put](time_put "cpp/locale/time put") | formats contents of `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` for output as character sequence (class template) |
| [get\_time](../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::numpunct std::numpunct
=============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class numpunct;
```
| | |
The facet `std::numpunct` encapsulates numeric punctuation preferences. Stream I/O operations use `std::numpunct` through `[std::num\_get](num_get "cpp/locale/num get")` and `[std::num\_put](num_put "cpp/locale/num put")` for parsing numeric input and formatting numeric output.
The numbers that are supported by `std::numpunct` have the format described below. Here `digit` represents the radix set specified by the `fmtflags` argument value, `thousands-sep` and `decimal-point` are the results of `[thousands\_sep()](numpunct/thousands_sep "cpp/locale/numpunct/thousands sep")` and `[decimal\_point()](numpunct/decimal_point "cpp/locale/numpunct/decimal point")` functions respectively. The format of integer values is as follows:
```
integer ::= [sign] units
sign ::= plusminus
plusminus ::= '+' | '-'
units ::= digits [thousands-sep units]
digits ::= digit [digits]
```
The number of digits between the `thousand-sep`s (maximum size of `digits`) is specified by the result of `[grouping()](numpunct/grouping "cpp/locale/numpunct/grouping")`.
The format of floating-point values is as follows:
```
floatval ::= [sign] units [decimal-point [digits]] [e [sign] digits] |
[sign] decimal-point digits [e [sign] digits]
e ::= 'e' | 'E'
```
![std-numpunct-inheritance.svg]()
Inheritance diagram.
Two standalone (locale-independent) specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::numpunct<char>` | provides equivalents of the "C" locale preferences |
| `std::numpunct<wchar_t>` | provides wide character equivalents of the "C" locale preferences |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `charT` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<charT>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](numpunct/numpunct "cpp/locale/numpunct/numpunct") | constructs a new numpunct facet (public member function) |
| [(destructor)](numpunct/~numpunct "cpp/locale/numpunct/~numpunct") | destructs a numpunct facet (protected member function) |
| |
| [decimal\_point](numpunct/decimal_point "cpp/locale/numpunct/decimal point") | invokes `do_decimal_point` (public member function) |
| [thousands\_sep](numpunct/thousands_sep "cpp/locale/numpunct/thousands sep") | invokes `do_thousands_sep` (public member function) |
| [grouping](numpunct/grouping "cpp/locale/numpunct/grouping") | invokes `do_grouping` (public member function) |
| [truenamefalsename](numpunct/truefalsename "cpp/locale/numpunct/truefalsename") | invokes `do_truename` or `do_falsename` (public member function) |
### Protected member functions
| | |
| --- | --- |
| [do\_decimal\_point](numpunct/decimal_point "cpp/locale/numpunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function) |
| [do\_thousands\_sep](numpunct/thousands_sep "cpp/locale/numpunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function) |
| [do\_grouping](numpunct/grouping "cpp/locale/numpunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function) |
| [do\_truenamedo\_falsename](numpunct/truefalsename "cpp/locale/numpunct/truefalsename")
[virtual] | provides the string to use as the name of the boolean `true` and `false` (virtual protected member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Example
The following example changes the string representations of `true` and `false`.
```
#include <iostream>
#include <locale>
struct french_bool : std::numpunct<char> {
string_type do_truename() const override { return "vrai"; }
string_type do_falsename() const override { return "faux"; }
};
int main()
{
std::cout << "default locale: "
<< std::boolalpha << true << ", " << false << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new french_bool));
std::cout << "locale with modified numpunct: "
<< std::boolalpha << true << ", " << false << '\n';
}
```
Output:
```
default locale: true, false
locale with modified numpunct: vrai, faux
```
### See also
| | |
| --- | --- |
| [numpunct\_byname](numpunct_byname "cpp/locale/numpunct byname") | creates a numpunct facet for the named locale (class template) |
cpp std::codecvt_byname std::codecvt\_byname
====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class InternT, class ExternT, class State >
class codecvt_byname : public std::codecvt<InternT, ExternT, State>;
```
| | |
`std::codecvt_byname` is a `[std::codecvt](codecvt "cpp/locale/codecvt")` facet which encapsulates multibyte/wide character conversion rules of a locale specified at its construction.
Following specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::codecvt\_byname<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | identity conversion |
| `std::codecvt\_byname<char16\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-16 and UTF-8 (since C++11)(deprecated in C++20) |
| `std::codecvt\_byname<char16\_t, char8_t, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-16 and UTF-8 (since C++20) |
| `std::codecvt\_byname<char32\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-32 and UTF-8 (since C++11)(deprecated in C++20) |
| `std::codecvt\_byname<char32\_t, char8_t, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-32 and UTF-8 (since C++20) |
| `std::codecvt\_byname<wchar\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | locale-specific conversion between wide string and narrow character sets |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `codecvt_byname` facet (public member function) |
| **(destructor)** | destroys a `codecvt_byname` facet (protected member function) |
std::codecvt\_byname::codecvt\_byname
--------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit codecvt_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit codecvt_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::codecvt_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::codecvt\_byname::~codecvt\_byname
---------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~codecvt_byname();
```
| | |
Destroys the facet.
Inherited from [std::codecvt](codecvt "cpp/locale/codecvt")
-------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `intern_type` | `internT` |
| `extern_type` | `externT` |
| `state_type` | `stateT` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [out](codecvt/out "cpp/locale/codecvt/out") | invokes `do_out` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [in](codecvt/in "cpp/locale/codecvt/in") | invokes `do_in` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [unshift](codecvt/unshift "cpp/locale/codecvt/unshift") | invokes `do_unshift` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [encoding](codecvt/encoding "cpp/locale/codecvt/encoding") | invokes `do_encoding` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv") | invokes `do_always_noconv` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [length](codecvt/length "cpp/locale/codecvt/length") | invokes `do_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [max\_length](codecvt/max_length "cpp/locale/codecvt/max length") | invokes `do_max_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_out](codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_in](codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_unshift](codecvt/unshift "cpp/locale/codecvt/unshift")
[virtual] | generates the termination character sequence of `ExternT` characters for incomplete conversion (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_encoding](codecvt/encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv")
[virtual] | tests if the facet encodes an identity conversion for all valid argument values (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_length](codecvt/length "cpp/locale/codecvt/length")
[virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_max\_length](codecvt/max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
Inherited from [std::codecvt\_base](codecvt_base "cpp/locale/codecvt base")
-----------------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Example
This example demonstrates reading a GB18030-encoded file using the codecvt facet from a GB18030-aware locale.
```
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
int main()
{
// GB18030 narrow multibyte encoding
std::ofstream("text.txt") << "\x7a" // letter 'z', U+007a
"\x81\x30\x89\x38" // letter 'ß', U+00df
"\xcb\xae" // CJK ideogram '水' (water), U+6c34
"\x94\x32\xbc\x35"; // musical sign '𝄋' (segno), U+1d10b
std::wifstream fin("text.txt");
fin.imbue(std::locale(fin.getloc(),
new std::codecvt_byname<wchar_t, char, std::mbstate_t>("zh_CN.gb18030")));
for (wchar_t c; fin.get(c);)
std::cout << std::hex << std::showbase << c << '\n';
}
```
Output:
```
0x7a
0xdf
0x6c34
0x1d10b
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 21](https://cplusplus.github.io/LWG/issue21) | C++98 | the standard library did not need to provideany `std::codecvt_byname` specializations | two specializations are required |
### See also
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
| programming_docs |
cpp std::codecvt_utf8 std::codecvt\_utf8
==================
| Defined in header `[<codecvt>](../header/codecvt "cpp/header/codecvt")` | | |
| --- | --- | --- |
|
```
template<
class Elem,
unsigned long Maxcode = 0x10ffff,
std::codecvt_mode Mode = (std::codecvt_mode)0
> class codecvt_utf8 : public std::codecvt<Elem, char, std::mbstate_t>;
```
| | (since C++11) (deprecated in C++17) |
`std::codecvt_utf8` is a `[std::codecvt](codecvt "cpp/locale/codecvt")` facet which encapsulates conversion between a UTF-8 encoded byte string and UCS2 or UTF-32 character string (depending on the type of `Elem`). This codecvt facet can be used to read and write UTF-8 files, both text and binary.
### Template Parameters
| | | |
| --- | --- | --- |
| Elem | - | either `char16_t`, `char32_t`, or `wchar_t` |
| Maxcode | - | the largest value of `Elem` that this facet will read or write without error |
| Mode | - | a constant of type `[std::codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `codecvt_utf8` facet (public member function) |
| **(destructor)** | destroys a `codecvt_utf8` facet (public member function) |
std::codecvt\_utf8::codecvt\_utf8
----------------------------------
| | | |
| --- | --- | --- |
|
```
explicit codecvt_utf8( std::size_t refs = 0 );
```
| | |
Constructs a new `std::codecvt_utf8` facet, passes the initial reference counter `refs` to the base class.
### Parameters
| | | |
| --- | --- | --- |
| refs | - | the number of references that link to the facet |
std::codecvt\_utf8::~codecvt\_utf8
-----------------------------------
| | | |
| --- | --- | --- |
|
```
~codecvt_utf8();
```
| | |
Destroys the facet. Unlike the locale-managed facets, this facet's destructor is public.
Inherited from [std::codecvt](codecvt "cpp/locale/codecvt")
-------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `intern_type` | `internT` |
| `extern_type` | `externT` |
| `state_type` | `stateT` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [out](codecvt/out "cpp/locale/codecvt/out") | invokes `do_out` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [in](codecvt/in "cpp/locale/codecvt/in") | invokes `do_in` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [unshift](codecvt/unshift "cpp/locale/codecvt/unshift") | invokes `do_unshift` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [encoding](codecvt/encoding "cpp/locale/codecvt/encoding") | invokes `do_encoding` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv") | invokes `do_always_noconv` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [length](codecvt/length "cpp/locale/codecvt/length") | invokes `do_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [max\_length](codecvt/max_length "cpp/locale/codecvt/max length") | invokes `do_max_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_out](codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_in](codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_unshift](codecvt/unshift "cpp/locale/codecvt/unshift")
[virtual] | generates the termination character sequence of `ExternT` characters for incomplete conversion (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_encoding](codecvt/encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv")
[virtual] | tests if the facet encodes an identity conversion for all valid argument values (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_length](codecvt/length "cpp/locale/codecvt/length")
[virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_max\_length](codecvt/max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
Inherited from [std::codecvt\_base](codecvt_base "cpp/locale/codecvt base")
-----------------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Notes
Although the standard requires that this facet works with UCS2 when the size of `Elem` is 16 bits, some implementations use UTF-16 instead. The term "UCS2" was deprecated and removed from the Unicode standard.
### Example
The following example demonstrates the difference between UCS2/UTF-8 and UTF-16/UTF-8 conversions: the third character in the string is not a valid UCS2 character.
```
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main()
{
// UTF-8 data. The character U+1d10b, musical sign segno, does not fit in UCS2
std::string utf8 = u8"z\u6c34\U0001d10b";
// the UTF-8 / UTF-16 standard conversion facet
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;
std::u16string utf16 = utf16conv.from_bytes(utf8);
std::cout << "UTF16 conversion produced " << utf16.size() << " code units:\n";
for (char16_t c : utf16)
std::cout << std::hex << std::showbase << c << '\n';
// the UTF-8 / UCS2 standard conversion facet
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> ucs2conv;
try {
std::u16string ucs2 = ucs2conv.from_bytes(utf8);
} catch(const std::range_error& e) {
std::u16string ucs2 = ucs2conv.from_bytes(utf8.substr(0, ucs2conv.converted()));
std::cout << "UCS2 failed after producing " << std::dec << ucs2.size()<<" characters:\n";
for (char16_t c : ucs2)
std::cout << std::hex << std::showbase << c << '\n';
}
}
```
Output:
```
UTF16 conversion produced 4 code units:
0x7a
0x6c34
0xd834
0xdd0b
UCS2 failed after producing 2 characters:
0x7a
0x6c34
```
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | [`codecvt`](codecvt "cpp/locale/codecvt")<char16\_t, char, mbstate\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char16\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char32\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | **`codecvt_utf8`**<char16\_t> **`codecvt_utf8`**<wchar\_t>(Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char16\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | [`codecvt`](codecvt "cpp/locale/codecvt")<char32\_t, char, mbstate\_t> **`codecvt_utf8`**<char32\_t> **`codecvt_utf8`**<wchar\_t>(non-Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char32\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<[`codecvt`](codecvt "cpp/locale/codecvt") <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
| [codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")
(C++11)(deprecated in C++17) | tags to alter behavior of the standard codecvt facets (enum) |
| [codecvt\_utf16](codecvt_utf16 "cpp/locale/codecvt utf16")
(C++11)(deprecated in C++17) | converts between UTF-16 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
cpp std::time_put std::time\_put
==============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class OutputIt = std::ostreambuf_iterator<CharT>
> class time_put;
```
| | |
Class template `std::time_put` encapsulates date and time formatting rules. The I/O manipulator `[std::put\_time](../io/manip/put_time "cpp/io/manip/put time")` uses the `std::time_put` facet of the I/O stream's locale to generate text representation of an `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object.
![std-time put-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::time_put<char>` | creates narrow string representations of date and time |
| `std::time_put<wchar_t>` | creates wide string representations of date and time |
| `std::time_put<char, OutputIt>` | creates narrow string representations of date and time using custom output iterator |
| `std::time_put<wchar_t, OutputIt>` | creates wide string representations of date and time using custom output iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `OutputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](time_put/time_put "cpp/locale/time put/time put") | constructs a new time\_put facet (public member function) |
| [(destructor)](time_put/~time_put "cpp/locale/time put/~time put") | destructs a time\_put facet (protected member function) |
| [put](time_put/put "cpp/locale/time put/put") | invokes `do_put` (public member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Protected member functions
| | |
| --- | --- |
| [do\_put](time_put/put "cpp/locale/time put/put")
[virtual] | formats date/time and writes to output stream (virtual protected member function) |
### Example
```
#include <iostream>
#include <ctime>
#include <iomanip>
#include <codecvt>
int main()
{
std::time_t t = std::time(nullptr);
std::wbuffer_convert<std::codecvt_utf8<wchar_t>> conv(std::cout.rdbuf());
std::wostream out(&conv);
out.imbue(std::locale("ja_JP.utf8"));
// this I/O manipulator std::put_time uses std::time_put<wchar_t>
out << std::put_time(std::localtime(&t), L"%A %c") << '\n';
}
```
Output:
```
水曜日 2011年11月09日 12時32分05秒
```
### See also
| | |
| --- | --- |
| [time\_put\_byname](time_put_byname "cpp/locale/time put byname") | represents the system-supplied `std::time_put` for the named locale (class template) |
| [time\_get](time_get "cpp/locale/time get") | parses time/date values from an input character sequence into `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` (class template) |
| [put\_time](../io/manip/put_time "cpp/io/manip/put time")
(C++11) | formats and outputs a date/time value according to the specified format (function template) |
cpp std::money_get std::money\_get
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class InputIt = std::istreambuf_iterator<CharT>
> class money_get;
```
| | |
Class template `std::money_get` encapsulates the rules for parsing monetary values from character streams. The standard I/O manipulator `[std::get\_money](../io/manip/get_money "cpp/io/manip/get money")` uses the `std::money_get` facet of the I/O stream's locale.
![std-money get-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::money_get<char>` | parses narrow string representations of monetary values |
| `std::money_get<wchar_t>` | parses wide string representations of monetary values |
| `std::money_get<char, InputIt>` | parses narrow string representations of monetary values using custom input iterator |
| `std::money_get<wchar_t, InputIt>` | parses wide string representations of monetary values using custom input iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `std::basic_string<CharT>` |
| `iter_type` | `InputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](money_get/money_get "cpp/locale/money get/money get") | constructs a new money\_get facet (public member function) |
| [(destructor)](money_get/~money_get "cpp/locale/money get/~money get") | destructs a money\_get facet (protected member function) |
| [get](money_get/get "cpp/locale/money get/get") | invokes `do_get` (public member function) |
### Protected member functions
| | |
| --- | --- |
| [do\_get](money_get/get "cpp/locale/money get/get")
[virtual] | parses a monetary value from an input stream (virtual protected member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Example
```
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
#include <iterator>
int main()
{
std::string str = "$1.11 $2.22 $3.33";
std::cout << std::fixed << std::setprecision(2);
std::cout << '"' << str << "\" parsed with the I/O manipulator: ";
std::istringstream s1(str);
s1.imbue(std::locale("en_US.UTF-8"));
long double val;
while(s1 >> std::get_money(val))
std::cout << val/100 << ' ';
std::cout << '\n';
str = "USD 1,234.56";
std::cout << '"' << str << "\" parsed with the facet directly: ";
std::istringstream s2(str);
s2.imbue(std::locale("en_US.UTF-8"));
auto& f = std::use_facet<std::money_get<char>>(s2.getloc());
std::ios_base::iostate err;
std::istreambuf_iterator<char> beg(s2), end;
f.get(beg, end, true, s2, err, val);
std::cout << val/100 << '\n';
}
```
Output:
```
"$1.11 $2.22 $3.33" parsed with the I/O manipulator: 1.11 2.22 3.33
"USD 1,234.56" parsed with the facet directly: 1234.56
```
### See also
| | |
| --- | --- |
| [moneypunct](moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `std::money_get` and `[std::money\_put](money_put "cpp/locale/money put")` (class template) |
| [money\_put](money_put "cpp/locale/money put") | formats a monetary value for output as a character sequence (class template) |
| [get\_money](../io/manip/get_money "cpp/io/manip/get money")
(C++11) | parses a monetary value (function template) |
cpp std::codecvt std::codecvt
============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class InternT,
class ExternT,
class StateT
> class codecvt;
```
| | |
Class template `std::codecvt` encapsulates conversion of character strings, including wide and multibyte, from one encoding to another. All file I/O operations performed through `[std::basic\_fstream](http://en.cppreference.com/w/cpp/io/basic_fstream)<CharT>` use the `std::codecvt<CharT, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` facet of the locale imbued in the stream.
![std-codecvt-inheritance.svg]()
Inheritance diagram.
The following standalone (locale-independent) specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::codecvt<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | identity conversion |
| `std::codecvt<char16\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-16 and UTF-8 (since C++11)(deprecated in C++20) |
| `std::codecvt<char16\_t, char8_t, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-16 and UTF-8 (since C++20) |
| `std::codecvt<char32\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-32 and UTF-8 (since C++11)(deprecated in C++20) |
| `std::codecvt<char32\_t, char8_t, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between UTF-32 and UTF-8 (since C++20) |
| `std::codecvt<wchar\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` | conversion between the system's native wide and the single-byte narrow character sets |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of above specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `intern_type` | `InternT` |
| `extern_type` | `ExternT` |
| `state_type` | `StateT` |
### Member functions
| | |
| --- | --- |
| [(constructor)](codecvt/codecvt "cpp/locale/codecvt/codecvt") | constructs a new codecvt facet (public member function) |
| [(destructor)](codecvt/~codecvt "cpp/locale/codecvt/~codecvt") | destructs a codecvt facet (protected member function) |
| [out](codecvt/out "cpp/locale/codecvt/out") | invokes `do_out` (public member function) |
| [in](codecvt/in "cpp/locale/codecvt/in") | invokes `do_in` (public member function) |
| [unshift](codecvt/unshift "cpp/locale/codecvt/unshift") | invokes `do_unshift` (public member function) |
| [encoding](codecvt/encoding "cpp/locale/codecvt/encoding") | invokes `do_encoding` (public member function) |
| [always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv") | invokes `do_always_noconv` (public member function) |
| [length](codecvt/length "cpp/locale/codecvt/length") | invokes `do_length` (public member function) |
| [max\_length](codecvt/max_length "cpp/locale/codecvt/max length") | invokes `do_max_length` (public member function) |
### Member objects
| Member name | Type |
| --- | --- |
| `id` [static] | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Protected member functions
| | |
| --- | --- |
| [do\_out](codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function) |
| [do\_in](codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function) |
| [do\_unshift](codecvt/unshift "cpp/locale/codecvt/unshift")
[virtual] | generates the termination character sequence of `ExternT` characters for incomplete conversion (virtual protected member function) |
| [do\_encoding](codecvt/encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function) |
| [do\_always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv")
[virtual] | tests if the facet encodes an identity conversion for all valid argument values (virtual protected member function) |
| [do\_length](codecvt/length "cpp/locale/codecvt/length")
[virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function) |
| [do\_max\_length](codecvt/max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function) |
Inherited from [std::codecvt\_base](codecvt_base "cpp/locale/codecvt base")
-----------------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Example
The following examples reads a UTF-8 file using a locale which implements UTF-8 conversion in `codecvt<wchar_t, char, mbstate_t>` and converts a UTF-8 string to UTF-16 using one of the standard specializations of `std::codecvt`.
```
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <iomanip>
#include <codecvt>
#include <cstdint>
// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template<class Facet>
struct deletable_facet : Facet
{
template<class... Args>
deletable_facet(Args&&... args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
int main()
{
// UTF-8 narrow multibyte encoding
std::string data = reinterpret_cast<const char*>(+u8"z\u00df\u6c34\U0001f34c");
// or reinterpret_cast<const char*>(+u8"zß水🍌")
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c"
std::ofstream("text.txt") << data;
// using system-supplied locale's codecvt facet
std::wifstream fin("text.txt");
// reading from wifstream will use codecvt<wchar_t, char, mbstate_t>
// this locale's codecvt converts UTF-8 to UCS4 (on systems such as Linux)
fin.imbue(std::locale("en_US.UTF-8"));
std::cout << "The UTF-8 file contains the following UCS4 code units: ";
for (wchar_t c; fin >> c; )
std::cout << "U+" << std::hex << std::setw(4) << std::setfill('0')
<< static_cast<uint32_t>(c) << ' ';
// using standard (locale-independent) codecvt facet
std::wstring_convert<
deletable_facet<std::codecvt<char16_t, char, std::mbstate_t>>, char16_t> conv16;
std::u16string str16 = conv16.from_bytes(data);
std::cout << "\nThe UTF-8 file contains the following UTF-16 code units: ";
for (char16_t c : str16)
std::cout << "U+" << std::hex << std::setw(4) << std::setfill('0')
<< static_cast<uint16_t>(c) << ' ';
}
```
Output:
```
The UTF-8 file contains the following UCS4 code units: U+007a U+00df U+6c34 U+1f34c
The UTF-8 file contains the following UTF-16 code units: U+007a U+00df U+6c34 U+d83c U+df4c
```
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | **`codecvt`**<char16\_t, char, mbstate\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char16\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char32\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char16\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char16\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | **`codecvt`**<char32\_t, char, mbstate\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char32\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(non-Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char32\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<**`codecvt`** <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [codecvt\_base](codecvt_base "cpp/locale/codecvt base") | defines character conversion errors (class template) |
| [codecvt\_byname](codecvt_byname "cpp/locale/codecvt byname") | creates a codecvt facet for the named locale (class template) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf16](codecvt_utf16 "cpp/locale/codecvt utf16")
(C++11)(deprecated in C++17) | converts between UTF-16 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
| programming_docs |
cpp std::ctype_base std::ctype\_base
================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class ctype_base;
```
| | |
The class `std::ctype_base` lists the character classification categories which are inherited by the `[std::ctype](ctype "cpp/locale/ctype")` facets.
### Member types
| | |
| --- | --- |
| mask | unspecified [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") (enumeration, integer type, or bitset) (typedef) |
### Member constants
| | |
| --- | --- |
| space
[static] | the value of `mask` identifying whitespace character classification (public static member constant) |
| print
[static] | the value of `mask` identifying printable character classification (public static member constant) |
| cntrl
[static] | the value of `mask` identifying control character classification (public static member constant) |
| upper
[static] | the value of `mask` identifying uppercase character classification (public static member constant) |
| lower
[static] | the value of `mask` identifying lowercase character classification (public static member constant) |
| alpha
[static] | the value of `mask` identifying alphabetic character classification (public static member constant) |
| digit
[static] | the value of `mask` identifying digit character classification (public static member constant) |
| punct
[static] | the value of `mask` identifying punctuation character classification (public static member constant) |
| xdigit
[static] | the value of `mask` identifying hexadecimal digit character classification (public static member constant) |
| blank
[static] (C++11) | the value of `mask` identifying blank character classification (public static member constant) |
| alnum
[static] | `alpha | digit` (public static member constant) |
| graph
[static] | `alnum | punct` (public static member constant) |
### See also
| | |
| --- | --- |
| [ctype](ctype "cpp/locale/ctype") | defines character classification tables (class template) |
| [ctype<char>](ctype_char "cpp/locale/ctype char") | specialization of `[std::ctype](ctype "cpp/locale/ctype")` for type `char` (class template specialization) |
| [ctype\_byname](ctype_byname "cpp/locale/ctype byname") | represents the system-supplied `[std::ctype](ctype "cpp/locale/ctype")` for the named locale (class template) |
| |
cpp std::isspace(std::locale) std::isspace(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isspace( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as a whitespace character by the given locale's ctype facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as a whitespace character, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isspace( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::space, ch);
}
```
|
### Example
Demonstrates the use of isspace() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
void try_with(wchar_t c, const char* loc)
{
std::wcout << "isspace('" << c << "', locale(\"" << loc << "\")) returned "
<< std::boolalpha << std::isspace(c, std::locale(loc)) << '\n';
}
int main()
{
const wchar_t EM_SPACE = L'\u2003'; // Unicode character 'EM SPACE'
try_with(EM_SPACE, "C");
try_with(EM_SPACE, "en_US.UTF8");
}
```
Output:
```
isspace(' ', locale("C")) returned false
isspace(' ', locale("en_US.UTF8")) returned true
```
### See also
| | |
| --- | --- |
| [isspace](../string/byte/isspace "cpp/string/byte/isspace") | checks if a character is a space character (function) |
| [iswspace](../string/wide/iswspace "cpp/string/wide/iswspace") | checks if a wide character is a space character (function) |
cpp std::collate std::collate
============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class collate;
```
| | |
Class `std::collate` encapsulates locale-specific collation (comparison) and hashing of strings. This facet is used by `[std::basic\_regex](../regex/basic_regex "cpp/regex/basic regex")` and can be applied, by means of `std::locale::operator()`, directly to all standard algorithms that expect a string comparison predicate.
![std-collate-inheritance.svg]()
Inheritance diagram.
Two standalone (locale-independent) specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::collate<char>` | implements lexicographical ordering of byte strings |
| `std::collate<wchar_t>` | implements lexicographical ordering of wide strings |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `std::basic_string<CharT>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](collate/collate "cpp/locale/collate/collate") | constructs a new collate facet (public member function) |
| [(destructor)](collate/~collate "cpp/locale/collate/~collate") | destructs a collate facet (protected member function) |
| [compare](collate/compare "cpp/locale/collate/compare") | invokes `do_compare` (public member function) |
| [transform](collate/transform "cpp/locale/collate/transform") | invokes `do_transform` (public member function) |
| [hash](collate/hash "cpp/locale/collate/hash") | invokes `do_hash` (public member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Protected member functions
| | |
| --- | --- |
| [do\_compare](collate/compare "cpp/locale/collate/compare")
[virtual] | compares two strings using this facet's collation rules (virtual protected member function) |
| [do\_transform](collate/transform "cpp/locale/collate/transform")
[virtual] | transforms a string so that collation can be replaced by comparison (virtual protected member function) |
| [do\_hash](collate/hash "cpp/locale/collate/hash")
[virtual] | generates an integer hash value using this facet's collation rules (virtual protected member function) |
### Example
```
#include <locale>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::wcout.imbue(std::locale(""));
std::vector<std::wstring> v = {L"ar", L"zebra", L"\u00f6grupp", L"Zebra", L"\u00e4ngel",
L"\u00e5r", L"f\u00f6rnamn"};
std::wcout << "Default locale collation order: ";
std::sort(v.begin(), v.end());
for (auto s : v) std::wcout << s << ' '; std::wcout << '\n';
std::wcout << "English locale collation order: ";
std::sort(v.begin(), v.end(), std::locale("en_US.UTF-8"));
for (auto s : v) std::wcout << s << ' '; std::wcout << '\n';
std::wcout << "Swedish locale collation order: ";
std::sort(v.begin(), v.end(), std::locale("sv_SE.UTF-8"));
for (auto s : v) std::wcout << s << ' '; std::wcout << '\n';
}
```
Output:
```
Default locale collation order: Zebra ar förnamn zebra ängel år ögrupp
English locale collation order: ängel ar år förnamn ögrupp zebra Zebra
Swedish locale collation order: ar förnamn zebra Zebra år ängel ögrupp
```
### See also
| | |
| --- | --- |
| [operator()](locale/operator() "cpp/locale/locale/operator()") | lexicographically compares two strings using this locale's collate facet (public member function of `std::locale`) |
| [collate\_byname](collate_byname "cpp/locale/collate byname") | creates a collate facet for the named locale (class template) |
cpp std::numpunct_byname std::numpunct\_byname
=====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class numpunct_byname : public std::numpunct<CharT>;
```
| | |
`std::numpunct_byname` is a `[std::numpunct](numpunct "cpp/locale/numpunct")` facet which encapsulates numeric punctuation preferences of a locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::numpunct_byname<char>` | locale-specific `[std::numpunct](numpunct "cpp/locale/numpunct")` facet for narrow character I/O |
| `std::numpunct_byname<wchar_t>` | locale-specific `[std::numpunct](numpunct "cpp/locale/numpunct")` facet for wide characters I/O |
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `numpunct_byname` facet (public member function) |
| **(destructor)** | destroys a `numpunct_byname` facet (protected member function) |
std::numpunct\_byname::numpunct\_byname
----------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit numpunct_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit numpunct_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::numpunct_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::numpunct\_byname::~numpunct\_byname
-----------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~numpunct_byname();
```
| | |
Destroys the facet.
Inherited from [std::numpunct](numpunct "cpp/locale/numpunct")
----------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `charT` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<charT>` |
### Member functions
| | |
| --- | --- |
| [decimal\_point](numpunct/decimal_point "cpp/locale/numpunct/decimal point") | invokes `do_decimal_point` (public member function of `std::numpunct<CharT>`) |
| [thousands\_sep](numpunct/thousands_sep "cpp/locale/numpunct/thousands sep") | invokes `do_thousands_sep` (public member function of `std::numpunct<CharT>`) |
| [grouping](numpunct/grouping "cpp/locale/numpunct/grouping") | invokes `do_grouping` (public member function of `std::numpunct<CharT>`) |
| [truenamefalsename](numpunct/truefalsename "cpp/locale/numpunct/truefalsename") | invokes `do_truename` or `do_falsename` (public member function of `std::numpunct<CharT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_decimal\_point](numpunct/decimal_point "cpp/locale/numpunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function of `std::numpunct<CharT>`) |
| [do\_thousands\_sep](numpunct/thousands_sep "cpp/locale/numpunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function of `std::numpunct<CharT>`) |
| [do\_grouping](numpunct/grouping "cpp/locale/numpunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function of `std::numpunct<CharT>`) |
| [do\_truenamedo\_falsename](numpunct/truefalsename "cpp/locale/numpunct/truefalsename")
[virtual] | provides the string to use as the name of the boolean `true` and `false` (virtual protected member function of `std::numpunct<CharT>`) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Example
This example demonistrates how to apply numeric punctuation rules of another language without changing the rest of the locale.
```
#include <iostream>
#include <locale>
int main()
{
const double number = 1000.25;
std::wcout << L"default locale: " << number << L'\n';
std::wcout.imbue(std::locale(std::wcout.getloc(),
new std::numpunct_byname<wchar_t>("ru_RU.UTF8")));
std::wcout << L"default locale with russian numpunct: " << number << L'\n';
}
```
Output:
```
default locale: 1000.25
default locale with russian numpunct: 1 000,25
```
### See also
| | |
| --- | --- |
| [numpunct](numpunct "cpp/locale/numpunct") | defines numeric punctuation rules (class template) |
cpp std::time_base std::time\_base
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class time_base;
```
| | |
The class `std::time_base` provides the date order constants which are inherited by the `[std::time\_get](time_get "cpp/locale/time get")` facets.
### Member types
| Member type | Definition |
| --- | --- |
| `enum dateorder { no_order, dmy, mdy, ymd, ydm };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `no_order` | Unspecified order |
| `dmy` | Day, month, year (european) order |
| `mdy` | Month, day, year (american) order |
| `ymd` | Year, month, day |
| `ydm` | Year, day, month |
### See also
| | |
| --- | --- |
| [do\_date\_order](time_get/date_order "cpp/locale/time get/date order")
[virtual] | obtains preferred ordering of day, month, and year (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_date](time_get/get_date "cpp/locale/time get/get date")
[virtual] | extracts month, day, and year from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
cpp std::messages_byname std::messages\_byname
=====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class messages_byname : public std::messages<CharT>;
```
| | |
`std::messages_byname` is a `[std::messages](messages "cpp/locale/messages")` facet which encapsulates retrieval of strings from message catalogs of the locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::messages_byname<char>` | narrow/multibyte message catalog access |
| `std::messages_byname<wchar_t>` | wide string message catalog access |
### Member types
| Member type | Definition |
| --- | --- |
| `catalog` | `std::messages_base<CharT>::catalog` |
| `string_type` | `std::basic_string<CharT>` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `messages_byname` facet (public member function) |
| **(destructor)** | destroys a `messages_byname` facet (protected member function) |
std::messages\_byname::messages\_byname
----------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit messages_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit messages_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::messages_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::messages\_byname::~messages\_byname
-----------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~messages_byname();
```
| | |
Destroys the facet.
Inherited from [std::messages](messages "cpp/locale/messages")
----------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `charT` |
| `string_type` | `std::basic_string<charT>` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [open](messages/open "cpp/locale/messages/open") | invokes `do_open` (public member function of `std::messages<CharT>`) |
| [get](messages/get "cpp/locale/messages/get") | invokes `do_get` (public member function of `std::messages<CharT>`) |
| [close](messages/close "cpp/locale/messages/close") | invokes `do_close` (public member function of `std::messages<CharT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_open](messages/open "cpp/locale/messages/open")
[virtual] | opens a named message catalog (virtual protected member function of `std::messages<CharT>`) |
| [do\_get](messages/get "cpp/locale/messages/get")
[virtual] | retrieves a message from an open message catalog (virtual protected member function of `std::messages<CharT>`) |
| [do\_close](messages/close "cpp/locale/messages/close")
[virtual] | closes a message catalog (virtual protected member function of `std::messages<CharT>`) |
### Example
```
#include <iostream>
#include <locale>
void try_with(const std::locale& loc)
{
const std::messages<char>& facet = std::use_facet<std::messages<char> >(loc)
;
std::messages<char>::catalog cat = facet.open("sed", std::cout.getloc());
if(cat < 0 )
std::cout << "Could not open \"sed\" message catalog\n";
else
std::cout << "\"No match\" "
<< facet.get(cat, 0, 0, "No match") << '\n'
<< "\"Memory exhausted\" "
<< facet.get(cat, 0, 0, "Memory exhausted") << '\n';
facet.close(cat);
}
int main()
{
std::locale loc("en_US.utf8");
std::cout.imbue(loc);
try_with(std::locale(loc, new std::messages_byname<char>("de_DE.utf8")));
try_with(std::locale(loc, new std::messages_byname<char>("fr_FR.utf8")));
try_with(std::locale(loc, new std::messages_byname<char>("ja_JP.utf8")));
}
```
Possible output:
```
"No match" Keine Übereinstimmung
"Memory exhausted" Speicher erschöpft
"No match" Pas de concordance
"Memory exhausted" Mémoire épuisée
"No match" 照合しません
"Memory exhausted" メモリーが足りません
```
### See also
| | |
| --- | --- |
| [messages](messages "cpp/locale/messages") | implements retrieval of strings from message catalogs (class template) |
cpp std::time_get_byname std::time\_get\_byname
======================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class InputIt = std::istreambuf_iterator<CharT>
> class time_get_byname : public std::time_get<CharT, InputIt>
```
| | |
`std::time_get_byname` is a `[std::time\_get](time_get "cpp/locale/time get")` facet which encapsulates time and date parsing rules of the locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::time_get_byname<char, InputIt>` | narrow/multibyte time parsing |
| `std::time_get_byname<wchar_t, InputIt>` | wide string time parsing |
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `InputIt` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `time_get_byname` facet (public member function) |
| **(destructor)** | destroys a `time_get_byname` facet (protected member function) |
std::time\_get\_byname::time\_get\_byname
------------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit time_get_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit time_get_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::time_get_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::time\_get\_byname::~time\_get\_byname
-------------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~time_get_byname();
```
| | |
Destroys the facet.
Inherited from [std::time\_get](time_get "cpp/locale/time get")
-----------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `InputIt` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [date\_order](time_get/date_order "cpp/locale/time get/date order") | invokes `do_date_order` (public member function of `std::time_get<CharT,InputIt>`) |
| [get\_time](time_get/get_time "cpp/locale/time get/get time") | invokes `do_get_time` (public member function of `std::time_get<CharT,InputIt>`) |
| [get\_date](time_get/get_date "cpp/locale/time get/get date") | invokes `do_get_date` (public member function of `std::time_get<CharT,InputIt>`) |
| [get\_weekday](time_get/get_weekday "cpp/locale/time get/get weekday") | invokes `do_get_weekday` (public member function of `std::time_get<CharT,InputIt>`) |
| [get\_monthname](time_get/get_monthname "cpp/locale/time get/get monthname") | invokes `do_get_monthname` (public member function of `std::time_get<CharT,InputIt>`) |
| [get\_year](time_get/get_year "cpp/locale/time get/get year") | invokes `do_get_year` (public member function of `std::time_get<CharT,InputIt>`) |
| [get](time_get/get "cpp/locale/time get/get")
(C++11) | invokes `do_get` (public member function of `std::time_get<CharT,InputIt>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_date\_order](time_get/date_order "cpp/locale/time get/date order")
[virtual] | obtains preferred ordering of day, month, and year (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_time](time_get/get_time "cpp/locale/time get/get time")
[virtual] | extracts hours, minutes, and seconds from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_date](time_get/get_date "cpp/locale/time get/get date")
[virtual] | extracts month, day, and year from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_weekday](time_get/get_weekday "cpp/locale/time get/get weekday")
[virtual] | extracts the name of a day of the week from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_monthname](time_get/get_monthname "cpp/locale/time get/get monthname")
[virtual] | extacts a month name from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get\_year](time_get/get_year "cpp/locale/time get/get year")
[virtual] | extracts a year from input stream (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| [do\_get](time_get/get "cpp/locale/time get/get")
[virtual] (C++11) | extracts date/time components from input stream, according to the specified format (virtual protected member function of `std::time_get<CharT,InputIt>`) |
Inherited from std::time\_base
-------------------------------
| Type | Definition |
| --- | --- |
| `dateorder` | date order enumeration type, defining the values `no_order`, `dmy`, `mdy`, `ymd`, and `ydm` |
### Example
### See also
| | |
| --- | --- |
| [time\_get](time_get "cpp/locale/time get") | parses time/date values from an input character sequence into `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` (class template) |
| [get\_time](../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
| programming_docs |
cpp std::has_facet std::has\_facet
===============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class Facet >
bool has_facet( const locale& loc ) throw();
```
| | (until C++11) |
|
```
template< class Facet >
bool has_facet( const locale& loc ) noexcept;
```
| | (since C++11) |
Checks if the locale `loc` implements the facet `Facet`.
### Parameters
| | | |
| --- | --- | --- |
| loc | - | the locale object to query |
### Return value
Returns `true` if the facet `Facet` was installed in the locale `loc`, `false` otherwise.
### Example
```
#include <iostream>
#include <locale>
// minimal custom facet
struct myfacet : public std::locale::facet {
static std::locale::id id;
};
std::locale::id myfacet::id;
int main()
{
// loc is a "C" locale with myfacet added
std::locale loc(std::locale::classic(), new myfacet);
std::cout << std::boolalpha
<< "Can loc classify chars? "
<< std::has_facet<std::ctype<char>>(loc) << '\n'
<< "Can loc classify char32_t? "
<< std::has_facet<std::ctype<char32_t>>(loc) << '\n'
<< "Does loc implement myfacet? "
<< std::has_facet<myfacet>(loc) << '\n';
}
```
Output:
```
Can loc classify chars? true
Can loc classify char32_t? false
Does loc implement myfacet? true
```
### See also
| | |
| --- | --- |
| [locale](locale "cpp/locale/locale") | set of polymorphic facets that encapsulate cultural differences (class) |
| [use\_facet](use_facet "cpp/locale/use facet") | obtains a facet from a locale (function template) |
cpp std::isupper(std::locale) std::isupper(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isupper( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as an uppercase alphabetic character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as uppercase, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isupper( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::upper, ch);
}
```
|
### Example
Demonstrates the use of isupper() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u00de'; // capital letter thorn
std::locale loc1("C");
std::cout << "isupper('Þ', C locale) returned "
<< std::boolalpha << std::isupper(c, loc1) << '\n';
std::locale loc2("en_US.UTF8");
std::cout << "isupper('Þ', Unicode locale) returned "
<< std::boolalpha << std::isupper(c, loc2) << '\n';
}
```
Output:
```
isupper('Þ', C locale) returned false
isupper('Þ', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [isupper](../string/byte/isupper "cpp/string/byte/isupper") | checks if a character is an uppercase character (function) |
| [iswupper](../string/wide/iswupper "cpp/string/wide/iswupper") | checks if a wide character is an uppercase character (function) |
cpp std::money_base std::money\_base
================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class money_base;
```
| | |
The class `std::money_base` provides constants which are inherited and used by the `[std::moneypunct](moneypunct "cpp/locale/moneypunct")`, `[std::money\_get](money_get "cpp/locale/money get")` and `[std::money\_put](money_put "cpp/locale/money put")` facets.
### Member types
| Member type | Definition |
| --- | --- |
| `enum part { none, space, symbol, sign, value };` | unscoped enumeration type |
| `struct pattern { char field[4]; };` | the monetary format type |
| Enumeration constant | Definition |
| --- | --- |
| `none` | whitespace is permitted but not required except in the last position, where whitespace is not permitted |
| `space` | one or more whitespace characters are required |
| `symbol` | the sequence of characters returned by moneypunct::curr\_symbol is required |
| `sign` | the first of the characters returned by moneypunct::positive\_sign or moneypunct::negative\_sign is required |
| `value` | the absolute numeric monetary value is required |
### Notes
The monetary format is an array of four `char`s convertible to `std::money_base::part`. In that sequence, each of `symbol`, `sign`, and `value` appears exactly once, and either `space` or `none` appears in the remaining position. The value `none`, if present, is not first; the value `space`, if present, is neither first nor last.
The default format, returned by the standard specializations of `[std::moneypunct](moneypunct "cpp/locale/moneypunct")` is `{symbol, sign, none, value}`
### See also
| | |
| --- | --- |
| [moneypunct](moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](money_get "cpp/locale/money get")` and `[std::money\_put](money_put "cpp/locale/money put")` (class template) |
| [money\_get](money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) |
| [money\_put](money_put "cpp/locale/money put") | formats a monetary value for output as a character sequence (class template) |
cpp std::ispunct(std::locale) std::ispunct(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool ispunct( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as an punctuation character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as punctuation, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool ispunct( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::punct, ch);
}
```
|
### Example
Demonstrates the use of ispunct() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u214b'; // upside-down ampersand
std::locale loc1("C");
std::cout << "ispunct('⅋', C locale) returned "
<< std::boolalpha << std::ispunct(c, loc1) << '\n';
std::locale loc2("en_US.UTF-8");
std::cout << "ispunct('⅋', Unicode locale) returned "
<< std::boolalpha << std::ispunct(c, loc2) << '\n';
}
```
Output:
```
isalpha('⅋', C locale) returned false
isalpha('⅋', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [ispunct](../string/byte/ispunct "cpp/string/byte/ispunct") | checks if a character is a punctuation character (function) |
| [iswpunct](../string/wide/iswpunct "cpp/string/wide/iswpunct") | checks if a wide character is a punctuation character (function) |
cpp std::iscntrl(std::locale) std::iscntrl(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool iscntrl( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as a control character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as a control character, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool iscntrl( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::cntrl, ch);
}
```
|
### Example
Demonstrates the use of iscntrl() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t CCH = L'\u0094'; // Destructive Backspace in Unicode
std::locale loc1("C");
std::cout << "iscntrl(CCH, C locale) returned "
<< std::boolalpha << std::iscntrl(CCH, loc1) << '\n';
std::locale loc2("en_US.UTF8");
std::cout << "iscntrl(CCH, Unicode locale) returned "
<< std::boolalpha << std::iscntrl(CCH, loc2) << '\n';
}
```
Output:
```
iscntrl(CCH, C locale) returned false
iscntrl(CCH, Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [iscntrl](../string/byte/iscntrl "cpp/string/byte/iscntrl") | checks if a character is a control character (function) |
| [iswcntrl](../string/wide/iswcntrl "cpp/string/wide/iswcntrl") | checks if a wide character is a control character (function) |
cpp std::isdigit(std::locale) std::isdigit(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isdigit( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as a digit by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as a digit, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isdigit( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::digit, ch);
}
```
|
### Example
```
#include <iostream>
#include <locale>
#include <string>
#include <set>
struct jdigit_ctype : std::ctype<wchar_t>
{
std::set<wchar_t> jdigits{L'一',L'二',L'三',L'四',L'五',L'六',L'七',L'八',L'九',L'十'};
bool do_is(mask m, char_type c) const {
if ((m & digit) && jdigits.count(c))
return true; // Japanese digits will be classified as digits
return ctype::do_is(m, c); // leave the rest to the parent class
}
};
int main()
{
std::wstring text = L"123一二三123";
std::locale loc(std::locale(""), new jdigit_ctype);
std::locale::global(std::locale(""));
std::wcout.imbue(std::locale());
for(wchar_t c : text)
if(std::isdigit(c, loc))
std::wcout << c << " is a digit\n";
else
std::wcout << c << " is NOT a digit\n";
}
```
Output:
```
1 is a digit
2 is a digit
3 is a digit
一 is a digit
二 is a digit
三 is a digit
1 is NOT a digit
2 is NOT a digit
3 is NOT a digit
```
### See also
| | |
| --- | --- |
| [isdigit](../string/byte/isdigit "cpp/string/byte/isdigit") | checks if a character is a digit (function) |
| [iswdigit](../string/wide/iswdigit "cpp/string/wide/iswdigit") | checks if a wide character is a digit (function) |
cpp std::messages_base std::messages\_base
===================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class messages_base;
```
| | |
The class `std::messages_base` provides a type definition which is inherited and used by the `[std::messages](messages "cpp/locale/messages")` facets.
### Member types
| Member type | Definition |
| --- | --- |
| `catalog` | `/*unspecified signed integer type*/` |
### Notes
`catalog` was erroneously specified as `int` in C++11, this was corrected in [LWG issue #2028](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2028) and included in C++14.
### See also
| | |
| --- | --- |
| [messages](messages "cpp/locale/messages") | implements retrieval of strings from message catalogs (class template) |
cpp std::setlocale std::setlocale
==============
| Defined in header `[<clocale>](../header/clocale "cpp/header/clocale")` | | |
| --- | --- | --- |
|
```
char* setlocale( int category, const char* locale);
```
| | |
The `setlocale` function installs the specified system locale or its portion as the new C locale. The modifications remain in effect and influences the execution of all locale-sensitive C library functions until the next call to `setlocale`. If `locale` is a null pointer, `setlocale` queries the current C locale without modifying it.
### Parameters
| | | |
| --- | --- | --- |
| category | - | locale category identifier, one of the [`LC_xxx`](lc_categories "cpp/locale/LC categories") macros. May be `0`. |
| locale | - | system-specific locale identifier. Can be `""` for the user-preferred locale or `"C"` for the minimal locale |
### Return value
Pointer to a narrow null-terminated string identifying the C locale after applying the changes, if any, or null pointer on failure.
A copy of the returned string along with the category used in this call to `std::setlocale` may be used later in the program to restore the locale back to the state at the end of this call.
### Notes
During program startup, the equivalent of `std::setlocale([LC\_ALL](http://en.cppreference.com/w/cpp/locale/LC_categories), "C");` is executed before any user code is run.
Although the return type is `char*`, modifying the pointed-to characters is undefined behavior.
Because `setlocale` modifies global state which affects execution of locale-dependent functions, it is undefined behavior to call it from one thread, while another thread is executing any of the following functions: `[std::fprintf](../io/c/fprintf "cpp/io/c/fprintf")`, `std::isprint`, `[std::iswdigit](../string/wide/iswdigit "cpp/string/wide/iswdigit")`, `[std::localeconv](localeconv "cpp/locale/localeconv")`, `std::tolower`, `[std::fscanf](../io/c/fscanf "cpp/io/c/fscanf")`, `std::ispunct`, `[std::iswgraph](../string/wide/iswgraph "cpp/string/wide/iswgraph")`, `[std::mblen](../string/multibyte/mblen "cpp/string/multibyte/mblen")`, `std::toupper`, `std::isalnum`, `std::isspace`, `[std::iswlower](../string/wide/iswlower "cpp/string/wide/iswlower")`, `[std::mbstowcs](../string/multibyte/mbstowcs "cpp/string/multibyte/mbstowcs")`, `[std::towlower](../string/wide/towlower "cpp/string/wide/towlower")`, `std::isalpha`, `std::isupper`, `[std::iswprint](../string/wide/iswprint "cpp/string/wide/iswprint")`, `[std::mbtowc](../string/multibyte/mbtowc "cpp/string/multibyte/mbtowc")`, `[std::towupper](../string/wide/towupper "cpp/string/wide/towupper")`, `std::isblank`, `[std::iswalnum](../string/wide/iswalnum "cpp/string/wide/iswalnum")`, `[std::iswpunct](../string/wide/iswpunct "cpp/string/wide/iswpunct")`, `std::setlocale`, `[std::wcscoll](../string/wide/wcscoll "cpp/string/wide/wcscoll")`, `std::iscntrl`, `[std::iswalpha](../string/wide/iswalpha "cpp/string/wide/iswalpha")`, `[std::iswspace](../string/wide/iswspace "cpp/string/wide/iswspace")`, `[std::strcoll](../string/byte/strcoll "cpp/string/byte/strcoll")`, `[std::wcstod](../string/wide/wcstof "cpp/string/wide/wcstof")`, `std::isdigit`, `[std::iswblank](../string/wide/iswblank "cpp/string/wide/iswblank")`, `[std::iswupper](../string/wide/iswupper "cpp/string/wide/iswupper")`, `[std::strerror](../string/byte/strerror "cpp/string/byte/strerror")`, `[std::wcstombs](../string/multibyte/wcstombs "cpp/string/multibyte/wcstombs")`, `std::isgraph`, `[std::iswcntrl](../string/wide/iswcntrl "cpp/string/wide/iswcntrl")`, `[std::iswxdigit](../string/wide/iswxdigit "cpp/string/wide/iswxdigit")`, `[std::strtod](../string/byte/strtof "cpp/string/byte/strtof")`, `[std::wcsxfrm](../string/wide/wcsxfrm "cpp/string/wide/wcsxfrm")`, `std::islower`, `[std::iswctype](../string/wide/iswctype "cpp/string/wide/iswctype")`, `std::isxdigit`.
POSIX also defines a locale named "POSIX", which is always accessible and is exactly equivalent to the default minimal "C" locale.
POSIX also specifies that the returned pointer, not just the contents of the pointed-to string, may be invalidated by subsequent calls to setlocale.
### Example
```
#include <cstdio>
#include <clocale>
#include <ctime>
#include <cwchar>
int main()
{
// the C locale will be UTF-8 enabled English;
// decimal dot will be German
// date and time formatting will be Japanese
std::setlocale(LC_ALL, "en_US.UTF-8");
std::setlocale(LC_NUMERIC, "de_DE.UTF-8");
std::setlocale(LC_TIME, "ja_JP.UTF-8");
wchar_t str[100];
std::time_t t = std::time(nullptr);
std::wcsftime(str, 100, L"%A %c", std::localtime(&t));
std::wprintf(L"Number: %.2f\nDate: %Ls\n", 3.14, str);
}
```
Output:
```
Number: 3,14
Date: 月曜日 2011年12月19日 18時04分40秒
```
### See also
| | |
| --- | --- |
| [LC\_ALLLC\_COLLATELC\_CTYPELC\_MONETARYLC\_NUMERICLC\_TIME](lc_categories "cpp/locale/LC categories") | locale categories for `std::setlocale` (macro constant) |
| [locale](locale "cpp/locale/locale") | set of polymorphic facets that encapsulate cultural differences (class) |
| [C documentation](https://en.cppreference.com/w/c/locale/setlocale "c/locale/setlocale") for `setlocale` |
cpp std::codecvt_base std::codecvt\_base
==================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class codecvt_base;
```
| | |
The class `std::codecvt_base` provides the conversion status constants which are inherited and used by the `[std::codecvt](codecvt "cpp/locale/codecvt")` facets.
### Member types
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Value | Explanation |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Notes
The value `std::codecvt_base::partial` is used to indicate that either the destination range is too short to receive the results of the conversion or the input is truncated in the middle of an otherwise valid multibyte character.
### See also
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
cpp std::time_put_byname std::time\_put\_byname
======================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT, class OutputIterator = std::ostreambuf_iterator<CharT> >
class time_put_byname : public std::time_put<CharT, OutputIterator>;
```
| | |
`std::time_put_byname` is a `[std::time\_put](time_put "cpp/locale/time put")` facet which encapsulates time and date formatting rules of the locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::time_put_byname<char, OutputIterator>` | narrow/multibyte time formatting |
| `std::time_put_byname<wchar_t, OutputIterator>` | wide string time formatting |
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `OutputIterator` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `time_put_byname` facet (public member function) |
| **(destructor)** | destroys a `time_put_byname` facet (protected member function) |
std::time\_put\_byname::time\_put\_byname
------------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit time_put_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit time_put_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::time_put_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::time\_put\_byname::~time\_put\_byname
-------------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~time_put_byname();
```
| | |
Destroys the facet.
Inherited from [std::time\_put](time_put "cpp/locale/time put")
-----------------------------------------------------------------
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [put](time_put/put "cpp/locale/time put/put") | invokes `do_put` (public member function of `std::time_put<CharT,OutputIt>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_put](time_put/put "cpp/locale/time put/put")
[virtual] | formats date/time and writes to output stream (virtual protected member function of `std::time_put<CharT,OutputIt>`) |
### Example
This example prints current time using the "C" locale with the time\_put facet replaced by various `std::time_put_byname` facets.
```
#include <iostream>
#include <ctime>
#include <iomanip>
#include <codecvt>
int main()
{
std::time_t t = std::time(nullptr);
std::wbuffer_convert<std::codecvt_utf8<wchar_t>> conv(std::cout.rdbuf());
std::wostream out(&conv);
out.imbue(std::locale(out.getloc(),
new std::time_put_byname<wchar_t>("ja_JP")));
out << std::put_time(std::localtime(&t), L"%A %c") << '\n';
out.imbue(std::locale(out.getloc(),
new std::time_put_byname<wchar_t>("ru_RU.utf8")));
out << std::put_time(std::localtime(&t), L"%A %c") << '\n';
out.imbue(std::locale(out.getloc(),
new std::time_put_byname<wchar_t>("sv_SE.utf8")));
out << std::put_time(std::localtime(&t), L"%A %c") << '\n';
}
```
Possible output:
```
木曜日 2012年08月09日 21時41分02秒
Четверг Чт. 09 авг. 2012 21:41:02
torsdag tor 9 aug 2012 21:41:02
```
### See also
| | |
| --- | --- |
| [time\_put](time_put "cpp/locale/time put") | formats contents of `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` for output as character sequence (class template) |
| programming_docs |
cpp std::localeconv std::localeconv
===============
| Defined in header `[<clocale>](../header/clocale "cpp/header/clocale")` | | |
| --- | --- | --- |
|
```
std::lconv* localeconv();
```
| | |
The `localeconv` function obtains a pointer to a static object of type `[std::lconv](lconv "cpp/locale/lconv")`, which represents numeric and monetary formatting rules of the current C locale.
### Parameters
(none).
### Return value
Pointer to the current `[std::lconv](lconv "cpp/locale/lconv")` object.
### Notes
Modifying the object references through the returned pointer is undefined behavior.
`std::localeconv` modifies a static object, calling it from different threads without synchronization is undefined behavior.
### Example
```
#include <clocale>
#include <iostream>
int main()
{
std::setlocale(LC_ALL, "ja_JP.UTF-8");
std::lconv* lc = std::localeconv();
std::cout << "Japanese currency symbol: " << lc->currency_symbol
<< '(' << lc->int_curr_symbol << ")\n";
}
```
Output:
```
Japanese currency symbol: ¥(JPY )
```
### See also
| | |
| --- | --- |
| [setlocale](setlocale "cpp/locale/setlocale") | gets and sets the current C locale (function) |
| [lconv](lconv "cpp/locale/lconv") | formatting details, returned by `std::localeconv` (class) |
| [C documentation](https://en.cppreference.com/w/c/locale/localeconv "c/locale/localeconv") for `localeconv` |
cpp std::wbuffer_convert std::wbuffer\_convert
=====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<class Codecvt,
class Elem = wchar_t,
class Tr = std::char_traits<Elem> >
class wbuffer_convert : public std::basic_streambuf<Elem, Tr>
```
| | (since C++11) (deprecated in C++17) |
`std::wbuffer_convert` is a wrapper over stream buffer of type `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<char>` which gives it the appearance of `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<Elem>`. All I/O performed through `std::wbuffer_convert` undergoes character conversion as defined by the facet `Codecvt`. `std::wbuffer_convert` assumes ownership of the conversion facet, and cannot use a facet managed by a locale. The standard facets suitable for use with `std::wbuffer_convert` are `[std::codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")` for UTF-8/UCS2 and UTF-8/UCS4 conversions and `[std::codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")` for UTF-8/UTF-16 conversions.
This class template makes the implicit character conversion functionality of `[std::basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf")` available for any `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`.
### Member types
| Member type | Definition |
| --- | --- |
| `state_type` | `Codecvt::state_type` |
### Member functions
| | |
| --- | --- |
| [(constructor)](wbuffer_convert/wbuffer_convert "cpp/locale/wbuffer convert/wbuffer convert") | constructs a new wbuffer\_convert (public member function) |
| operator= | the copy assignment operator is deleted (public member function) |
| [(destructor)](wbuffer_convert/~wbuffer_convert "cpp/locale/wbuffer convert/~wbuffer convert") | destructs the wbuffer\_convert and its conversion facet (public member function) |
| [rdbuf](wbuffer_convert/rdbuf "cpp/locale/wbuffer convert/rdbuf") | returns or replaces the underlying narrow stream buffer (public member function) |
| [state](wbuffer_convert/state "cpp/locale/wbuffer convert/state") | returns the current conversion state (public member function) |
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | [`codecvt`](codecvt "cpp/locale/codecvt")<char16\_t, char, mbstate\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char16\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char32\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char16\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char16\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | [`codecvt`](codecvt "cpp/locale/codecvt")<char32\_t, char, mbstate\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char32\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(non-Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char32\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<[`codecvt`](codecvt "cpp/locale/codecvt") <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [wstring\_convert](wstring_convert "cpp/locale/wstring convert")
(C++11)(deprecated in C++17) | performs conversions between a wide string and a byte string (class template) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
cpp std::isalpha(std::locale) std::isalpha(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isalpha( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as an alphabetic character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as alphabetic, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isalpha( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::alpha, ch);
}
```
|
### Example
Demonstrates the use of isalpha() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u042f'; // cyrillic capital letter ya
std::locale loc1("C");
std::cout << "isalpha('Я', C locale) returned "
<< std::boolalpha << std::isalpha(c, loc1) << '\n';
std::locale loc2("en_US.UTF8");
std::cout << "isalpha('Я', Unicode locale) returned "
<< std::boolalpha << std::isalpha(c, loc2) << '\n';
}
```
Output:
```
isalpha('Я', C locale) returned false
isalpha('Я', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [isalpha](../string/byte/isalpha "cpp/string/byte/isalpha") | checks if a character is alphabetic (function) |
| [iswalpha](../string/wide/iswalpha "cpp/string/wide/iswalpha") | checks if a wide character is alphabetic (function) |
cpp LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME LC\_ALL, LC\_COLLATE, LC\_CTYPE, LC\_MONETARY, LC\_NUMERIC, LC\_TIME
====================================================================
| Defined in header `[<clocale>](../header/clocale "cpp/header/clocale")` | | |
| --- | --- | --- |
|
```
#define LC_ALL /*implementation defined*/
```
| | |
|
```
#define LC_COLLATE /*implementation defined*/
```
| | |
|
```
#define LC_CTYPE /*implementation defined*/
```
| | |
|
```
#define LC_MONETARY /*implementation defined*/
```
| | |
|
```
#define LC_NUMERIC /*implementation defined*/
```
| | |
|
```
#define LC_TIME /*implementation defined*/
```
| | |
Each of the above macro constants expand to integer constant expressions with distinct values that are suitable for use as the first argument of `[std::setlocale](setlocale "cpp/locale/setlocale")`.
| Constant | Explanation |
| --- | --- |
| `LC_ALL` | selects the entire C locale |
| `LC_COLLATE` | selects the collation category of the C locale |
| `LC_CTYPE` | selects the character classification category of the C locale |
| `LC_MONETARY` | selects the monetary formatting category of the C locale |
| `LC_NUMERIC` | selects the numeric formatting category of the C locale |
| `LC_TIME` | selects the time formatting category of the C locale |
Additional macro constants, with names that begin with `LC_` followed by at least one uppercase letter, may be defined in `<clocale>`. For example, the POSIX specification requires LC\_MESSAGES (which controls `[std::perror](../io/c/perror "cpp/io/c/perror")` and `[std::strerror](../string/byte/strerror "cpp/string/byte/strerror")`), ISO/IEC 30112:2014 ([2014 draft](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf)) additionally defines LC\_IDENTIFICATION, LC\_XLITERATE, LC\_NAME, LC\_ADDRESS, LC\_TELEPHONE, LC\_PAPER, LC\_MEASUREMENT, and LC\_KEYBOARD, which are supported by the GNU C library (except for LC\_XLITERATE).
### Example
```
#include <cstdio>
#include <clocale>
#include <ctime>
#include <cwchar>
int main()
{
std::setlocale(LC_ALL, "en_US.UTF-8"); // the C locale will be the UTF-8 enabled English
std::setlocale(LC_NUMERIC, "de_DE.UTF-8"); // decimal dot will be German
std::setlocale(LC_TIME, "ja_JP.UTF-8"); // date/time formatting will be Japanese
wchar_t str[100];
std::time_t t = std::time(nullptr);
std::wcsftime(str, 100, L"%A %c", std::localtime(&t));
std::wprintf(L"Number: %.2f\nDate: %Ls\n", 3.14, str);
}
```
Output:
```
Number: 3,14
Date: 月曜日 2011年12月19日 18時04分40秒
```
### See also
| | |
| --- | --- |
| [setlocale](setlocale "cpp/locale/setlocale") | gets and sets the current C locale (function) |
| [locale](locale "cpp/locale/locale") | set of polymorphic facets that encapsulate cultural differences (class) |
| [C documentation](https://en.cppreference.com/w/c/locale/LC_categories "c/locale/LC categories") for locale categories |
cpp std::locale std::locale
===========
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class locale;
```
| | |
An object of class `std::locale` is an immutable indexed set of immutable facets. Each stream object of the C++ input/output library is associated with an `std::locale` object and uses its facets for parsing and formatting of all data. In addition, a locale object is associated with each `[std::basic\_regex](../regex/basic_regex "cpp/regex/basic regex")` object. Locale objects can also be used as predicates that perform string collation with the standard containers and algorithms and can be accessed directly to obtain or modify the facets they hold.
Each locale constructed in a C++ program holds at least the following standard facets, but a program may define additional specializations or completely new facets and add them to any existing locale object.
| Supported facets |
| --- |
| `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)<char>` | `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)<wchar\_t>` |
| `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` | `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<wchar\_t>` |
| `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char,char,mbstate_t>``[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char16\_t,char,mbstate_t>` | `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char32\_t,char,mbstate_t>` `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<wchar\_t,char,mbstate_t>` |
| `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<char>` `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<char,true>` | `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<wchar\_t>` `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<wchar\_t,true>` |
| `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)<char>` | `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)<wchar\_t>` |
| `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)<char>` | `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)<wchar\_t>` |
| `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<char>` | `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<wchar\_t>` |
| `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)<char>` | `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)<wchar\_t>` |
| `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)<char>` | `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)<wchar\_t>` |
| `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)<char>` | `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)<wchar\_t>` |
| `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)<char>` | `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)<wchar\_t>` |
| `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)<char>` | `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)<wchar\_t>` |
Internally, a locale object is implemented as-if it is a reference-counted pointer to an array (indexed by `[std::locale::id](locale/id "cpp/locale/locale/id")`) of reference-counted pointers to facets: copying a locale only copies one pointer and increments several reference counts. To maintain the standard C++ library thread safety guarantees (operations on different objects are always thread-safe), both the locale reference count and each facet reference count are updated in thread-safe manner, similar to `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")`.
### Member types
| | |
| --- | --- |
| [id](locale/id "cpp/locale/locale/id") | the facet index type: each facet class must declare or inherit a public static member of this type (class) |
| [facet](locale/facet "cpp/locale/locale/facet") | the base class for all facet categories: each facet of any category is derived from this type (class) |
| category | `int` (typedef) |
### Member objects
| | |
| --- | --- |
| none
[static] | a zero value of type `category` indicating no facet category (public static member constant) |
| collate
[static] | a bitmask value of type `category` indicating the collate facet category (public static member constant) |
| ctype
[static] | a bitmask value of type `category` indicating the ctype facet category (public static member constant) |
| monetary
[static] | a bitmask value of type `category` indicating the monetary facet category (public static member constant) |
| numeric
[static] | a bitmask value of type `category` indicating the numeric facet category (public static member constant) |
| time
[static] | a bitmask value of type `category` indicating the time facet category (public static member constant) |
| messages
[static] | a bitmask value of type `category` indicating the messages facet category (public static member constant) |
| all
[static] | `collate | ctype | monetary | numeric | time | messages` (public static member constant) |
### Member functions
| | |
| --- | --- |
| [(constructor)](locale/locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
| [(destructor)](locale/~locale "cpp/locale/locale/~locale") | destructs the locale and the facets whose reference count becomes zero (public member function) |
| [operator=](locale/operator= "cpp/locale/locale/operator=") | replaces a locale (public member function) |
| [combine](locale/combine "cpp/locale/locale/combine") | constructs a locale with compile-time identified facet copied from another locale (public member function) |
| [name](locale/name "cpp/locale/locale/name") | returns the name of the locale or "\*" if unnamed (public member function) |
| [operator==operator!=](locale/operator_cmp "cpp/locale/locale/operator cmp")
(removed in C++20) | equality comparison between locale objects (public member function) |
| [operator()](locale/operator() "cpp/locale/locale/operator()") | lexicographically compares two strings using this locale's collate facet (public member function) |
| [global](locale/global "cpp/locale/locale/global")
[static] | changes the global locale (public static member function) |
| [classic](locale/classic "cpp/locale/locale/classic")
[static] | obtains a reference to the "C" locale (public static member function) |
### Example
Demonstrates the typical prologue of a locale-sensitive program (cross-platform).
```
#include <iostream>
#include <locale>
int main()
{
std::wcout << "User-preferred locale setting is " << std::locale("").name().c_str() << '\n';
// on startup, the global locale is the "C" locale
std::wcout << 1000.01 << '\n';
// replace the C++ global locale as well as the C locale with the user-preferred locale
std::locale::global(std::locale(""));
// use the new global locale for future wide character output
std::wcout.imbue(std::locale());
// output the same number again
std::wcout << 1000.01 << '\n';
}
```
Possible output:
```
User-preferred locale setting is en_US.UTF8
1000.01
1,000.01
```
### See also
| | |
| --- | --- |
| [use\_facet](use_facet "cpp/locale/use facet") | obtains a facet from a locale (function template) |
| [has\_facet](has_facet "cpp/locale/has facet") | checks if a locale implements a specific facet (function template) |
| [imbue](../io/ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) |
| [getloc](../io/ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) |
cpp std::isgraph(std::locale) std::isgraph(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isgraph( charT ch, const locale& loc );
```
| | |
Checks if the given character classified as a graphic character (i.e. printable, excluding space) by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as graphic, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isgraph( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::graph, ch);
}
```
|
### Example
Demonstrates the use of isgraph() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u2a0c'; // quadruple integral
std::locale loc1("C");
std::cout << "isgraph('⨌', C locale) returned "
<< std::boolalpha << std::isgraph(c, loc1) << '\n';
std::locale loc2("en_US.UTF-8");
std::cout << "isgraph('⨌', Unicode locale) returned "
<< std::boolalpha << std::isgraph(c, loc2) << '\n';
}
```
Output:
```
isgraph('⨌', C locale) returned false
isgraph('⨌', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [isgraph](../string/byte/isgraph "cpp/string/byte/isgraph") | checks if a character is a graphical character (function) |
| [iswgraph](../string/wide/iswgraph "cpp/string/wide/iswgraph") | checks if a wide character is a graphical character (function) |
| programming_docs |
cpp std::islower(std::locale) std::islower(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool islower( charT ch, const locale& loc );
```
| | |
Checks if the given character is classified as a lowercase alphabetic character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as lowercase, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool islower( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::lower, ch);
}
```
|
### Example
Demonstrates the use of islower() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u03c0'; // greek small letter pi
std::locale loc1("C");
std::cout << "islower('π', C locale) returned "
<< std::boolalpha << std::islower(c, loc1) << '\n';
std::locale loc2("en_US.UTF8");
std::cout << "islower('π', Unicode locale) returned "
<< std::boolalpha << std::islower(c, loc2) << '\n';
}
```
Output:
```
islower('π', C locale) returned false
islower('π', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [islower](../string/byte/islower "cpp/string/byte/islower") | checks if a character is lowercase (function) |
| [iswlower](../string/wide/iswlower "cpp/string/wide/iswlower") | checks if a wide character is lowercase (function) |
cpp std::messages std::messages
=============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class messages;
```
| | |
Class template `std::messages` is a standard locale facet that encapsulates retrieval of strings from message catalogs, such as the ones provided by GNU [gettext](http://www.gnu.org/s/gettext/) or by POSIX [catgets](http://pubs.opengroup.org/onlinepubs/9699919799/functions/catgets.html).
The source of the messages is implementation-defined.
![std-messages-inheritance.svg]()
Inheritance diagram.
Two standalone (locale-independent) specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::messages<char>` | accesses narrow string message catalog |
| `std::messages<wchar_t>` | accesses wide string message catalog |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `std::basic_string<CharT>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](messages/messages "cpp/locale/messages/messages") | constructs a new messages facet (public member function) |
| [(destructor)](messages/~messages "cpp/locale/messages/~messages") | destructs a messages facet (protected member function) |
| [open](messages/open "cpp/locale/messages/open") | invokes `do_open` (public member function) |
| [get](messages/get "cpp/locale/messages/get") | invokes `do_get` (public member function) |
| [close](messages/close "cpp/locale/messages/close") | invokes `do_close` (public member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Protected member functions
| | |
| --- | --- |
| [do\_open](messages/open "cpp/locale/messages/open")
[virtual] | opens a named message catalog (virtual protected member function) |
| [do\_get](messages/get "cpp/locale/messages/get")
[virtual] | retrieves a message from an open message catalog (virtual protected member function) |
| [do\_close](messages/close "cpp/locale/messages/close")
[virtual] | closes a message catalog (virtual protected member function) |
Inherited from std::messages\_base
-----------------------------------
| Type | Definition |
| --- | --- |
| `catalog` | `/*unspecified signed integer type*/` |
### See also
| | |
| --- | --- |
| [messages\_base](messages_base "cpp/locale/messages base") | defines messages catalog type (class template) |
| [messages\_byname](messages_byname "cpp/locale/messages byname") | creates a messages facet for the named locale (class template) |
cpp std::isblank(std::locale) std::isblank(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isblank( charT ch, const locale& loc );
```
| | (since C++11) |
Checks if the given character is classified as a blank character by the given locale's ctype facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as a blank character, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isblank( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::blank, ch);
}
```
|
### Example
Demonstrates the use of `isblank()` with different locales (OS-specific).
```
#include <iostream>
#include <locale>
void try_with(wchar_t c, const char* loc)
{
std::wcout << "isblank('" << c << "', locale(\"" << loc << "\")) returned " << std::boolalpha
<< std::isblank(c, std::locale(loc)) << '\n';
}
int main()
{
const wchar_t IDEO_SPACE = L'\u3000'; // Unicode character 'IDEOGRAPHIC SPACE'
try_with(IDEO_SPACE, "C");
try_with(IDEO_SPACE, "en_US.UTF-8");
}
```
Output:
```
isblank(' ', locale("C")) returned false
isblank(' ', locale("en_US.UTF-8")) returned true
```
### See also
| | |
| --- | --- |
| [isblank](../string/byte/isblank "cpp/string/byte/isblank")
(C++11) | checks if a character is a blank character (function) |
| [iswblank](../string/wide/iswblank "cpp/string/wide/iswblank")
(C++11) | checks if a wide character is a blank character (function) |
cpp std::ctype<char> std::ctype<char>
================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<>
class ctype<char>;
```
| | |
This specialization of `[std::ctype](ctype "cpp/locale/ctype")` encapsulates character classification features for type `char`. Unlike general-purpose `[std::ctype](ctype "cpp/locale/ctype")`, which uses virtual functions, this specialization uses table lookup to classify characters (which is generally faster).
The base class `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` implements character classification equivalent to the minimal "C" locale. The classification rules can be extended or modified if constructed with a non-default classification table argument, if constructed as `[std::ctype\_byname](http://en.cppreference.com/w/cpp/locale/ctype_byname)<char>` or as a user-defined derived facet. All `[std::istream](../io/basic_istream "cpp/io/basic istream")` formatted input functions are required to use `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` for character classing during input parsing.
![std-ctype char-inheritance.svg]()
Inheritance diagram.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `char` |
### Member functions
| | |
| --- | --- |
| [(constructor)](ctype_char/ctype "cpp/locale/ctype char/ctype") | constructs a new `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` facet (public member function) |
| [(destructor)](ctype_char/~ctype "cpp/locale/ctype char/~ctype") | destructs a `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` facet (protected member function) |
| [table](ctype_char/table "cpp/locale/ctype char/table") | obtains the character classification table (public member function) |
| [classic\_table](ctype_char/classic_table "cpp/locale/ctype char/classic table")
[static] | obtains the "C" locale character classification table (public static member function) |
| [is](ctype_char/is "cpp/locale/ctype char/is") | classifies a character or a character sequence, using the classification table (public member function) |
| [scan\_is](ctype_char/scan_is "cpp/locale/ctype char/scan is") | locates the first character in a sequence that conforms to given classification, using the classification table (public member function) |
| [scan\_not](ctype_char/scan_not "cpp/locale/ctype char/scan not") | locates the first character in a sequence that fails given classification, using the classification table (public member function) |
| [toupper](ctype/toupper "cpp/locale/ctype/toupper") | invokes `do_toupper` (public member function of `std::ctype<CharT>`) |
| [tolower](ctype/tolower "cpp/locale/ctype/tolower") | invokes `do_tolower` (public member function of `std::ctype<CharT>`) |
| [widen](ctype/widen "cpp/locale/ctype/widen") | invokes `do_widen` (public member function of `std::ctype<CharT>`) |
| [narrow](ctype/narrow "cpp/locale/ctype/narrow") | invokes `do_narrow` (public member function of `std::ctype<CharT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_toupper](ctype/toupper "cpp/locale/ctype/toupper")
[virtual] | converts a character or characters to uppercase (virtual protected member function of `std::ctype<CharT>`) |
| [do\_tolower](ctype/tolower "cpp/locale/ctype/tolower")
[virtual] | converts a character or characters to lowercase (virtual protected member function of `std::ctype<CharT>`) |
| [do\_widen](ctype/widen "cpp/locale/ctype/widen")
[virtual] | converts a character or characters from `char` to `charT` (virtual protected member function of `std::ctype<CharT>`) |
| [do\_narrow](ctype/narrow "cpp/locale/ctype/narrow")
[virtual] | converts a character or characters from `charT` to `char` (virtual protected member function of `std::ctype<CharT>`) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id
[static] | *id* of the locale (public static member constant) |
| static const std::size\_t table\_size
[static] | size of the classification table, at least 256 (public static member constant) |
Inherited from std::ctype\_base
--------------------------------
### Member types
| Type | Definition |
| --- | --- |
| `mask` | unspecified bitmask type (enumeration, integer type, or bitset) |
### Member constants
| | |
| --- | --- |
| space
[static] | the value of `mask` identifying whitespace character classification (public static member constant) |
| print
[static] | the value of `mask` identifying printable character classification (public static member constant) |
| cntrl
[static] | the value of `mask` identifying control character classification (public static member constant) |
| upper
[static] | the value of `mask` identifying uppercase character classification (public static member constant) |
| lower
[static] | the value of `mask` identifying lowercase character classification (public static member constant) |
| alpha
[static] | the value of `mask` identifying alphabetic character classification (public static member constant) |
| digit
[static] | the value of `mask` identifying digit character classification (public static member constant) |
| punct
[static] | the value of `mask` identifying punctuation character classification (public static member constant) |
| xdigit
[static] | the value of `mask` identifying hexadecimal digit character classification (public static member constant) |
| blank
[static] (C++11) | the value of `mask` identifying blank character classification (public static member constant) |
| alnum
[static] | `alpha | digit` (public static member constant) |
| graph
[static] | `alnum | punct` (public static member constant) |
### Example
The following example demonstrates modification of ctype<char> to tokenize comma-separated values.
```
#include <iostream>
#include <vector>
#include <locale>
#include <sstream>
// This ctype facet classifies commas and endlines as whitespace
struct csv_whitespace : std::ctype<char> {
static const mask* make_table()
{
// make a copy of the "C" locale table
static std::vector<mask> v(classic_table(), classic_table() + table_size);
v[','] |= space; // comma will be classified as whitespace
v[' '] &= ~space; // space will not be classified as whitespace
return &v[0];
}
csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};
int main()
{
std::string in = "Column 1,Column 2,Column 3\n123,456,789";
std::string token;
std::cout << "default locale:\n";
std::istringstream s1(in);
while(s1 >> token)
std::cout << " " << token << '\n';
std::cout << "locale with modified ctype:\n";
std::istringstream s2(in);
s2.imbue(std::locale(s2.getloc(), new csv_whitespace));
while(s2 >> token)
std::cout << " " << token<< '\n';
}
```
Output:
```
default locale:
Column
1,Column
2,Column
3
123,456,789
locale with modified ctype:
Column 1
Column 2
Column 3
123
456
789
```
### See also
| | |
| --- | --- |
| [ctype](ctype "cpp/locale/ctype") | defines character classification tables (class template) |
| [ctype\_base](ctype_base "cpp/locale/ctype base") | defines character classification categories (class template) |
| [ctype\_byname](ctype_byname "cpp/locale/ctype byname") | creates a ctype facet for the named locale (class template) |
cpp std::ctype_byname std::ctype\_byname
==================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class ctype_byname : public std::ctype<CharT>;
```
| | |
`std::ctype_byname` is a `[std::ctype](ctype "cpp/locale/ctype")` facet which encapsulates character classification rules of the locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::ctype_byname<char>` | provides narrow character classification. This specialization uses table lookup for character classification |
| `std::ctype_byname<wchar_t>` | provides wide character classification |
### Member types
| Member type | Definition |
| --- | --- |
| `mask` | `ctype<CharT>::mask` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `ctype_byname` facet (public member function) |
| **(destructor)** | destroys a `ctype_byname` facet (protected member function) |
std::ctype\_byname::ctype\_byname
----------------------------------
| | | |
| --- | --- | --- |
|
```
explicit ctype_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit ctype_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::ctype_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::ctype\_byname::~ctype\_byname
-----------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~ctype_byname();
```
| | |
Destroys the facet.
Inherited from std::ctype<CharT>
---------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
### Member objects
| Member name | Type |
| --- | --- |
| static std::locale::id id
[static] | *id* of the locale (public static member constant) |
| if `CharT` is `char`, the following member of `std::ctype<char>` is inherited |
| static const std::size\_t table\_size
[static] | size of the classification table, at least 256 (public static member constant) |
### Member functions
| | |
| --- | --- |
| [is](ctype/is "cpp/locale/ctype/is") | invokes `do_is` (public member function of `std::ctype<CharT>`) |
| [scan\_is](ctype/scan_is "cpp/locale/ctype/scan is") | invokes `do_scan_is` (public member function of `std::ctype<CharT>`) |
| [scan\_not](ctype/scan_not "cpp/locale/ctype/scan not") | invokes `do_scan_not` (public member function of `std::ctype<CharT>`) |
| [toupper](ctype/toupper "cpp/locale/ctype/toupper") | invokes `do_toupper` (public member function of `std::ctype<CharT>`) |
| [tolower](ctype/tolower "cpp/locale/ctype/tolower") | invokes `do_tolower` (public member function of `std::ctype<CharT>`) |
| [widen](ctype/widen "cpp/locale/ctype/widen") | invokes `do_widen` (public member function of `std::ctype<CharT>`) |
| [narrow](ctype/narrow "cpp/locale/ctype/narrow") | invokes `do_narrow` (public member function of `std::ctype<CharT>`) |
| if `CharT` is `char`, the following members of `std::ctype<char>` are inherited |
| [table](ctype_char/table "cpp/locale/ctype char/table") | obtains the character classification table (public member function of `std::ctype<char>`) |
| [classic\_table](ctype_char/classic_table "cpp/locale/ctype char/classic table")
[static] | obtains the "C" locale character classification table (public static member function of `std::ctype<char>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_toupper](ctype/toupper "cpp/locale/ctype/toupper")
[virtual] | converts a character or characters to uppercase (virtual protected member function of `std::ctype<CharT>`) |
| [do\_tolower](ctype/tolower "cpp/locale/ctype/tolower")
[virtual] | converts a character or characters to lowercase (virtual protected member function of `std::ctype<CharT>`) |
| [do\_widen](ctype/widen "cpp/locale/ctype/widen")
[virtual] | converts a character or characters from `char` to `charT` (virtual protected member function of `std::ctype<CharT>`) |
| [do\_narrow](ctype/narrow "cpp/locale/ctype/narrow")
[virtual] | converts a character or characters from `charT` to `char` (virtual protected member function of `std::ctype<CharT>`) |
| if `CharT` is `char`, the following members of `[std::ctype](ctype "cpp/locale/ctype")` are NOT inherited |
| [do\_is](ctype/is "cpp/locale/ctype/is")
[virtual] | classifies a character or a character sequence (virtual protected member function of `std::ctype<CharT>`) |
| [do\_scan\_is](ctype/scan_is "cpp/locale/ctype/scan is")
[virtual] | locates the first character in a sequence that conforms to given classification (virtual protected member function of `std::ctype<CharT>`) |
| [do\_scan\_not](ctype/scan_not "cpp/locale/ctype/scan not")
[virtual] | locates the first character in a sequence that fails given classification (virtual protected member function of `std::ctype<CharT>`) |
Inherited from std::ctype\_base
--------------------------------
### Member types
| Type | Definition |
| --- | --- |
| `mask` | unspecified bitmask type (enumeration, integer type, or bitset) |
### Member constants
| | |
| --- | --- |
| space
[static] | the value of `mask` identifying whitespace character classification (public static member constant) |
| print
[static] | the value of `mask` identifying printable character classification (public static member constant) |
| cntrl
[static] | the value of `mask` identifying control character classification (public static member constant) |
| upper
[static] | the value of `mask` identifying uppercase character classification (public static member constant) |
| lower
[static] | the value of `mask` identifying lowercase character classification (public static member constant) |
| alpha
[static] | the value of `mask` identifying alphabetic character classification (public static member constant) |
| digit
[static] | the value of `mask` identifying digit character classification (public static member constant) |
| punct
[static] | the value of `mask` identifying punctuation character classification (public static member constant) |
| xdigit
[static] | the value of `mask` identifying hexadecimal digit character classification (public static member constant) |
| blank
[static] (C++11) | the value of `mask` identifying blank character classification (public static member constant) |
| alnum
[static] | `alpha | digit` (public static member constant) |
| graph
[static] | `alnum | punct` (public static member constant) |
### Notes
The explicit specialization [`std::ctype_byname<char>`](ctype_byname_char "cpp/locale/ctype byname char") was listed as a separate entry in the header file `<locale>` until C++11. it was removed in C++11 as [defect #1298](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#1298), but it remains a required specialization, just like `std::ctype_byname<wchar_t>`.
### Example
```
#include <iostream>
#include <locale>
int main()
{
wchar_t c = L'\u00de'; // capital letter thorn
std::locale loc("C");
std::cout << "isupper('Þ', C locale) returned "
<< std::boolalpha << std::isupper(c, loc) << '\n';
loc = std::locale(loc, new std::ctype_byname<wchar_t>("en_US.utf8"));
std::cout << "isupper('Þ', C locale with Unicode ctype) returned "
<< std::boolalpha << std::isupper(c, loc) << '\n';
}
```
Output:
```
isupper('Þ', C locale) returned false
isupper('Þ', C locale with Unicode ctype) returned true
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 16](https://cplusplus.github.io/LWG/issue16) | C++98 | the definition of the explicit specialization `std::ctype_byname<char>`misspecified the name and parameter list of `do_narrow` | corrected |
### See also
| | |
| --- | --- |
| [ctype](ctype "cpp/locale/ctype") | defines character classification tables (class template) |
| [ctype<char>](ctype_char "cpp/locale/ctype char") | specialization of `[std::ctype](ctype "cpp/locale/ctype")` for type `char` (class template specialization) |
| programming_docs |
cpp std::lconv std::lconv
==========
| Defined in header `[<clocale>](../header/clocale "cpp/header/clocale")` | | |
| --- | --- | --- |
|
```
struct lconv;
```
| | |
The class `std::lconv` contains numeric and monetary formatting rules as defined by a C locale. Objects of this struct may be obtained with `[std::localeconv](localeconv "cpp/locale/localeconv")`. The members of `std::lconv` are values of type `char` and of type `char*`. Each `char*` member except `decimal_point` may be pointing at a null character (that is, at an empty C-string). The members of type `char` are all non-negative numbers, any of which may be `[CHAR\_MAX](../types/climits "cpp/types/climits")` if the corresponding value is not available in the current C locale.
### Member objects
#### Non-monetary numeric formatting parameters
| | |
| --- | --- |
| char\* decimal\_point | the character used as the decimal point (public member object) |
| char\* thousands\_sep | the character used to separate groups of digits before the decimal point (public member object) |
| char\* grouping | a string whose elements indicate the sizes of digit groups (public member object) |
#### Monetary numeric formatting parameters
| | |
| --- | --- |
| char\* mon\_decimal\_point | the character used as the decimal point (public member object) |
| char\* mon\_thousands\_sep | the character used to separate groups of digits before the decimal point (public member object) |
| char\* mon\_grouping | a string whose elements indicate the sizes of digit groups (public member object) |
| char\* positive\_sign | a string used to indicate non-negative monetary quantity (public member object) |
| char\* negative\_sign | a string used to indicate negative monetary quantity (public member object) |
#### Local monetary numeric formatting parameters
| | |
| --- | --- |
| char\* currency\_symbol | the symbol used for currency in the current C locale (public member object) |
| char frac\_digits | the number of digits after the decimal point to display in a monetary quantity (public member object) |
| char p\_cs\_precedes | `1` if currency\_symbol is placed before non-negative value, `0` if after (public member object) |
| char n\_cs\_precedes | `1` if currency\_symbol is placed before negative value, `0` if after (public member object) |
| char p\_sep\_by\_space | indicates the separation of `currency_symbol`, `positive_sign`, and the non-negative monetary value (public member object) |
| char n\_sep\_by\_space | indicates the separation of `currency_symbol`, `negative_sign`, and the negative monetary value (public member object) |
| char p\_sign\_posn | indicates the position of `positive_sign` in a non-negative monetary value (public member object) |
| char n\_sign\_posn | indicates the position of `negative_sign` in a negative monetary value (public member object) |
#### International monetary numeric formatting parameters
| | |
| --- | --- |
| char\* int\_curr\_symbol | the string used as international currency name in the current C locale (public member object) |
| char int\_frac\_digits | the number of digits after the decimal point to display in an international monetary quantity (public member object) |
| char int\_p\_cs\_precedes
(C++11) | `1` if int\_curr\_symbol is placed before non-negative international monetary value, `0` if after (public member object) |
| char int\_n\_cs\_precedes
(C++11) | `1` if int\_curr\_symboll is placed before negative international monetary value, `0` if after (public member object) |
| char int\_p\_sep\_by\_space
(C++11) | indicates the separation of `int_curr_symbol`, `positive_sign`, and the non-negative international monetary value (public member object) |
| char int\_n\_sep\_by\_space
(C++11) | indicates the separation of `int_curr_symbol`, `negative_sign`, and the negative international monetary value (public member object) |
| char int\_p\_sign\_posn
(C++11) | indicates the position of `positive_sign` in a non-negative international monetary value (public member object) |
| char int\_n\_sign\_posn
(C++11) | indicates the position of `negative_sign` in a negative international monetary value (public member object) |
The characters of the C-strings pointed to by `grouping` and `mon_grouping` are interpreted according to their numeric values. When the terminating `'\0'` is encountered, the last value seen is assumed to repeat for the remainder of digits. If `[CHAR\_MAX](../types/climits "cpp/types/climits")` is encountered, no further digits are grouped. the typical grouping of three digits at a time is `"\003"`.
The values of `p_sep_by_space`, `n_sep_by_space`, `int_p_sep_by_space`, `int_n_sep_by_space` are interpreted as follows:
| | |
| --- | --- |
| 0 | no space separates the currency symbol and the value |
| 1 | sign sticks to the currency symbol, value is separated by a space |
| 2 | sign sticks to the value. Currency symbol is separated by a space |
The values of `p_sign_posn`, `n_sign_posn`, `int_p_sign_posn`, `int_n_sign_posn` are interpreted as follows:
| | |
| --- | --- |
| 0 | parentheses around the value and the currency symbol are used to represent the sign |
| 1 | sign before the value and the currency symbol |
| 2 | sign after the value and the currency symbol |
| 3 | sign before the currency symbol |
| 4 | sign after the currency symbol |
### Example
```
#include <clocale>
#include <iostream>
int main()
{
std::setlocale(LC_ALL, "ja_JP.UTF-8");
std::lconv* lc = std::localeconv();
std::cout << "Japanese currency symbol: " << lc->currency_symbol
<< '(' << lc->int_curr_symbol << ")\n";
}
```
Output:
```
Japanese currency symbol: ¥(JPY )
```
### See also
| | |
| --- | --- |
| [localeconv](localeconv "cpp/locale/localeconv") | queries numeric and monetary formatting details of the current locale (function) |
| [numpunct](numpunct "cpp/locale/numpunct") | defines numeric punctuation rules (class template) |
| [moneypunct](moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](money_get "cpp/locale/money get")` and `[std::money\_put](money_put "cpp/locale/money put")` (class template) |
| [C documentation](https://en.cppreference.com/w/c/locale/lconv "c/locale/lconv") for `lconv` |
cpp std::isprint(std::locale) std::isprint(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isprint( charT ch, const locale& loc );
```
| | |
Checks if the given character classified as a printable character (including space) by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as printable, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isprint( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::print, ch);
}
```
|
### Example
Demonstrates the use of isprint() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u2122'; // trademark sign
std::locale loc1("C");
std::cout << "isprint('™', C locale) returned "
<< std::boolalpha << std::isprint(c, loc1) << '\n';
std::locale loc2("en_US.UTF-8");
std::cout << "isprint('™', Unicode locale) returned "
<< std::boolalpha << std::isprint(c, loc2) << '\n';
}
```
Output:
```
isprint('™', C locale) returned false
isprint('™', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [isprint](../string/byte/isprint "cpp/string/byte/isprint") | checks if a character is a printing character (function) |
| [iswprint](../string/wide/iswprint "cpp/string/wide/iswprint") | checks if a wide character is a printing character (function) |
cpp std::wstring_convert std::wstring\_convert
=====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class Codecvt,
class Elem = wchar_t,
class Wide_alloc = std::allocator<Elem>,
class Byte_alloc = std::allocator<char> >
class wstring_convert;
```
| | (since C++11) (deprecated in C++17) |
Class template `std::wstring_convert` performs conversions between byte string `[std::string](../string/basic_string "cpp/string/basic string")` and wide string `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<Elem>`, using an individual code conversion facet `Codecvt`. `std::wstring_convert` assumes ownership of the conversion facet, and cannot use a facet managed by a locale. The standard facets suitable for use with `std::wstring_convert` are `[std::codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")` for UTF-8/UCS2 and UTF-8/UCS4 conversions and `[std::codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")` for UTF-8/UTF-16 conversions.
### Member types
| Member type | Definition |
| --- | --- |
| `byte_string` | `std::basic_string<char, char_traits<char>, Byte_alloc>` |
| `wide_string` | `std::basic_string<Elem, char_traits<Elem>, Wide_alloc>` |
| `state_type` | `Codecvt::state_type` |
| `int_type` | `wide_string::traits_type::int_type` |
### Member functions
| | |
| --- | --- |
| [(constructor)](wstring_convert/wstring_convert "cpp/locale/wstring convert/wstring convert") | constructs a new wstring\_convert (public member function) |
| operator= | the copy assignment operator is deleted (public member function) |
| [(destructor)](wstring_convert/~wstring_convert "cpp/locale/wstring convert/~wstring convert") | destructs the wstring\_convert and its conversion facet (public member function) |
| [from\_bytes](wstring_convert/from_bytes "cpp/locale/wstring convert/from bytes") | converts a byte string into a wide string (public member function) |
| [to\_bytes](wstring_convert/to_bytes "cpp/locale/wstring convert/to bytes") | converts a wide string into a byte string (public member function) |
| [converted](wstring_convert/converted "cpp/locale/wstring convert/converted") | returns the number of characters successfully converted (public member function) |
| [state](wstring_convert/state "cpp/locale/wstring convert/state") | returns the current conversion state (public member function) |
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | [`codecvt`](codecvt "cpp/locale/codecvt")<char16\_t, char, mbstate\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char16\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char32\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char16\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char16\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | [`codecvt`](codecvt "cpp/locale/codecvt")<char32\_t, char, mbstate\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char32\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(non-Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char32\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<[`codecvt`](codecvt "cpp/locale/codecvt") <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [wbuffer\_convert](wbuffer_convert "cpp/locale/wbuffer convert")
(C++11)(deprecated in C++17) | performs conversion between a byte stream buffer and a wide stream buffer (class template) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
cpp std::tolower(std::locale) std::tolower(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
charT tolower( charT ch, const locale& loc );
```
| | |
Converts the character `ch` to lowercase if possible, using the conversion rules specified by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns the lowercase form of `ch` if one is listed in the locale, otherwise return `ch` unchanged.
### Notes
Only 1:1 character mapping can be performed by this function, e.g. the Greek uppercase letter 'Σ' has two lowercase forms, depending on the position in a word: 'σ' and 'ς'. A call to `std::tolower` cannot be used to obtain the correct lowercase form in this case.
### Possible implementation
| |
| --- |
|
```
template< class charT >
charT tolower( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).tolower(ch);
}
```
|
### Example
```
#include <iostream>
#include <cwctype>
#include <locale>
int main()
{
wchar_t c = L'\u0190'; // Latin capital open E ('Ɛ')
std::cout << std::hex << std::showbase;
std::cout << "in the default locale, tolower(" << (std::wint_t)c << ") = "
<< std::tolower(c, std::locale()) << '\n';
std::cout << "in Unicode locale, tolower(" << (std::wint_t)c << ") = "
<< std::tolower(c, std::locale("en_US.utf8")) << '\n';
}
```
Output:
```
in the default locale, tolower(0x190) = 0x190
in Unicode locale, tolower(0x190) = 0x25b
```
### See also
| | |
| --- | --- |
| [toupper(std::locale)](toupper "cpp/locale/toupper") | converts a character to uppercase using the ctype facet of a locale (function template) |
| [tolower](../string/byte/tolower "cpp/string/byte/tolower") | converts a character to lowercase (function) |
| [towlower](../string/wide/towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) |
cpp std::codecvt_utf16 std::codecvt\_utf16
===================
| Defined in header `[<codecvt>](../header/codecvt "cpp/header/codecvt")` | | |
| --- | --- | --- |
|
```
template< class Elem,
unsigned long Maxcode = 0x10ffff,
std::codecvt_mode Mode = (std::codecvt_mode)0 >
class codecvt_utf16 : public std::codecvt<Elem, char, std::mbstate_t>;
```
| | (since C++11) (deprecated in C++17) |
`std::codecvt_utf16` is a `[std::codecvt](codecvt "cpp/locale/codecvt")` facet which encapsulates conversion between a UTF-16 encoded byte string and UCS2 or UTF-32 character string (depending on the type of `Elem`). This codecvt facet can be used to read and write UTF-16 files in binary mode.
### Template Parameters
| | | |
| --- | --- | --- |
| Elem | - | either `char16_t`, `char32_t`, or `wchar_t` |
| Maxcode | - | the largest value of `Elem` that this facet will read or write without error |
| Mode | - | a constant of type `[std::codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `codecvt_utf16` facet (public member function) |
| **(destructor)** | destroys a `codecvt_utf16` facet (public member function) |
std::codecvt\_utf16::codecvt\_utf16
------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit codecvt_utf16( std::size_t refs = 0 );
```
| | |
Constructs a new `std::codecvt_utf16` facet, passes the initial reference counter `refs` to the base class.
### Parameters
| | | |
| --- | --- | --- |
| refs | - | the number of references that link to the facet |
std::codecvt\_utf16::~codecvt\_utf16
-------------------------------------
| | | |
| --- | --- | --- |
|
```
~codecvt_utf16();
```
| | |
Destroys the facet. Unlike the locale-managed facets, this facet's destructor is public.
Inherited from [std::codecvt](codecvt "cpp/locale/codecvt")
-------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `intern_type` | `internT` |
| `extern_type` | `externT` |
| `state_type` | `stateT` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [out](codecvt/out "cpp/locale/codecvt/out") | invokes `do_out` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [in](codecvt/in "cpp/locale/codecvt/in") | invokes `do_in` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [unshift](codecvt/unshift "cpp/locale/codecvt/unshift") | invokes `do_unshift` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [encoding](codecvt/encoding "cpp/locale/codecvt/encoding") | invokes `do_encoding` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv") | invokes `do_always_noconv` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [length](codecvt/length "cpp/locale/codecvt/length") | invokes `do_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [max\_length](codecvt/max_length "cpp/locale/codecvt/max length") | invokes `do_max_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_out](codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_in](codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_unshift](codecvt/unshift "cpp/locale/codecvt/unshift")
[virtual] | generates the termination character sequence of `ExternT` characters for incomplete conversion (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_encoding](codecvt/encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv")
[virtual] | tests if the facet encodes an identity conversion for all valid argument values (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_length](codecvt/length "cpp/locale/codecvt/length")
[virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_max\_length](codecvt/max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
Inherited from [std::codecvt\_base](codecvt_base "cpp/locale/codecvt base")
-----------------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Notes
Although the standard requires that this facet works with UCS2 when the size of `Elem` is 16 bits, some implementations use UTF-16 instead, making this a non-converting locale. The term "UCS2" was deprecated and removed from the Unicode standard.
### Example
The following example demonstrates decoding of UTF-16le file on a system with 32-bit `wchar_t`. On a system with 16-bit `wchar_t`, decoding of the third character will fail because `std::codecvt_utf16<char16_t>` produces UCS2, not UTF-16.
```
#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
void prepare_file()
{
// UTF-16le data (if host system is little-endian)
char16_t utf16le[4] ={0x007a, // latin small letter 'z' U+007a
0x6c34, // CJK ideograph "water" U+6c34
0xd834, 0xdd0b}; // musical sign segno U+1d10b
// store in a file
std::ofstream fout("text.txt");
fout.write( reinterpret_cast<char*>(utf16le), sizeof utf16le);
}
int main()
{
prepare_file();
// open as a byte stream
std::wifstream fin("text.txt", std::ios::binary);
// apply facet
fin.imbue(std::locale(fin.getloc(),
new std::codecvt_utf16<wchar_t, 0x10ffff, std::little_endian>));
for (wchar_t c; fin.get(c); )
std::cout << std::showbase << std::hex << c << '\n';
}
```
Output:
```
0x7a
0x6c34
0x1d10b
```
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | [`codecvt`](codecvt "cpp/locale/codecvt")<char16\_t, char, mbstate\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char16\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<char32\_t>[`codecvt_utf8_utf16`](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char16\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(Windows). | **`codecvt_utf16`**<char16\_t> **`codecvt_utf16`**<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | [`codecvt`](codecvt "cpp/locale/codecvt")<char32\_t, char, mbstate\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char32\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(non-Windows). | **`codecvt_utf16`**<char32\_t> **`codecvt_utf16`**<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<[`codecvt`](codecvt "cpp/locale/codecvt") <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
| [codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")
(C++11)(deprecated in C++17) | tags to alter behavior of the standard codecvt facets (enum) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf8\_utf16](codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")
(C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) |
| programming_docs |
cpp std::moneypunct_byname std::moneypunct\_byname
=======================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT, bool Intl = false >
class moneypunct_byname : public std::moneypunct<CharT, Intl>;
```
| | |
`std::moneypunct_byname` is a `[std::moneypunct](moneypunct "cpp/locale/moneypunct")` facet which encapsulates monetary formatting preferences of a locale specified at its construction.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::moneypunct_byname<char, Intl>` | locale-specific `[std::moneypunct](moneypunct "cpp/locale/moneypunct")` facet for narrow character I/O |
| `std::moneypunct_byname<wchar_t, Intl>` | locale-specific `[std::moneypunct](moneypunct "cpp/locale/moneypunct")` facet for wide character I/O |
### Member types
| Member type | Definition |
| --- | --- |
| `pattern` | `[std::money\_base::pattern](money_base "cpp/locale/money base")` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `moneypunct_byname` facet (public member function) |
| **(destructor)** | destroys a `moneypunct_byname` facet (protected member function) |
std::moneypunct\_byname::moneypunct\_byname
--------------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit moneypunct_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit moneypunct_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::moneypunct_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::moneypunct\_byname::~moneypunct\_byname
---------------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~moneypunct_byname();
```
| | |
Destroys the facet.
Inherited from [std::moneypunct](moneypunct "cpp/locale/moneypunct")
----------------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` |
### Member functions
| | |
| --- | --- |
| [decimal\_point](moneypunct/decimal_point "cpp/locale/moneypunct/decimal point") | invokes `do_decimal_point` (public member function of `std::moneypunct<CharT,International>`) |
| [thousands\_sep](moneypunct/thousands_sep "cpp/locale/moneypunct/thousands sep") | invokes `do_thousands_sep` (public member function of `std::moneypunct<CharT,International>`) |
| [grouping](moneypunct/grouping "cpp/locale/moneypunct/grouping") | invokes `do_grouping` (public member function of `std::moneypunct<CharT,International>`) |
| [curr\_symbol](moneypunct/curr_symbol "cpp/locale/moneypunct/curr symbol") | invokes `do_curr_symbol` (public member function of `std::moneypunct<CharT,International>`) |
| [positive\_signnegative\_sign](moneypunct/positive_sign "cpp/locale/moneypunct/positive sign") | invokes `do_positive_sign` or `do_negative_sign` (public member function of `std::moneypunct<CharT,International>`) |
| [frac\_digits](moneypunct/frac_digits "cpp/locale/moneypunct/frac digits") | invokes `do_frac_digits` (public member function of `std::moneypunct<CharT,International>`) |
| [pos\_formatneg\_format](moneypunct/pos_format "cpp/locale/moneypunct/pos format") | invokes `do_pos_format`/`do_neg_format` (public member function of `std::moneypunct<CharT,International>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_decimal\_point](moneypunct/decimal_point "cpp/locale/moneypunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_thousands\_sep](moneypunct/thousands_sep "cpp/locale/moneypunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_grouping](moneypunct/grouping "cpp/locale/moneypunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_curr\_symbol](moneypunct/curr_symbol "cpp/locale/moneypunct/curr symbol")
[virtual] | provides the string to use as the currency identifier (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_positive\_signdo\_negative\_sign](moneypunct/positive_sign "cpp/locale/moneypunct/positive sign")
[virtual] | provides the string to indicate a positive or negative value (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_frac\_digits](moneypunct/frac_digits "cpp/locale/moneypunct/frac digits")
[virtual] | provides the number of digits to display after the decimal point (virtual protected member function of `std::moneypunct<CharT,International>`) |
| [do\_pos\_formatdo\_neg\_format](moneypunct/pos_format "cpp/locale/moneypunct/pos format")
[virtual] | provides the formatting pattern for currency values (virtual protected member function of `std::moneypunct<CharT,International>`) |
### Member constants
| Member | Definition |
| --- | --- |
| const bool `intl` (static) | `International` |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
Inherited from [std::money\_base](money_base "cpp/locale/money base")
----------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum part { none, space, symbol, sign, value };` | unscoped enumeration type |
| `struct pattern { char field[4]; };` | the monetary format type |
| Enumeration constant | Definition |
| --- | --- |
| `none` | whitespace is permitted but not required except in the last position, where whitespace is not permitted |
| `space` | one or more whitespace characters are required |
| `symbol` | the sequence of characters returned by moneypunct::curr\_symbol is required |
| `sign` | the first of the characters returned by moneypunct::positive\_sign or moneypunct::negative\_sign is required |
| `value` | the absolute numeric monetary value is required |
### Example
This example demonstrates how to apply monetary formatting rules of another language without changing the rest of the locale.
```
#include <iostream>
#include <iomanip>
#include <locale>
int main()
{
long double mon = 1234567;
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wcout << L"american locale : " << std::showbase
<< std::put_money(mon) << '\n';
std::wcout.imbue(std::locale(std::wcout.getloc(),
new std::moneypunct_byname<wchar_t>("ru_RU.utf8")));
std::wcout << L"american locale with russian moneypunct: "
<< std::put_money(mon) << '\n';
}
```
Output:
```
american locale : $12,345.67
american locale with russian moneypunct: 12 345.67 руб
```
### See also
| | |
| --- | --- |
| [moneypunct](moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](money_get "cpp/locale/money get")` and `[std::money\_put](money_put "cpp/locale/money put")` (class template) |
cpp std::num_put std::num\_put
=============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class OutputIt = std::ostreambuf_iterator<CharT>
> class num_put;
```
| | |
Class `std::num_put` encapsulates the rules for formatting numeric values as strings. Specifically, the types `bool`, `long`, `unsigned long`, `long long`, `unsigned long long`, `double`, `long double`, `void*`, and of all types implicitly convertible to these (such as `int` or `float`) are supported. The standard formatting output operators (such as `cout << n;`) use the `std::num_put` facet of the I/O stream's locale to generate text representation of numbers.
![std-num put-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::num_put<char>` | creates narrow string representations of numbers |
| `std::num_put<wchar_t>` | creates wide string representations of numbers |
| `std::num_put<char, OutputIt>` | creates narrow string representations of numbers using custom output iterator |
| `std::num_put<wchar_t, OutputIt>` | creates wide string representations of numbers using custom output iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `OutputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](num_put/num_put "cpp/locale/num put/num put") | constructs a new num\_put facet (public member function) |
| [(destructor)](num_put/~num_put "cpp/locale/num put/~num put") | destructs a num\_put facet (protected member function) |
| [put](num_put/put "cpp/locale/num put/put") | invokes `do_put` (public member function) |
### Protected member functions
| | |
| --- | --- |
| [do\_put](num_put/put "cpp/locale/num put/put")
[virtual] | formats a number and writes to output stream (virtual protected member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Example
```
#include <iostream>
#include <locale>
#include <string>
#include <iterator>
int main()
{
double n = 1234567.89;
std::cout.imbue(std::locale("de_DE"));
std::cout << "Direct conversion to string:\n"
<< std::to_string(n) << '\n'
<< "Output using a german locale:\n"
<< std::fixed << n << '\n'
<< "Output using an american locale:\n";
// use the facet directly
std::cout.imbue(std::locale("en_US.UTF-8"));
auto& f = std::use_facet<std::num_put<char>>(std::cout.getloc());
f.put(std::ostreambuf_iterator<char>(std::cout), std::cout, ' ', n);
std::cout << '\n';
}
```
Output:
```
Direct conversion to string:
1234567.890000
Output using a german locale:
1.234.567,890000
Output using an american locale:
1,234,567.890000
```
### See also
| | |
| --- | --- |
| [numpunct](numpunct "cpp/locale/numpunct") | defines numeric punctuation rules (class template) |
| [num\_get](num_get "cpp/locale/num get") | parses numeric values from an input character sequence (class template) |
| [to\_string](../string/basic_string/to_string "cpp/string/basic string/to string")
(C++11) | converts an integral or floating point value to `string` (function) |
| [to\_wstring](../string/basic_string/to_wstring "cpp/string/basic string/to wstring")
(C++11) | converts an integral or floating point value to `wstring` (function) |
cpp std::isalnum(std::locale) std::isalnum(std::locale)
=========================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class charT >
bool isalnum( charT ch, const locale& loc );
```
| | |
Checks if the given character classified as an alphanumeric character by the given locale's `[std::ctype](ctype "cpp/locale/ctype")` facet.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character |
| loc | - | locale |
### Return value
Returns `true` if the character is classified as alphanumeric, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template< class charT >
bool isalnum( charT ch, const std::locale& loc ) {
return std::use_facet<std::ctype<charT>>(loc).is(std::ctype_base::alnum, ch);
}
```
|
### Example
Demonstrates the use of isalnum() with different locales (OS-specific).
```
#include <iostream>
#include <locale>
int main()
{
const wchar_t c = L'\u2135'; // mathematical symbol aleph
std::locale loc1("C");
std::cout << "isalnum('ℵ', C locale) returned "
<< std::boolalpha << std::isalnum(c, loc1) << '\n';
std::locale loc2("en_US.UTF-8");
std::cout << "isalnum('ℵ', Unicode locale) returned "
<< std::boolalpha << std::isalnum(c, loc2) << '\n';
}
```
Output:
```
isalnum('ℵ', C locale) returned false
isalnum('ℵ', Unicode locale) returned true
```
### See also
| | |
| --- | --- |
| [isalnum](../string/byte/isalnum "cpp/string/byte/isalnum") | checks if a character is alphanumeric (function) |
| [iswalnum](../string/wide/iswalnum "cpp/string/wide/iswalnum") | checks if a wide character is alphanumeric (function) |
cpp std::collate_byname std::collate\_byname
====================
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class CharT >
class collate_byname : public std::collate<CharT>;
```
| | |
`std::collate_byname` is a `[std::collate](collate "cpp/locale/collate")` facet which encapsulates locale-specific collation (comparison) and hashing of strings. Just like `[std::collate](collate "cpp/locale/collate")`, it can be imbued in `[std::regex](../regex/basic_regex "cpp/regex/basic regex")` and applied, by means of `std::locale::operator()`, directly to all standard algorithms that expect a string comparison predicate.
Two specializations are provided by the standard library.
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::collate_byname<char>` | locale-specific collation of multibyte strings |
| `std::collate_byname<wchar_t>` | locale-specific collation of wide strings |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `collate_byname` facet (public member function) |
| **(destructor)** | destroys a `collate_byname` facet (protected member function) |
std::collate\_byname::collate\_byname
--------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit collate_byname( const char* name, std::size_t refs = 0 );
```
| | |
|
```
explicit collate_byname( const std::string& name, std::size_t refs = 0 );
```
| | (since C++11) |
Constructs a new `std::collate_byname` facet for a locale with `name`.
`refs` is used for resource management: if `refs == 0`, the implementation destroys the facet, when the last `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)` object holding it is destroyed. Otherwise, the object is not destroyed.
### Parameters
| | | |
| --- | --- | --- |
| name | - | the name of the locale |
| refs | - | the number of references that link to the facet |
std::collate\_byname::~collate\_byname
---------------------------------------
| | | |
| --- | --- | --- |
|
```
protected:
~collate_byname();
```
| | |
Destroys the facet.
Inherited from [std::collate](collate "cpp/locale/collate")
-------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `charT` |
| `string_type` | `std::basic_string<charT>` |
### Member functions
| | |
| --- | --- |
| [compare](collate/compare "cpp/locale/collate/compare") | invokes `do_compare` (public member function of `std::collate<CharT>`) |
| [transform](collate/transform "cpp/locale/collate/transform") | invokes `do_transform` (public member function of `std::collate<CharT>`) |
| [hash](collate/hash "cpp/locale/collate/hash") | invokes `do_hash` (public member function of `std::collate<CharT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_compare](collate/compare "cpp/locale/collate/compare")
[virtual] | compares two strings using this facet's collation rules (virtual protected member function of `std::collate<CharT>`) |
| [do\_transform](collate/transform "cpp/locale/collate/transform")
[virtual] | transforms a string so that collation can be replaced by comparison (virtual protected member function of `std::collate<CharT>`) |
| [do\_hash](collate/hash "cpp/locale/collate/hash")
[virtual] | generates an integer hash value using this facet's collation rules (virtual protected member function of `std::collate<CharT>`) |
### Notes
Collation order is the dictionary order: the position of the letter in the national alphabet (its *equivalence class*) has higher priority than its case or variant. Within an equivalence class, lowercase characters collate before their uppercase equivalents and locale-specific order may apply to the characters with diacritics. In some locales, groups of characters compare as single *collation units*. For example, `"ch"` in Czech follows `"h"` and precedes `"i"`, and `"dzs"` in Hungarian follows `"dz"` and precedes `"g"`.
### Example
### See also
| | |
| --- | --- |
| [collate](collate "cpp/locale/collate") | defines lexicographical comparison and hashing of strings (class template) |
| [strcoll](../string/byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [wcscoll](../string/wide/wcscoll "cpp/string/wide/wcscoll") | compares two wide strings in accordance to the current locale (function) |
| [operator()](locale/operator() "cpp/locale/locale/operator()") | lexicographically compares two strings using this locale's collate facet (public member function of `std::locale`) |
cpp std::codecvt_utf8_utf16 std::codecvt\_utf8\_utf16
=========================
| Defined in header `[<codecvt>](../header/codecvt "cpp/header/codecvt")` | | |
| --- | --- | --- |
|
```
template< class Elem,
unsigned long Maxcode = 0x10ffff,
std::codecvt_mode Mode = (std::codecvt_mode)0 >
class codecvt_utf8_utf16 : public std::codecvt<Elem, char, std::mbstate_t>;
```
| | (since C++11) (deprecated in C++17) |
`std::codecvt_utf8_utf16` is a `[std::codecvt](codecvt "cpp/locale/codecvt")` facet which encapsulates conversion between a UTF-8 encoded byte string and UTF-16 encoded character string. If `Elem` is a 32-bit type, one UTF-16 code unit will be stored in each 32-bit character of the output sequence.
This is an N:M conversion facet, and cannot be used with `[std::basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf")` (which only permits 1:N conversions, such as UTF-32/UTF-8, between the internal and the external encodings). This facet can be used with `[std::wstring\_convert](wstring_convert "cpp/locale/wstring convert")`.
### Template Parameters
| | | |
| --- | --- | --- |
| Elem | - | either `char16_t`, `char32_t`, or `wchar_t` |
| Maxcode | - | the largest value of `Elem` that this facet will read or write without error |
| Mode | - | a constant of type `[std::codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")` |
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a new `codecvt_utf8_utf16` facet (public member function) |
| **(destructor)** | destroys a `codecvt_utf8_utf16` facet (public member function) |
std::codecvt\_utf8\_utf16::codecvt\_utf8\_utf16
------------------------------------------------
| | | |
| --- | --- | --- |
|
```
explicit codecvt_utf8_utf16( std::size_t refs = 0 );
```
| | |
Constructs a new `std::codecvt_utf8_utf16` facet, passes the initial reference counter `refs` to the base class.
### Parameters
| | | |
| --- | --- | --- |
| refs | - | the number of references that link to the facet |
std::codecvt\_utf8\_utf16::~codecvt\_utf8\_utf16
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
~codecvt_utf8_utf16();
```
| | |
Destroys the facet. Unlike the locale-managed facets, this facet's destructor is public.
Inherited from [std::codecvt](codecvt "cpp/locale/codecvt")
-------------------------------------------------------------
### Member types
| Member type | Definition |
| --- | --- |
| `intern_type` | `internT` |
| `extern_type` | `externT` |
| `state_type` | `stateT` |
### Member objects
| Member name | Type |
| --- | --- |
| `id` (static) | `[std::locale::id](locale/id "cpp/locale/locale/id")` |
### Member functions
| | |
| --- | --- |
| [out](codecvt/out "cpp/locale/codecvt/out") | invokes `do_out` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [in](codecvt/in "cpp/locale/codecvt/in") | invokes `do_in` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [unshift](codecvt/unshift "cpp/locale/codecvt/unshift") | invokes `do_unshift` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [encoding](codecvt/encoding "cpp/locale/codecvt/encoding") | invokes `do_encoding` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv") | invokes `do_always_noconv` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [length](codecvt/length "cpp/locale/codecvt/length") | invokes `do_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [max\_length](codecvt/max_length "cpp/locale/codecvt/max length") | invokes `do_max_length` (public member function of `std::codecvt<InternT,ExternT,StateT>`) |
### Protected member functions
| | |
| --- | --- |
| [do\_out](codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_in](codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_unshift](codecvt/unshift "cpp/locale/codecvt/unshift")
[virtual] | generates the termination character sequence of `ExternT` characters for incomplete conversion (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_encoding](codecvt/encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_always\_noconv](codecvt/always_noconv "cpp/locale/codecvt/always noconv")
[virtual] | tests if the facet encodes an identity conversion for all valid argument values (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_length](codecvt/length "cpp/locale/codecvt/length")
[virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
| [do\_max\_length](codecvt/max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
Inherited from [std::codecvt\_base](codecvt_base "cpp/locale/codecvt base")
-----------------------------------------------------------------------------
| Member type | Definition |
| --- | --- |
| `enum result { ok, partial, error, noconv };` | Unscoped enumeration type |
| Enumeration constant | Definition |
| --- | --- |
| `ok` | conversion was completed with no error |
| `partial` | not all source characters were converted |
| `error` | encountered an invalid character |
| `noconv` | no conversion required, input and output types are the same |
### Example
```
#include <iostream>
#include <string>
#include <codecvt>
#include <cassert>
#include <locale>
int main()
{
std::string u8 = u8"z\u00df\u6c34\U0001f34c";
std::u16string u16 = u"z\u00df\u6c34\U0001f34c";
// UTF-8 to UTF-16/char16_t
std::u16string u16_conv = std::wstring_convert<
std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(u8);
assert(u16 == u16_conv);
std::cout << "UTF-8 to UTF-16 conversion produced "
<< u16_conv.size() << " code units:\n";
for (char16_t c : u16_conv)
std::cout << std::hex << std::showbase << c << ' ';
// UTF-16/char16_t to UTF-8
std::string u8_conv = std::wstring_convert<
std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
assert(u8 == u8_conv);
std::cout << "\nUTF-16 to UTF-8 conversion produced "
<< std::dec << u8_conv.size() << " bytes:\n" << std::hex;
for (char c : u8_conv)
std::cout << +(unsigned char)c << ' ';
}
```
Output:
```
UTF-8 to UTF-16 conversion produced 5 code units:
0x7a 0xdf 0x6c34 0xd83c 0xdf4c
UTF-16 to UTF-8 conversion produced 10 bytes:
0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c
```
### See also
| Characterconversions | locale-defined multibyte(UTF-8, GB18030) | UTF-8 | UTF-16 |
| --- | --- | --- | --- |
| UTF-16 | [`mbrtoc16`](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") / [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(with C11's DR488) | [`codecvt`](codecvt "cpp/locale/codecvt")<char16\_t, char, mbstate\_t>**`codecvt_utf8_utf16`**<char16\_t>**`codecvt_utf8_utf16`**<char32\_t>**`codecvt_utf8_utf16`**<wchar\_t> | N/A |
| UCS2 | [`c16rtomb`](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")(without C11's DR488) | [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char16\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char16\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(Windows). |
| UTF-32 | [`mbrtoc32`](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") / [`c32rtomb`](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb"). | [`codecvt`](codecvt "cpp/locale/codecvt")<char32\_t, char, mbstate\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<char32\_t> [`codecvt_utf8`](codecvt_utf8 "cpp/locale/codecvt utf8")<wchar\_t>(non-Windows). | [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<char32\_t> [`codecvt_utf16`](codecvt_utf16 "cpp/locale/codecvt utf16")<wchar\_t>(non-Windows). |
| system wide:UTF-32(non-Windows)UCS2(Windows) | [`mbsrtowcs`](../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") / [`wcsrtombs`](../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") [`use_facet`](use_facet "cpp/locale/use facet")<[`codecvt`](codecvt "cpp/locale/codecvt") <wchar\_t, char, mbstate\_t>>([`locale`](locale "cpp/locale/locale")). | No | No |
| | |
| --- | --- |
| [codecvt](codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) |
| [codecvt\_mode](codecvt_mode "cpp/locale/codecvt mode")
(C++11)(deprecated in C++17) | tags to alter behavior of the standard codecvt facets (enum) |
| [codecvt\_utf8](codecvt_utf8 "cpp/locale/codecvt utf8")
(C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) |
| [codecvt\_utf16](codecvt_utf16 "cpp/locale/codecvt utf16")
(C++11)(deprecated in C++17) | converts between UTF-16 and UCS2/UCS4 (class template) |
| programming_docs |
cpp std::num_get std::num\_get
=============
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class InputIt = std::istreambuf_iterator<CharT>
> class num_get;
```
| | |
Class `std::num_get` encapsulates the rules for parsing string representations of numeric values. Specifically, types `bool`, `unsigned short`, `unsigned int`, `long`, `unsigned long`, `long long`, `unsigned long long`, `float`, `double`, `long double`, and `void*` are supported. The standard formatting input operators (such as `cin >> n;`) use the `std::num_get` facet of the I/O stream's locale to parse the text representations of the numbers.
![std-num get-inheritance.svg]()
Inheritance diagram.
### Type requirements
| |
| --- |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
### Specializations
Two standalone (locale-independent) full specializations and two partial specializations are provided by the standard library:
| Defined in header `[<locale>](../header/locale "cpp/header/locale")` |
| --- |
| `std::num_get<char>` | creates narrow string parsing of numbers |
| `std::num_get<wchar_t>` | creates wide string parsing of numbers |
| `std::num_get<char, InputIt>` | creates narrow string parsing of numbers using custom input iterator |
| `std::num_get<wchar_t, InputIt>` | creates wide string parsing of numbers using custom input iterator |
In addition, every locale object constructed in a C++ program implements its own (locale-specific) versions of these specializations.
### Member types
| Member type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `iter_type` | `InputIt` |
### Member functions
| | |
| --- | --- |
| [(constructor)](num_get/num_get "cpp/locale/num get/num get") | constructs a new num\_get facet (public member function) |
| [(destructor)](num_get/~num_get "cpp/locale/num get/~num get") | destructs a num\_get facet (protected member function) |
| [get](num_get/get "cpp/locale/num get/get") | invokes `do_get` (public member function) |
### Member objects
| | |
| --- | --- |
| static std::locale::id id | *id* of the locale (public member object) |
### Protected member functions
| | |
| --- | --- |
| [do\_get](num_get/get "cpp/locale/num get/get")
[virtual] | parses a number from an input stream (virtual protected member function) |
### Example
```
#include <iostream>
#include <locale>
#include <string>
#include <sstream>
#include <iterator>
int main()
{
std::string de_double = "1.234.567,89";
std::string us_double = "1,234,567.89";
// parse using streams
std::istringstream de_in(de_double);
de_in.imbue(std::locale("de_DE"));
double f1;
de_in >> f1;
std::istringstream us_in(de_double);
us_in.imbue(std::locale("en_US.UTF-8"));
double f2;
us_in >> f2;
std::cout << "Parsing " << de_double << " as double gives " << std::fixed
<< f1 << " in de_DE locale and " << f2 << " in en_US\n";
// use the facet directly
std::istringstream s3(us_double);
s3.imbue(std::locale("en_US.UTF-8"));
auto& f = std::use_facet<std::num_get<char>>(s3.getloc());
std::istreambuf_iterator<char> beg(s3), end;
double f3;
std::ios::iostate err;
f.get(beg, end, s3, err, f3);
std::cout << "parsing " << us_double
<< " as double using raw en_US facet gives " << f3 << '\n';
}
```
Output:
```
Parsing 1.234.567,89 as double gives 1234567.890000 in de_DE locale and 1.234000 in en_US
parsing 1,234,567.89 as double using raw en_US facet gives 1234567.890000
```
### See also
| | |
| --- | --- |
| [numpunct](numpunct "cpp/locale/numpunct") | defines numeric punctuation rules (class template) |
| [num\_put](num_put "cpp/locale/num put") | formats numeric values for output as character sequence (class template) |
| [operator>>](../io/basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) |
cpp std::ctype<CharT>::toupper, std::ctype<CharT>::do_toupper std::ctype<CharT>::toupper, std::ctype<CharT>::do\_toupper
==========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
CharT toupper( CharT c ) const;
```
| (1) | |
|
```
public:
const CharT* toupper( CharT* beg, const CharT* end ) const;
```
| (2) | |
|
```
protected:
virtual CharT do_toupper( CharT c ) const;
```
| (3) | |
|
```
protected:
virtual const CharT* do_toupper( CharT* beg, const CharT* end ) const;
```
| (4) | |
1,2) public member function, calls the protected virtual member function `do_toupper` of the most derived class.
3) Converts the character `c` to upper case if an upper case form is defined by this locale.
4) For every character in the character array `[beg, end)`, for which an upper case form exists, replaces the character with that upper case form. ### Parameters
| | | |
| --- | --- | --- |
| c | - | character to convert |
| beg | - | pointer to the first character in an array of characters to convert |
| end | - | one past the end pointer for the array of characters to convert |
### Return value
1,3) upper case character or `c` if no upper case form is listed by this locale.
2,4) `end`. ### Notes
Only 1:1 character mapping can be performed by this function, e.g. the uppercase form of 'ß' is the two-character string "SS" (with some exceptions - see [«Capital ẞ»](https://en.wikipedia.org/wiki/Capital_%E1%BA%9E)), which cannot be obtained by `do_toupper`.
### Example
```
#include <locale>
#include <iostream>
void try_upper(const std::ctype<wchar_t>& f, wchar_t c)
{
wchar_t up = f.toupper(c);
if (up != c) {
std::wcout << "Upper case form of \'" << c << "' is " << up << '\n';
} else {
std::wcout << '\'' << c << "' has no upper case form\n";
}
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wcout << "In US English UTF-8 locale:\n";
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
try_upper(f, L's');
try_upper(f, L'ſ');
try_upper(f, L'δ');
try_upper(f, L'ö');
try_upper(f, L'ß');
std::wstring str = L"Hello, World!";
std::wcout << "Uppercase form of the string '" << str << "' is ";
f.toupper(&str[0], &str[0] + str.size());
std::wcout << "'" << str << "'\n";
}
```
Output:
```
In US English UTF-8 locale:
Upper case form of 's' is S
Upper case form of 'ſ' is S
Upper case form of 'δ' is Δ
Upper case form of 'ö' is Ö
'ß' has no upper case form
Uppercase form of the string 'Hello, World!' is 'HELLO, WORLD!'
```
### See also
| | |
| --- | --- |
| [tolower](tolower "cpp/locale/ctype/tolower") | invokes `do_tolower` (public member function) |
| [toupper](../../string/byte/toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) |
| [towupper](../../string/wide/towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) |
cpp std::ctype<CharT>::widen, do_widen std::ctype<CharT>::widen, do\_widen
===================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
CharT widen( char c ) const;
```
| (1) | |
|
```
public:
const char* widen( const char* beg, const char* end, CharT* dst ) const;
```
| (2) | |
|
```
protected:
virtual CharT do_widen( char c ) const;
```
| (3) | |
|
```
protected:
virtual const char* do_widen( const char* beg, const char* end, CharT* dst ) const;
```
| (4) | |
1,2) public member function, calls the protected virtual member function `do_widen` of the most derived class.
3) Converts the single-byte character `c` to the corresponding wide character representation using the simplest reasonable transformation. Typically, this applies only to the characters whose multibyte encoding is a single byte (e.g. U+0000-U+007F in UTF-8).
4) For every character in the character array `[beg, end)`, writes the corresponding widened character to the successive locations in the character array pointed to by `dst`. Widening always returns a wide character, but only the characters from the [basic source character set](../../language/charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](../../language/charset#Basic_character_set "cpp/language/charset") (since C++23) are guaranteed to have a unique, well-defined, widening transformation, which is also guaranteed to be reversible (by `[narrow()](narrow "cpp/locale/ctype/narrow")`). In practice, all characters whose multibyte representation is a single byte are usually widened to their wide character counterparts, and the rest of the possible single-byte values are usually mapped into the same placeholder value, typically `CharT(-1)`.
Widening, if successful, preserves all character classification categories known to `[is()](is "cpp/locale/ctype/is")`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | character to convert |
| dflt | - | default value to produce if the conversion fails |
| beg | - | pointer to the first character in an array of characters to convert |
| end | - | one past the end pointer for the array of characters to convert |
| dst | - | pointer to the first element of the array of char to fill |
### Return value
1,3) widened character
2,4) `end`
### Example
```
#include <locale>
#include <iostream>
void try_widen(const std::ctype<wchar_t>& f, char c)
{
wchar_t w = f.widen(c);
std::cout << "The single-byte character " << +(unsigned char)c
<< " widens to " << +w << '\n';
}
int main()
{
std::locale::global(std::locale("cs_CZ.iso88592"));
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
std::cout << std::hex << std::showbase << "In Czech ISO-8859-2 locale:\n";
try_widen(f, 'a');
try_widen(f, '\xdf'); // German letter ß (U+00df) in ISO-8859-2
try_widen(f, '\xec'); // Czech letter ě (U+011b) in ISO-8859-2
std::locale::global(std::locale("cs_CZ.utf8"));
auto& f2 = std::use_facet<std::ctype<wchar_t>>(std::locale());
std::cout << "In Czech UTF-8 locale:\n";
try_widen(f2, 'a');
try_widen(f2, '\xdf');
try_widen(f2, '\xec');
}
```
Output:
```
In Czech ISO-8859-2 locale:
The single-byte character 0x61 widens to 0x61
The single-byte character 0xdf widens to 0xdf
The single-byte character 0xec widens to 0x11b
In Czech UTF-8 locale:
The single-byte character 0x61 widens to 0x61
The single-byte character 0xdf widens to 0xffffffff
The single-byte character 0xec widens to 0xffffffff
```
### See also
| | |
| --- | --- |
| [narrow](narrow "cpp/locale/ctype/narrow") | invokes `do_narrow` (public member function) |
| [widen](../../io/basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) |
| [btowc](../../string/multibyte/btowc "cpp/string/multibyte/btowc") | widens a single-byte narrow character to wide character, if possible (function) |
cpp std::ctype<CharT>::tolower, std::ctype<CharT>::do_tolower std::ctype<CharT>::tolower, std::ctype<CharT>::do\_tolower
==========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
CharT tolower( CharT c ) const;
```
| (1) | |
|
```
public:
const CharT* tolower( CharT* beg, const CharT* end ) const;
```
| (2) | |
|
```
protected:
virtual CharT do_tolower( CharT c ) const;
```
| (3) | |
|
```
protected:
virtual const CharT* do_tolower( CharT* beg, const CharT* end ) const;
```
| (4) | |
1,2) public member function, calls the protected virtual member function `do_tolower` of the most derived class.
3) Converts the character `c` to lower case if a lower case form is defined by this locale.
4) For every character in the character array `[beg, end)`, for which a lower case form exists, replaces the character with that lower case form. ### Parameters
| | | |
| --- | --- | --- |
| c | - | character to convert |
| beg | - | pointer to the first character in an array of characters to convert |
| end | - | one past the end pointer for the array of characters to convert |
### Return value
1,3) lower case character or `c` if no lower case form is listed by this locale.
2,4) `end`. ### Notes
Only 1:1 character mapping can be performed by this function, e.g. the Greek uppercase letter 'Σ' has two lowercase forms, depending on the position in a word: 'σ' and 'ς'. A call to `do_tolower` cannot be used to obtain the correct lowercase form in this case.
### Example
```
#include <locale>
#include <iostream>
void try_lower(const std::ctype<wchar_t>& f, wchar_t c)
{
wchar_t up = f.tolower(c);
if (up != c) {
std::wcout << "Lower case form of \'" << c << "' is " << up << '\n';
} else {
std::wcout << '\'' << c << "' has no lower case form\n";
}
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wcout << "In US English UTF-8 locale:\n";
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
try_lower(f, L'Σ');
try_lower(f, L'Ɛ');
try_lower(f, L'A');
std::wstring str = L"HELLo, wORLD!";
std::wcout << "Lowercase form of the string '" << str << "' is ";
f.tolower(&str[0], &str[0] + str.size());
std::wcout << "'" << str << "'\n";
}
```
Output:
```
In US English UTF-8 locale:
Lower case form of 'Σ' is σ
Lower case form of 'Ɛ' is ɛ
Lower case form of 'A' is a
Lowercase form of the string 'HELLo, wORLD!' is 'hello, world!'
```
### See also
| | |
| --- | --- |
| [toupper](toupper "cpp/locale/ctype/toupper") | invokes `do_toupper` (public member function) |
| [tolower](../../string/byte/tolower "cpp/string/byte/tolower") | converts a character to lowercase (function) |
| [towlower](../../string/wide/towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) |
cpp std::ctype<CharT>::narrow, do_narrow std::ctype<CharT>::narrow, do\_narrow
=====================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
char narrow( CharT c, char dflt ) const;
```
| (1) | |
|
```
public:
const CharT* narrow( const CharT* beg, const CharT* end,
char dflt, char* dst ) const;
```
| (2) | |
|
```
protected:
virtual char do_narrow( CharT c, char dflt ) const;
```
| (3) | |
|
```
protected:
virtual const CharT* do_narrow( const CharT* beg, const CharT* end,
char dflt, char* dst ) const;
```
| (4) | |
1,2) Public member function, calls the protected virtual member function `do_narrow` of the most derived class.
3) Converts the (possibly wide) character `c` to multibyte representation if the character can be represented with a single byte (for example, ASCII characters in UTF-8 encoding are single bytes). Returns `dflt` if such conversion does not exist.
4) For every character in the character array `[beg, end)`, writes narrowed characters (or `dflt` whenever narrowing fails) to the successive locations in the character array pointed to by `dst`. Narrowing is always successful and is always reversible (by calling `[widen()](widen "cpp/locale/ctype/widen")`) for all characters from the [basic source character set](../../language/charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](../../language/charset#Basic_character_set "cpp/language/charset") (since C++23).
Narrowing, if successful, preserves all character classification categories known to `[is()](is "cpp/locale/ctype/is")`.
Narrowing of any digit character guarantees that if the result is subtracted from the character literal `'0'`, the difference equals the digit value of the original character.
### Parameters
| | | |
| --- | --- | --- |
| c | - | character to convert |
| dflt | - | default value to produce if the conversion fails |
| beg | - | pointer to the first character in an array of characters to convert |
| end | - | one past the end pointer for the array of characters to convert |
| dst | - | pointer to the first element of the array of char to fill |
### Return value
1,3) narrowed character or `dflt` if narrowing fails
2,4) `end`
### Example
```
#include <locale>
#include <iostream>
void try_narrow(const std::ctype<wchar_t>& f, wchar_t c)
{
char n = f.narrow(c, 0);
if (n) {
std::wcout << '\'' << c << "' narrowed to " << +(unsigned char)n << '\n';
} else {
std::wcout << '\'' << c << "' could not be narrowed\n";
}
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wcout << std::hex << std::showbase << "In US English UTF-8 locale:\n";
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
try_narrow(f, L'A');
try_narrow(f, L'A');
try_narrow(f, L'ě');
std::locale::global(std::locale("cs_CZ.iso88592"));
auto& f2 = std::use_facet<std::ctype<wchar_t>>(std::locale());
std::wcout << "In Czech ISO-8859-2 locale:\n";
try_narrow(f2, L'A');
try_narrow(f2, L'A');
try_narrow(f2, L'ě');
}
```
Output:
```
In US English UTF-8 locale:
'A' narrowed to 0x41
'A' could not be narrowed
'ě' could not be narrowed
In Czech ISO-8859-2 locale:
'A' narrowed to 0x41
'A' could not be narrowed
'ě' narrowed to 0xec
```
### See also
| | |
| --- | --- |
| [widen](widen "cpp/locale/ctype/widen") | invokes `do_widen` (public member function) |
| [narrow](../../io/basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) |
| [wctob](../../string/multibyte/wctob "cpp/string/multibyte/wctob") | narrows a wide character to a single-byte narrow character, if possible (function) |
cpp std::num_get<CharT,InputIt>::~num_get std::num\_get<CharT,InputIt>::~num\_get
=======================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~num_get();
```
| | |
Destructs a `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_num_get : public std::num_get<wchar_t>
{
Destructible_num_get(std::size_t refs = 0) : num_get(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_num_get dc;
// std::num_get<wchar_t> c; // compile error: protected destructor
}
```
cpp std::num_get<CharT,InputIt>::get, std::num_get<CharT,InputIt>::do_get std::num\_get<CharT,InputIt>::get, std::num\_get<CharT,InputIt>::do\_get
========================================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
public:
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, bool& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long long& v ) const;
```
| (since C++11) |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned short& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned int& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned long& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned long long& v ) const;
```
| (since C++11) |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, float& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, double& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long double& v ) const;
```
| |
|
```
iter_type get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, void*& v ) const;
```
| |
| | (2) | |
|
```
protected:
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, bool& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long long& v ) const;
```
| (since C++11) |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned short& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned int& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned long& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, unsigned long long& v ) const;
```
| (since C++11) |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, float& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, double& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long double& v ) const;
```
| |
|
```
virtual iter_type do_get( iter_type in, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, void*& v ) const;
```
| |
1) Public member function, calls the member function `do_get` of the most derived class.
2) Reads characters from the input iterator `in` and generates the value of the type of `v`, taking into account I/O stream formatting flags from `str.flags()`, character classification rules from `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<charT>>(str.getloc())`, and numeric punctuation characters from `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc())`. This function is called by all formatted input stream operators such as `[std::cin](http://en.cppreference.com/w/cpp/io/cin) >> n;`. Conversion occurs in three stages:
#### Stage 1: conversion specifier selection
* I/O format flags are obtained, as if by
`fmtflags basefield = (str.flags() & [std::ios\_base::basefield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags boolalpha = (str.flags() & [std::ios\_base::boolalpha](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
* If the type of `v` is an integer type, the first applicable choice of the following five is selected:
If `basefield == oct`, will use conversion specifier `%o`
If `basefield == hex`, will use conversion specifier `%X`
If `basefield == 0`, will use conversion specifier `%i`
If the type of `v` is signed, will use conversion specifier `%d`
If the type of `v` is unsigned, will use conversion specifier `%u`
* For integer types, length modifier is added to the conversion specification if necessary: `h` for `short` and `unsigned short`, `l` for `long` and `unsigned long`, `ll` for `long long` and `unsigned long long` (since C++11)
* If the type of `v` is `float`, will use conversion specifier `%g`
* If the type of `v` is `double`, will use conversion specifier `%lg`
* If the type of `v` is `long double`, will use conversion specifier `%Lg`
* If the type of `v` is `void*`, will use conversion specifier `%p`
* If the type of `v` is `bool` and `boolalpha == 0`, proceeds as if the type of `v` is `long`, except for the value to be stored in `v` in stage 3.
* If the type of `v` is `bool` and `boolalpha != 0`, the following replaces stages 2 and 3:
+ Successive characters obtained from the input iterator `in` are matched against the character sequences obtained from `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).falsename()` and `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).truename()` only as necessary as to identify the unique match. The input iterator `in` is compared to `end` only when necessary to obtain a character.
+ If the target sequence is uniquely matched, `v` is set to the corresponding `bool` value. Otherwise `false` is stored in `v` and `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` is assigned to `err`. If unique match could not be found before the input ended (`in == end`), `err |= [std::ios\_base::eofbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)` is executed.
#### Stage 2: character extraction
* If `in == end`, Stage 2 is terminated immediately, no further characters are extracted
* The next character is extracted from `in` as if by `char_type ct = *in;`
+ If the character matches one of `"0123456789abcdefxABCDEFX+-"` (until C++11)`"0123456789abcdefpxABCDEFPX+-"` (since C++11), widened to the locale's char\_type as if by `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<charT>>(str.getloc()).widen()`, it is converted to the corresponding `char`.
+ If the character matches the decimal point separator (`[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).decimal\_point())`), it is replaced by `'.'`.
+ If the character matches the thousands separator (`[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).thousands\_sep()`) and the thousands separation is in use (as determined by `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).grouping().length() != 0`), then if the decimal point `'.'` has not yet been accumulated, the position of the character is remembered, but the character is otherwise ignored. If the decimal point has already been accumulated, the character is discarded and Stage 2 terminates.
+ In any case, the check is made whether the `char` obtained from the previous steps is allowed in the input field that would be parsed by `[std::scanf](../../io/c/fscanf "cpp/io/c/fscanf")` given the conversion specifier selected in Stage 1. If it is allowed, it is accumulated in a temporary buffer and Stage 2 repeats. If it is not allowed, Stage 2 terminates.
#### Stage 3: conversion and storage
* The sequence of `char`s accumulated in Stage 2 is converted to a numeric value
The input is parsed as if by `[std::strtoll](../../string/byte/strtol "cpp/string/byte/strtol")` for signed integer `v`, `[std::strtoull](../../string/byte/strtoul "cpp/string/byte/strtoul")` for unsigned integer `v`, `[std::strtof](../../string/byte/strtof "cpp/string/byte/strtof")` for `float` `v`, `[std::strtod](../../string/byte/strtof "cpp/string/byte/strtof")` for `double` `v`, or `[std::strtold](../../string/byte/strtof "cpp/string/byte/strtof")` for `long double` `v` * If the conversion function fails to convert the entire field, the value `0` is stored in `v`
* If the type of `v` is a signed integer type and the conversion function results in a positive or negative value too large to fit in it, the most positive or negative representable value is stored in `v`, respectively
* If the type of `v` is an unsigned integer type and the conversion function results in a value that does not fit in it, the most positive representable value is stored in `v`.
* In any case, if the conversion function fails `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` is assigned to `err`
* Otherwise, the numeric result of the conversion is stored in `v`
+ If the type of `v` is `bool` and boolalpha is not set, then if the value to be stored is `0`, `false` is stored, if the value to be stored is `1`, `true` is stored, for any other value `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` is assigned to `err` and `true` is stored.
* After this, digit grouping is checked. if the position of any of the thousands separators discarded in Stage 2 does not match the grouping provided by `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<charT>>(str.getloc()).grouping()`, `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` is assigned to `err`.
* If Stage 2 was terminated by the test `in == end`, `err |= [std::ios\_base::eofbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)` is executed to set the eof bit.
### Return value
`in`.
### Notes
Before the resolutions of [LWG issue 23](https://cplusplus.github.io/LWG/issue23) and [LWG issue 696](https://cplusplus.github.io/LWG/issue696), `v` was left unchanged if an error occurs.
Before the resolution of [LWG issue 1169](https://cplusplus.github.io/LWG/issue1169), converting a negative number string into an unsigned integer might produce zero (since the value represented by the string is smaller than what the target type can represent).
Before the resolution of [LWG issue 2381](https://cplusplus.github.io/LWG/issue2381), the strings `"NaN"` and `"inf"` were rejected by `do_get(double)` even if they are valid input to `strtod` because stage 2 filters out characters such as `'N'` or `'i'`. Similarly, exadecimal floating-point numbers such as `"0x1.23p-10"` used to be rejected by `do_get`.
### Example
An implementation of `operator>>` for a user-defined type.
```
#include <iostream>
#include <iterator>
#include <locale>
struct base { long x; };
template<class CharT, class Traits>
std::basic_istream<CharT, Traits>&
operator >>(std::basic_istream<CharT, Traits>& is, base& b)
{
std::ios_base::iostate err = std::ios_base::goodbit;
try // setting err could throw
{
typename std::basic_istream<CharT, Traits>::sentry s(is);
if (s) // if stream is ready for input
{
std::use_facet<std::num_get<CharT>>(is.getloc()).get(is, {}, is, err, b.x);
}
}
catch(std::ios_base::failure& error)
{
// handle the exception
}
return is;
}
int main()
{
base b;
std::cin >> b;
}
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 17](https://cplusplus.github.io/LWG/issue17) | C++98 | the process of parsing text boolean values was errornous | corrected |
| [LWG 18](https://cplusplus.github.io/LWG/issue18) | C++98 | the member `get` that parses booleanvalues was not listed in the member list | listed |
| [LWG 23](https://cplusplus.github.io/LWG/issue23) | C++98 | overflowing input resulted in undefined behavior | overflow handled |
| [LWG 696](https://cplusplus.github.io/LWG/issue696) | C++98 | the result was unchanged on conversion failure | set to zero |
| [LWG 1169](https://cplusplus.github.io/LWG/issue1169) | C++98 | overflow handling was inconsistent between floating-point types | made consistentwith `strtof`/`strtod` |
| [LWG 2381](https://cplusplus.github.io/LWG/issue2381) | C++11 | `do_get` did not parse `'p'` and `'P'` while `strtod` parsed them | made `'p'` and `'P'` parsed |
### See also
| | |
| --- | --- |
| [operator>>](../../io/basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) |
| programming_docs |
cpp std::num_get<CharT,InputIt>::num_get std::num\_get<CharT,InputIt>::num\_get
======================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit num_get( std::size_t refs = 0 );
```
| | |
Creates a `[std::num\_get](http://en.cppreference.com/w/cpp/locale/num_get)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::moneypunct<CharT,International>::moneypunct std::moneypunct<CharT,International>::moneypunct
================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit moneypunct( std::size_t refs = 0 );
```
| | |
Creates a `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::moneypunct<CharT,International>::thousands_sep, do_thousands_sep std::moneypunct<CharT,International>::thousands\_sep, do\_thousands\_sep
========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
char_type thousands_sep() const;
```
| (1) | |
|
```
protected:
virtual char_type do_thousands_sep() const;
```
| (2) | |
1) Public member function, calls the member function `do_thousands_sep` of the most derived class.
2) Returns the character to be used as the separator between digit groups when parsing or formatting the integral parts of monetary values. ### Return value
The object of type `char_type` to use as the thousands separator. In common U.S. locales, this is `','` or `L','`.
### Example
```
#include <locale>
#include <iostream>
#include <iomanip>
#include <iterator>
struct space_out : std::moneypunct<char> {
pattern do_pos_format() const { return { {value, none, none, none} };}
int do_frac_digits() const { return 0; }
char_type do_thousands_sep() const { return ' ';}
string_type do_grouping() const { return "\002";}
};
int main()
{
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "american locale: " << std::showbase
<< std::put_money(12345678.0)<< '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new space_out));
std::cout << "locale with modified moneypunct: "
<< std::put_money(12345678.0)<< '\n';
}
```
Output:
```
american locale: $123,456.78
locale with modified moneypunct: 12 34 56 78
```
### See also
| | |
| --- | --- |
| [do\_grouping](grouping "cpp/locale/moneypunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function) |
cpp std::moneypunct<CharT,International>::decimal_point, do_decimal_point std::moneypunct<CharT,International>::decimal\_point, do\_decimal\_point
========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
CharT decimal_point() const;
```
| (1) | |
|
```
protected:
virtual CharT do_decimal_point() const;
```
| (2) | |
1) Public member function, calls the member function `do_decimal_point` of the most derived class.
2) Returns the character to use as the decimal point separator in monetary I/O if the format uses fractions (that is, if `[do\_frac\_digits()](frac_digits "cpp/locale/moneypunct/frac digits")` is greater than zero). For typical U.S. locales, it is the character `'.'` (or `L'.'`) ### Return value
The object of type `CharT` holding the decimal point character.
### Example
```
#include <iostream>
#include <iomanip>
#include <locale>
void show_dpt(const char* locname)
{
std::locale loc(locname);
std::cout.imbue(loc);
std::cout << locname << " decimal point is '"
<< std::use_facet<std::moneypunct<char>>(loc).decimal_point()
<< "' for example: " << std::showbase << std::put_money(123);
if (std::use_facet<std::moneypunct<char>>(loc).frac_digits() == 0)
std::cout << " (does not use frac digits) ";
std::cout << '\n';
}
int main()
{
show_dpt("en_US.utf8");
show_dpt("ja_JP.utf8");
show_dpt("sv_SE.utf8");
show_dpt("de_DE.utf8");
}
```
Output:
```
en_US.utf8 decimal point is '.' for example: $1.23
ja_JP.utf8 decimal point is '.' for example: ¥123 (does not use frac digits)
sv_SE.utf8 decimal point is ',' for example: 1,23 kr
de_DE.utf8 decimal point is ',' for example: 1,23 €
```
### See also
| | |
| --- | --- |
| [do\_frac\_digits](frac_digits "cpp/locale/moneypunct/frac digits")
[virtual] | provides the number of digits to display after the decimal point (virtual protected member function) |
cpp std::moneypunct<CharT,International>::frac_digits, do_frac_digits std::moneypunct<CharT,International>::frac\_digits, do\_frac\_digits
====================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
int frac_digits() const;
```
| (1) | |
|
```
protected:
virtual int do_frac_digits() const;
```
| (2) | |
1) Public member function, calls the member function `do_frac_digits` of the most derived class.
2) Returns the number of digits to be displayed after the decimal point when printing monetary values ### Return value
The number of digits to be displayed after the decimal point. In common U.S. locales, this is the value `2`.
### Example
```
#include <locale>
#include <iostream>
#include <iomanip>
#include <iterator>
struct space_out : std::moneypunct<char> {
pattern do_pos_format() const { return { {value, none, none, none} };}
int do_frac_digits() const { return 0; }
char_type do_thousands_sep() const { return ' ';}
string_type do_grouping() const { return "\002";}
};
int main()
{
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "american locale: " << std::showbase
<< std::put_money(12345678.0)<< '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new space_out));
std::cout << "locale with modified moneypunct: "
<< std::put_money(12345678.0)<< '\n';
}
```
Output:
```
american locale: $123,456.78
locale with modified moneypunct: 12 34 56 78
```
### See also
| | |
| --- | --- |
| [do\_thousands\_sep](thousands_sep "cpp/locale/moneypunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function) |
| [do\_decimal\_point](decimal_point "cpp/locale/moneypunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function) |
cpp std::moneypunct<CharT,International>::positive_sign, do_positive_sign, negative_sign, do_negative_sign std::moneypunct<CharT,International>::positive\_sign, do\_positive\_sign, negative\_sign, do\_negative\_sign
============================================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
string_type positive_sign() const;
```
| (1) | |
|
```
public:
string_type negative_sign() const;
```
| (2) | |
|
```
protected:
virtual string_type do_positive_sign() const;
```
| (3) | |
|
```
protected:
virtual string_type do_negative_sign() const;
```
| (4) | |
1) Public member function, calls the member function `do_positive_sign` of the most derived class.
2) Public member function, calls the member function `do_negative_sign` of the most derived class.
3) Returns the string that is used for formatting of positive monetary values.
3) Returns the string that is used for formatting of negative monetary values. Only the first character of the string returned is the character that appears in the `[pos\_format()](pos_format "cpp/locale/moneypunct/pos format")`/`[neg\_format()](pos_format "cpp/locale/moneypunct/pos format")` position indicated by the value `sign`. The rest of the characters appear *after* the rest of the monetary string.
In particular, for negative\_sign of `"-"`, the formatting may appear as `"-1.23 €"`, while for negative\_sign of `"()"` it would appear as `"(1.23 €)"`.
### Return value
The string of type `string_type` holding the characters to be used as positive or negative sign.
### Example
```
#include <iostream>
#include <iomanip>
#include <locale>
struct my_punct : std::moneypunct_byname<char, false> {
my_punct(const char* name) : moneypunct_byname(name) {}
string_type do_negative_sign() const { return "()"; }
};
int main()
{
std::locale loc("de_DE.utf8");
std::cout.imbue(loc);
std::cout << loc.name() << " negative sign is '"
<< std::use_facet<std::moneypunct<char>>(loc).negative_sign()
<< "' for example: " << std::showbase << std::put_money(-1234) << '\n';
std::locale loc2("ms_MY.utf8");
std::cout.imbue(loc2);
std::cout << loc2.name() << " negative sign is '"
<< std::use_facet<std::moneypunct<char>>(loc2).negative_sign()
<< "' for example: " << std::put_money(-1234) << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new my_punct("de_DE.utf8")));
std::cout << "de_DE.utf8 with negative_sign set to \"()\": "
<< std::put_money(-1234) << '\n';
}
```
Output:
```
de_DE.utf8 negative sign is '-' for example: -12,34 €
ms_MY.utf8 negative sign is '()' for example: (RM12.34)
de_DE.utf8 with negative_sign set to "()": (12,34 €)
```
### See also
| | |
| --- | --- |
| [do\_pos\_formatdo\_neg\_format](pos_format "cpp/locale/moneypunct/pos format")
[virtual] | provides the formatting pattern for currency values (virtual protected member function) |
cpp std::moneypunct<CharT,International>::~moneypunct std::moneypunct<CharT,International>::~moneypunct
=================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~moneypunct();
```
| | |
Destructs a `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_moneypunct : public std::moneypunct<wchar_t>
{
Destructible_moneypunct(std::size_t refs = 0) : moneypunct(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_moneypunct dc;
// std::moneypunct<wchar_t> c; // compile error: protected destructor
}
```
cpp std::moneypunct<CharT,International>::curr_symbol, do_curr_symbol std::moneypunct<CharT,International>::curr\_symbol, do\_curr\_symbol
====================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
string_type curr_symbol() const;
```
| (1) | |
|
```
protected:
virtual string_type do_curr_symbol() const;
```
| (2) | |
1) Public member function, calls the member function `do_curr_symbol` of the most derived class.
2) Returns the string used as the currency identifier by this locale. If `International` (the second template parameter of `std::moneypunct`) is `false`, the identifier is usually a single (wide) character, such as `"¥"` or `"$"`. If `International` is `true`, the identifier is usually a four-character string holding the three-character [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217 "enwiki:ISO 4217") currency code followed by a space (`"JPY "` or `"USD "`) ### Return value
The object of type `string_type` holding the currency symbol or code.
### Example
```
#include <iostream>
#include <locale>
void show_ccy(const char* locname)
{
std::locale loc(locname);
std::cout << locname << " currency symbol is "
<< std::use_facet<std::moneypunct<char, true>>(loc).curr_symbol()
<< "or " << std::use_facet<std::moneypunct<char>>(loc).curr_symbol()
<< " for short\n";
}
int main()
{
show_ccy("en_US.utf8");
show_ccy("ja_JP.utf8");
show_ccy("sv_SE.utf8");
show_ccy("ru_RU.utf8");
show_ccy("vi_VN.utf8");
}
```
Output:
```
en_US.utf8 currency symbol is USD or $ for short
ja_JP.utf8 currency symbol is JPY or ¥ for short
sv_SE.utf8 currency symbol is SEK or kr for short
ru_RU.utf8 currency symbol is RUB or руб for short
vi_VN.utf8 currency symbol is VND or ₫ for short
```
### See also
| | |
| --- | --- |
| [do\_pos\_formatdo\_neg\_format](pos_format "cpp/locale/moneypunct/pos format")
[virtual] | provides the formatting pattern for currency values (virtual protected member function) |
cpp std::moneypunct<CharT,International>::pos_format, do_pos_format, neg_format, do_neg_format std::moneypunct<CharT,International>::pos\_format, do\_pos\_format, neg\_format, do\_neg\_format
================================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
pattern pos_format() const;
```
| (1) | |
|
```
public:
pattern neg_format() const;
```
| (2) | |
|
```
protected:
virtual pattern do_pos_format() const;
```
| (3) | |
|
```
protected:
virtual pattern do_neg_format() const;
```
| (4) | |
1) Public member function, calls the member function `do_pos_format` of the most derived class.
2) Public member function, calls the member function `do_neg_format` of the most derived class.
3) Returns the format structure (of type [`std::money_base::format`](../money_base "cpp/locale/money base")) which describes the formatting of positive monetary values.
4) Returns the format structure (of type [`std::money_base::format`](../money_base "cpp/locale/money base")) which describes the formatting of negative monetary values. The standard specializations of `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)` return the pattern `{symbol, sign, none, value}`
### Return value
The object of type [`std::money_base::format`](../money_base "cpp/locale/money base") describing the formatting used by this locale.
### Notes
While `[std::money\_put](../money_put "cpp/locale/money put")` uses pos\_format for formatting positive values and neg\_format for formatting negative values, `[std::money\_get](../money_get "cpp/locale/money get")` uses neg\_format for parsing all monetary values: it assumes that neg\_format is compatible with pos\_format.
### Example
```
#include <locale>
#include <iostream>
#include <iomanip>
struct my_punct : std::moneypunct_byname<char, false> {
my_punct(const char* name) : moneypunct_byname(name) {}
pattern do_pos_format() const { return { {value, space, symbol, sign} };}
pattern do_neg_format() const { return { {value, space, symbol, sign} };}
};
int main()
{
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "american locale: " << std::showbase
<< std::put_money(12345678.0) << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new my_punct("en_US.utf8")));
std::cout << "locale with modified moneypunct:\n"
<< std::put_money(12345678.0) << '\n'
<< std::put_money(-12345678.0) << '\n';
}
```
Output:
```
american locale: $123,456.78
locale with modified moneypunct:
123,456.78 $
123,456.78 $-
```
### See also
| | |
| --- | --- |
| [do\_curr\_symbol](curr_symbol "cpp/locale/moneypunct/curr symbol")
[virtual] | provides the string to use as the currency identifier (virtual protected member function) |
| [do\_positive\_signdo\_negative\_sign](positive_sign "cpp/locale/moneypunct/positive sign")
[virtual] | provides the string to indicate a positive or negative value (virtual protected member function) |
| [do\_get](../money_get/get "cpp/locale/money get/get")
[virtual] | parses a monetary value from an input stream (virtual protected member function of `std::money_get<CharT,InputIt>`) |
| [do\_put](../money_put/put "cpp/locale/money put/put")
[virtual] | formats a monetary value and writes to output stream (virtual protected member function of `std::money_put<CharT,OutputIt>`) |
cpp std::moneypunct<CharT,International>::grouping, do_grouping std::moneypunct<CharT,International>::grouping, do\_grouping
============================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
std::string grouping() const;
```
| (1) | |
|
```
protected:
virtual std::string do_grouping() const;
```
| (2) | |
1) Public member function, calls the member function `do_grouping` of the most derived class.
2) Returns the pattern that determines the grouping of the digits in the monetary output, with the same exact meaning as `[std::numpunct::do\_grouping](../numpunct/grouping "cpp/locale/numpunct/grouping")`
### Return value
The object of type `[std::string](../../string/basic_string "cpp/string/basic string")` holding the groups. The standard specializations of `std::moneypunct` return an empty string, indicating no grouping. Typical groupings (e.g. the `en_US` locale) return `"\003"`.
### Example
```
#include <locale>
#include <iostream>
#include <iomanip>
#include <iterator>
struct space_out : std::moneypunct<char> {
pattern do_pos_format() const { return { {value, none, none, none} };}
int do_frac_digits() const { return 0; }
char_type do_thousands_sep() const { return ' ';}
string_type do_grouping() const { return "\002";}
};
int main()
{
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "american locale: " << std::showbase
<< std::put_money(12345678.0)<< '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new space_out));
std::cout << "locale with modified moneypunct: "
<< std::put_money(12345678.0)<< '\n';
}
```
Output:
```
american locale: $123,456.78
locale with modified moneypunct: 12 34 56 78
```
### See also
| | |
| --- | --- |
| [do\_thousands\_sep](thousands_sep "cpp/locale/moneypunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function) |
| [do\_decimal\_point](decimal_point "cpp/locale/moneypunct/decimal point")
[virtual] | provides the character to use as decimal point (virtual protected member function) |
cpp std::messages<CharT>::~messages std::messages<CharT>::~messages
===============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~messages();
```
| | |
Destructs a `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_messages : public std::messages<wchar_t>
{
Destructible_messages(std::size_t refs = 0) : messages(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_messages dc;
// std::messages<wchar_t> c; // compile error: protected destructor
}
```
| programming_docs |
cpp std::messages<CharT>::messages std::messages<CharT>::messages
==============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit messages( std::size_t refs = 0 );
```
| | |
Creates a `[std::messages](http://en.cppreference.com/w/cpp/locale/messages)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::messages<CharT>::close, std::messages<CharT>::do_close std::messages<CharT>::close, std::messages<CharT>::do\_close
============================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
void close( catalog c ) const;
```
| (1) | |
|
```
protected:
virtual void do_close( catalog c ) const;
```
| (2) | |
1) public member function, calls the protected virtual member function `do_close` of the most derived class.
2) Releases the implementation-defined resources associated with an open catalog that is designated by the value `c` of type `catalog` (inherited from `[std::messages\_base](../messages_base "cpp/locale/messages base")`), which was obtained from `[open()](open "cpp/locale/messages/open")`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | a valid open catalog identifier, on which `close()` has not yet been called |
### Return value
(none).
### Notes
On POSIX systems, this function call usually translates to a call to `[catclose()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/catclose.html)`. In GNU libstdc++, which is implemented in terms of GNU `gettext()`, it does nothing.
### Example
The following example demonstrated retrieval of messages: on a typical GNU/Linux system it reads from `/usr/share/locale/de/LC_MESSAGES/sed.mo`.
```
#include <iostream>
#include <locale>
int main()
{
std::locale loc("de_DE.utf8");
std::cout.imbue(loc);
auto& facet = std::use_facet<std::messages<char>>(loc);
auto cat = facet.open("sed", loc);
if(cat < 0 )
std::cout << "Could not open german \"sed\" message catalog\n";
else
std::cout << "\"No match\" in German: "
<< facet.get(cat, 0, 0, "No match") << '\n'
<< "\"Memory exhausted\" in German: "
<< facet.get(cat, 0, 0, "Memory exhausted") << '\n';
facet.close(cat);
}
```
Possible output:
```
"No match" in German: Keine Übereinstimmung
"Memory exhausted" in German: Speicher erschöpft
```
### See also
| |
| --- |
| |
cpp std::messages<CharT>::open, std::messages<CharT>::do_open std::messages<CharT>::open, std::messages<CharT>::do\_open
==========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
catalog open( const std::basic_string<char>& name, const std::locale& loc ) const;
```
| (1) | |
|
```
protected:
virtual catalog do_open( const std::basic_string<char>& name, const std::locale& loc ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_open` of the most derived class.
2) Obtains a value of type `catalog` (inherited from `[std::messages\_base](../messages_base "cpp/locale/messages base")`), which can be passed to `[get()](get "cpp/locale/messages/get")` to retrieve messages from the message catalog named by `name`. This value is usable until passed to `[close()](close "cpp/locale/messages/close")`.
### Parameters
| | | |
| --- | --- | --- |
| name | - | name of the message catalog to open |
| loc | - | a locale object that provides additional facets that may be required to read messages from the catalog, such as `[std::codecvt](../codecvt "cpp/locale/codecvt")` to perform wide/multibyte conversions |
### Return value
The non-negative value of type `catalog` that can be used with `[get()](get "cpp/locale/messages/get")` and `[close()](close "cpp/locale/messages/close")`. Returns a negative value if the catalog could not be opened.
### Notes
On POSIX systems, this function call usually translates to a call to `[catopen()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/catopen.html)`. In GNU libstdc++, it calls `[textdomain](http://gcc.gnu.org/onlinedocs/libstdc++/manual/facets.html)`.
The actual catalog location is implementation-defined: for the catalog `"sed"` (message catalogs installed with the Unix utility `'sed'`) in German locale, for example, the file opened by this function call may be `/usr/lib/nls/msg/de_DE/sed.cat`, `/usr/lib/locale/de_DE/LC_MESSAGES/sed.cat`, or `/usr/share/locale/de/LC_MESSAGES/sed.mo`.
### Example
The following example demonstrated retrieval of messages: on a typical GNU/Linux system it reads from `/usr/share/locale/de/LC_MESSAGES/sed.mo`.
```
#include <iostream>
#include <locale>
int main()
{
std::locale loc("de_DE.utf8");
std::cout.imbue(loc);
auto& facet = std::use_facet<std::messages<char>>(loc);
auto cat = facet.open("sed", loc);
if(cat < 0 )
std::cout << "Could not open german \"sed\" message catalog\n";
else
std::cout << "\"No match\" in German: "
<< facet.get(cat, 0, 0, "No match") << '\n'
<< "\"Memory exhausted\" in German: "
<< facet.get(cat, 0, 0, "Memory exhausted") << '\n';
facet.close(cat);
}
```
Possible output:
```
"No match" in German: Keine Übereinstimmung
"Memory exhausted" in German: Speicher erschöpft
```
### See also
| |
| --- |
| |
cpp std::messages<CharT>::get, std::messages<CharT>::do_get std::messages<CharT>::get, std::messages<CharT>::do\_get
========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
string_type get( catalog cat, int set, int msgid, const string_type& dfault ) const;
```
| (1) | |
|
```
protected:
virtual string_type do_get( catalog cat, int set, int msgid, const string_type& dfault ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_get` of the most derived class.
2) Obtains a message from the open message catalog `cat` using the values `set`, `msgid` and `dfault` in implementation-defined manner. If the expected message is not found in the catalog, returns a copy of `dfault`.
### Parameters
| | | |
| --- | --- | --- |
| cat | - | identifier of message catalog obtained from `[open()](open "cpp/locale/messages/open")` and not yet passed to `[close()](close "cpp/locale/messages/close")` |
| set | - | implementation-defined argument, message set in POSIX |
| msgid | - | implementation-defined argument, message id in POSIX |
| dfault | - | the string to look up in the catalog (if the catalog uses string look-up) and also the string to return in case of a failure |
### Return value
The message from the catalog or a copy of `dfault` if none was found.
### Notes
On POSIX systems, this function call usually translates to a call to `[catgets()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/catgets.html)`, and the parameters `set`, `msgid`, and `dfault` are passed to `catgets()` as-is. In GNU libstdc++, this function ignores `set` and `msgid` and simply calls GNU `gettext(dfault)` in the required locale.
### Example
The following example demonstrated retrieval of messages: on a typical GNU/Linux system it reads from `/usr/share/locale/de/LC_MESSAGES/sed.mo`.
```
#include <iostream>
#include <locale>
int main()
{
std::locale loc("de_DE.utf8");
std::cout.imbue(loc);
auto& facet = std::use_facet<std::messages<char>>(loc);
auto cat = facet.open("sed", loc);
if(cat < 0 )
std::cout << "Could not open german \"sed\" message catalog\n";
else
std::cout << "\"No match\" in German: "
<< facet.get(cat, 0, 0, "No match") << '\n'
<< "\"Memory exhausted\" in German: "
<< facet.get(cat, 0, 0, "Memory exhausted") << '\n';
facet.close(cat);
}
```
Possible output:
```
"No match" in German: Keine Übereinstimmung
"Memory exhausted" in German: Speicher erschöpft
```
### See also
| |
| --- |
| |
cpp std::num_put<CharT,OutputIt>::~num_put std::num\_put<CharT,OutputIt>::~num\_put
========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~num_put();
```
| | |
Destructs a `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_num_put : public std::num_put<wchar_t>
{
Destructible_num_put(std::size_t refs = 0) : num_put(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_num_put dc;
// std::num_put<wchar_t> c; // compile error: protected destructor
}
```
cpp std::num_put<CharT,OutputIt>::put, std::num_put<CharT,OutputIt>::do_put std::num\_put<CharT,OutputIt>::put, std::num\_put<CharT,OutputIt>::do\_put
==========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
| | (1) | |
|
```
public:
iter_type put( iter_type out, std::ios_base& str,
char_type fill, bool val ) const;
```
| |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, long val ) const;
```
| |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, long long val ) const;
```
| (since C++11) |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, unsigned long val ) const;
```
| |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, unsigned long long val ) const;
```
| (since C++11) |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, double val ) const;
```
| |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, long double val ) const;
```
| |
|
```
iter_type put( iter_type out, std::ios_base& str,
char_type fill, const void* val ) const;
```
| |
| | (2) | |
|
```
protected:
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, bool val ) const;
```
| |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, long val ) const;
```
| |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, long long val ) const;
```
| (since C++11) |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, unsigned long val ) const;
```
| |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, unsigned long long val ) const;
```
| (since C++11) |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, double val ) const;
```
| |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, long double val ) const;
```
| |
|
```
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, const void* val ) const;
```
| |
1) Public member function, calls the protected virtual member function `do_put` of the most derived class.
2) Writes characters to the output sequence `out` which represent the value of `val`, formatted as requested by the formatting flags `str.flags()` and the `[std::numpunct](../numpunct "cpp/locale/numpunct")` and `[std::ctype](../ctype "cpp/locale/ctype")` facets of the locale imbued in the stream `str`. This function is called by all formatted output stream operators, such as `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << n;`. Conversion occurs in four stages:
#### Stage 1: conversion specifier selection
* I/O format flags are obtained, as if by
`fmtflags basefield = (str.flags() & [std::ios\_base::basefield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags uppercase = (str.flags() & [std::ios\_base::uppercase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags floatfield = (str.flags() & [std::ios\_base::floatfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags showpos = (str.flags() & [std::ios\_base::showpos](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags showbase = (str.flags() & [std::ios\_base::showbase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
`fmtflags showpoint = (str.flags() & [std::ios\_base::showpoint](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags));`
* If the type of `val` is `bool`:
+ If `boolalpha == 0`, then converts `val` to type `int` and performs integer output.
+ If `boolalpha != 0`, obtains `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<CharT>>(str.getloc()).truename()` if `val == true` or `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<CharT>>(str.getloc()).falsename()` if `val == false`, and outputs each successive character `c` of that string to `out` with `*out++ = c`. No further processing is done in this case, the function returns `out`.
* If the type of `val` is an integer type, the first applicable choice of the following is selected:
+ If `basefield == oct`, will use conversion specifier `%o`
+ If `basefield == hex && !uppercase`, will use conversion specifier `%x`
+ If `basefield == hex`, will use conversion specifier `%X`
+ If the type of `val` is signed, will use conversion specifier `%d`
+ If the type of `val` is unsigned, will use conversion specifier `%u`
* For integer types, length modifier is added to the conversion specification if necessary: `l` for `long` and `unsigned long`, `ll` for `long long` and `unsigned long long` (since C++11).
* If the type of `val` is a floating-point type, the first applicable choice of the following is selected:
+ If `floatfield == [std::ios\_base::fixed](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, will use conversion specifier `%f`
+ If `floatfield == [std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags) && !uppercase`, will use conversion specifier `%e`
+ If `floatfield == [std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, will use conversion specifier `%E`
| | |
| --- | --- |
| * If `floatfield == ([std::ios\_base::fixed](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags) | [std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)) && !uppercase`, will use conversion specifier `%a`
* If `floatfield == ([std::ios\_base::fixed](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags) | [std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`, will use conversion specifier `%A`
| (since C++11) |
* If `!uppercase`, will use conversion specifier `%g`
* Otherwise, will use conversion specifier `%G`
Also: * If the type of `val` is `long double`, the length modifier `L` is added to the conversion specifier.
* Additionally, if `floatfield != (ios_base::fixed | ios_base::scientific)`, then (since C++11) precision modifier is added, set to `str.precision()`
* For both integer and floating-point types, if `showpos` is set, the modifier `+` is prepended
* For integer types, if `showbase` is set, the modifier `#` is prepended.
* For floating-point types, if `showpoint` is set, the modifier `#` is prepended.
* If the type of `val` is `void*`, will use conversion specifier `%p`
* A narrow character string is created as if by a call to `[std::printf](http://en.cppreference.com/w/cpp/io/c/fprintf)(spec, val)` in the "C" locale, where `spec` is the chosen conversion specifier.
#### Stage 2: locale-specific conversion
* Every character `c` obtained in Stage 1, other than the decimal point `'.'`, is converted to `CharT` by calling `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<CharT>>(str.getloc()).widen(c)`.
* For arithmetic types, the thousands separator character, obtained from `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<CharT>>(str.getloc()).thousands\_sep()`, is inserted into the sequence according to the grouping rules provided by `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<CharT>>(str.getloc()).grouping()`
* Decimal point characters (`'.'`) are replaced by `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)<CharT>>(str.getloc()).decimal\_point()`
#### Stage 3: padding
* The adjustment flag is obtained as if by `std::fmtflags adjustfield = (flags & ([std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)))` and examined to identify padding location, as follows:
+ If `adjustfield == [std::ios\_base::left](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, will pad after
+ If `adjustfield == [std::ios\_base::right](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, will pad before
+ If `adjustfield == [std::ios\_base::internal](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)` and a sign character occurs in the representation, will pad after the sign
+ If `adjustfield == [std::ios\_base::internal](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)` and Stage 1 representation began with 0x or 0X, will pad after the x or X
+ Otherwise, will pad before
* If `str.width()` is non-zero (e.g. `[std::setw](../../io/manip/setw "cpp/io/manip/setw")` was just used) and the number of `CharT`'s after Stage 2 is less than `str.width()`, then copies of the `fill` character are inserted at the position indicated by padding to bring the length of the sequence to `str.width()`.
In any case, `str.width(0)` is called to cancel the effects of `[std::setw](../../io/manip/setw "cpp/io/manip/setw")`.
#### Stage 4: output
Every successive character `c` from the sequence of `CharT`'s from Stage 3 is output as if by `*out++ = c`.
### Parameters
| | | |
| --- | --- | --- |
| out | - | iterator pointing to the first character to be overwritten |
| str | - | stream to retrieve the formatting information from |
| fill | - | padding character used when the results needs to be padded to the field width |
| val | - | value to convert to string and output |
### Return value
`out`.
### Notes
The leading zero generated by the conversion specification `#o` (resulting from the combination of `[std::showbase](../../io/manip/showbase "cpp/io/manip/showbase")` and `[std::oct](../../io/manip/hex "cpp/io/manip/hex")` for example) is not counted as a padding character.
| | |
| --- | --- |
| When formatting a floating point value as hexfloat (i.e., when `floatfield == ([std::ios\_base::fixed](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags) | [std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`), the stream's precision is not used; instead, the number is always printed with enough precision to exactly represent the value. | (since C++11) |
### Example
Output a number using the facet directly, and demonstrate user-defined facet:
```
#include <iostream>
#include <locale>
// this custom num_put outputs squares of all integers (except long long)
struct squaring_num_put : std::num_put<char>
{
iter_type do_put(iter_type out, std::ios_base& str,
char_type fill, long val) const
{
return std::num_put<char>::do_put(out, str, fill, val * val);
}
iter_type do_put(iter_type out, std::ios_base& str,
char_type fill, unsigned long val) const
{
return std::num_put<char>::do_put(out, str, fill, val * val);
}
};
int main()
{
auto& facet = std::use_facet<std::num_put<char>>(std::locale());
facet.put(std::cout, std::cout, '0', 2.71);
std::cout << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new squaring_num_put));
std::cout << 6 << ' ' << -12 << '\n';
}
```
Output:
```
2.71
36 144
```
An implementation of `operator<<` for a user-defined type.
```
#include <iostream>
#include <iterator>
#include <locale>
struct base { long x = 10; };
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<< (std::basic_ostream<CharT, Traits>& os, base const& b)
{
try
{
typename std::basic_ostream<CharT, Traits>::sentry s(os);
if (s)
{
std::ostreambuf_iterator<CharT, Traits> it(os);
std::use_facet<std::num_put<CharT>>(os.getloc())
.put(it, os, os.fill(), b.x);
}
}
catch (...)
{
// set badbit on os and rethrow if required
}
return os;
}
int main()
{
base b;
std::cout << b;
}
```
Output:
```
10
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 34](https://cplusplus.github.io/LWG/issue34) | C++98 | the `bool` overload used non-existing members`truename` and `falsename` of `[std::ctype](../ctype "cpp/locale/ctype")` | use these members of `[std::numpunct](../numpunct "cpp/locale/numpunct")` |
### See also
| | |
| --- | --- |
| [operator<<](../../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) |
| programming_docs |
cpp std::num_put<CharT,OutputIt>::num_put std::num\_put<CharT,OutputIt>::num\_put
=======================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit num_put( std::size_t refs = 0 );
```
| | |
Creates a `[std::num\_put](http://en.cppreference.com/w/cpp/locale/num_put)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::locale::id std::locale::id
===============
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class locale::id;
```
| | |
The class `std::locale::id` provides implementation-specific identification of a locale facet. Each class derived from `[std::locale::facet](facet "cpp/locale/locale/facet")` must have a public static member named `id` of type `std::locale::id` and each `[std::locale](../locale "cpp/locale/locale")` object maintains a list of facets it implements, indexed by their `id`s.
Facets with the same `id` belong to the same facet category and replace each other when added to a locale object.
### Member functions
| | |
| --- | --- |
| [(constructor)](id/id "cpp/locale/locale/id/id") | constructs a new id (public member function) |
| operator= | copy assignment operator is deleted (public member function) |
### Example
The following example shows how to construct a minimal custom facet.
```
#include <iostream>
#include <locale>
struct myfacet : std::locale::facet
{
myfacet(std::size_t refs = 0) : facet(refs) {}
static std::locale::id id;
};
std::locale::id myfacet::id;
int main()
{
std::locale myloc(std::locale(), new myfacet);
std::cout << "has_facet<myfacet>(myloc) returns " << std::boolalpha
<< std::has_facet<myfacet>(myloc) << '\n';
}
```
Output:
```
has_facet<myfacet>(myloc) returns true
```
### See also
| | |
| --- | --- |
| [facet](facet "cpp/locale/locale/facet") | the base class for all facet categories: each facet of any category is derived from this type (class) |
cpp std::locale::global std::locale::global
===================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
static locale global( const locale& loc );
```
| | |
Replaces the global C++ locale with `loc`, which means all future calls to the `[std::locale](../locale "cpp/locale/locale")` default constructor will now return a copy of `loc`. If `loc` has a name, also replaces the C locale as if by `[std::setlocale](http://en.cppreference.com/w/cpp/locale/setlocale)([LC\_ALL](http://en.cppreference.com/w/cpp/locale/LC_categories), loc.name().c\_str());`. This function is the only way to modify the global C++ locale, which is otherwise equivalent to `[std::locale::classic](http://en.cppreference.com/w/cpp/locale/locale/classic)()` at program startup.
### Parameters
| | | |
| --- | --- | --- |
| loc | - | the new global C++ locale |
### Return value
The previous value of the global C++ locale.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 8](https://cplusplus.github.io/LWG/issue8) | C++98 | it was unspecified whether other library functions (suchas `[std::setlocale](../setlocale "cpp/locale/setlocale")`) can modify the global C++ locale | specified (no otherlibrary functions allowed) |
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
| [classic](classic "cpp/locale/locale/classic")
[static] | obtains a reference to the "C" locale (public static member function) |
| [setlocale](../setlocale "cpp/locale/setlocale") | gets and sets the current C locale (function) |
cpp std::locale::~locale std::locale::~locale
====================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
~locale();
```
| | |
Non-virtual destructor which decrements reference counts of all facets held by `*this`. Those facets whose reference count becomes zero are deleted.
### Return value
(none).
### Example
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
cpp std::locale::operator() std::locale::operator()
=======================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits, class Alloc >
bool operator()( const basic_string<CharT,Traits,Alloc>& s1,
const basic_string<CharT,Traits,Alloc>& s2) const;
```
| | |
Compares two string arguments `s1` and `s2` according to the lexicographic comparison rules defined by this locale's `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)<charT>` facet. This operator allows any locale object that has a collate facet to be used as a binary predicate in the standard algorithms (such as `[std::sort](../../algorithm/sort "cpp/algorithm/sort")`) and ordered containers (such as `[std::set](../../container/set "cpp/container/set")`).
### Parameters
| | | |
| --- | --- | --- |
| s1 | - | the first string to compare |
| s2 | - | the second string to compare |
### Return value
`true` if `s1` is lexicographically less than `s2`, `false` otherwise.
### Possible implementation
| |
| --- |
|
```
template<class CharT, class Traits, class Alloc >
bool operator()(const std::basic_string<CharT,Traits,Alloc>& s1,
const std::basic_string<CharT,Traits,Alloc>& s2) const;
{
return std::use_facet<std::collate<CharT>>(*this).compare(
s1.data(), s1.data() + s1.size(),
s2.data(), s2.data() + s2.size() ) < 0;
}
```
|
### Example
A vector of strings can be sorted according to a non-default locale by using the locale object as comparator:
```
#include <locale>
#include <algorithm>
#include <vector>
#include <string>
#include <cassert>
int main()
{
std::vector<std::wstring> v = {L"жил", L"был", L"пёс"};
std::sort(v.begin(), v.end(), std::locale("ru_RU.UTF8"));
assert(v[0] == L"был");
assert(v[1] == L"жил");
assert(v[2] == L"пёс");
}
```
### See also
| | |
| --- | --- |
| [collate](../collate "cpp/locale/collate") | defines lexicographical comparison and hashing of strings (class template) |
cpp std::locale::combine std::locale::combine
====================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
template< class Facet >
locale combine( const locale& other ) const;
```
| | |
Constructs a locale object which is a copy of `*this` except for the facet of type `Facet`, which is copied from `other`.
### Return value
The new, nameless, locale.
### Exceptions
`[std::runtime\_error](../../error/runtime_error "cpp/error/runtime error")` if `other` does not implement `Facet`.
### Example
```
#include <iostream>
#include <locale>
int main()
{
const double number = 1000.25;
std::cout << "\"C\" locale: " << number << '\n';
std::locale loc = std::locale()
.combine<std::numpunct<char>>(std::locale("en_US.UTF8"));
std::cout.imbue(loc);
std::cout << "\"C\" locale with en_US numpunct: " << number << '\n';
}
```
Output:
```
"C" locale: 1000.25
"C" locale with en_US numpunct: 1,000.25
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 14](https://cplusplus.github.io/LWG/issue14) | C++98 | `locale::combine` was non-const | made const |
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
cpp std::locale::facet std::locale::facet
==================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
class locale::facet;
```
| | |
`std::locale::facet` is the base class for facets. It provides a common base class so that locales could store pointers to the facets they implement in a single indexed container, and it abstracts support for facet reference counting. Whenever a facet is added to a locale, the locale increments the reference count in the facet (through an implementation-specific mechanism). Whenever a locale is destructed or modified, it decrements the reference count in each facet it no longer implements. Whenever a facet's reference count becomes zero, the locale performs `delete static_cast<std::locale::facet*>(f)` where `f` is the pointer to the facet.
### Member functions
| | |
| --- | --- |
| [(constructor)](facet/facet "cpp/locale/locale/facet/facet") | constructs a new facet with specified reference count (protected member function) |
| operator= | the copy assignment operator is deleted (protected member function) |
| (destructor)
[virtual] | the destructor is protected virtual (virtual protected member function) |
### Example
### See also
| | |
| --- | --- |
| [id](id "cpp/locale/locale/id") | the facet index type: each facet class must declare or inherit a public static member of this type (class) |
cpp std::locale::locale std::locale::locale
===================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
| | (1) | |
|
```
locale() throw();
```
| (until C++11) |
|
```
locale() noexcept;
```
| (since C++11) |
| | (2) | |
|
```
locale( const locale& other ) throw();
```
| (until C++11) |
|
```
locale( const locale& other ) noexcept;
```
| (since C++11) |
|
```
explicit locale( const char* std_name );
```
| (3) | |
|
```
explicit locale( const std::string& std_name );
```
| (4) | (since C++11) |
|
```
locale( const locale& other, const char* std_name, category cat );
```
| (5) | |
|
```
locale( const locale& other, const std::string& std_name, category cat );
```
| (6) | (since C++11) |
|
```
template< class Facet >
locale( const locale& other, Facet* f );
```
| (7) | |
|
```
locale( const locale& other, const locale& one, category cat );
```
| (8) | |
Contstructs a new locale object.
1) Default constructor. Constructs a copy of the global C++ locale, which is the locale most recently used as the argument to `[std::locale::global](http://en.cppreference.com/w/cpp/locale/locale/global)` or a copy of `[std::locale::classic](http://en.cppreference.com/w/cpp/locale/locale/classic)` if no call to `[std::locale::global](http://en.cppreference.com/w/cpp/locale/locale/global)` has been made.
2) Copy constructor. Constructs a copy of `other`.
3-4) Constructs a copy of the system locale with specified `std_name` (such as `"C"`, or `"POSIX"`, or `"en_US.UTF-8"`, or `"English_US.1251"`), if such locale is supported by the operating system. The locale constructed in this manner has a name.
5-6) Constructs a copy of `other` except for all the facets identified by the `cat` argument, which are copied from the system locale identified by its `std_name`. The locale constructed in this manner has a name if and only if `other` has a name.
7) Constructs a copy of `other` except for the facet of type `Facet` (typically deduced from the type of the argument) which is installed from the argument `facet`. If `facet` is a null pointer, the constructed locale is a full copy of `other`. The locale constructed in this manner has no name.
8) Constructs a copy of `other` except for all the facets identified by the `cat` argument, which are copied from `one`. If both `other` and `one` have names, then the resulting locale also has a name. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another locale to copy |
| std\_name | - | name of the system locale to use |
| f | - | pointer to a facet to merge with `other` |
| cat | - | the locale category used to identify the facets to merge with `other` |
| one | - | another locale to take facets from |
### Exceptions
3,5) `[std::runtime\_error](../../error/runtime_error "cpp/error/runtime error")` if the operating system has no locale named `std_name` or if `std_name` is a null pointer.
4,6) `[std::runtime\_error](../../error/runtime_error "cpp/error/runtime error")` if the operating system has no locale named `std_name`.
7,8) May throw implementation-defined exceptions. ### Notes
Overload 7 is typically called with its second argument, `f`, obtained directly from a new-expression: the locale is responsible for calling the matching `delete` from its own destructor.
### Example
```
#include <codecvt>
#include <iostream>
#include <locale>
std::ostream& operator<< (std::ostream& os, std::locale const& loc)
{
if (loc.name().length() <= 80) { return os << loc.name() << '\n'; }
for (const auto c : loc.name())
{
c != ';' ? os << c : os << "\n ";
}
return os << '\n';
}
int main()
{
std::locale l1;
// l1 is a copy of the classic "C" locale
std::locale l2("en_US.UTF-8");
// l2 is a unicode locale
std::locale l3(l1, l2, std::locale::ctype);
// l3 is "C" except for ctype, which is unicode
std::locale l4(l1, new std::codecvt_utf8<wchar_t>);
// l4 is "C" except for codecvt
std::cout
<< "Locale names:\n"
<< "l1: " << l1 << "l2: " << l2
<< "l3: " << l3 << "l4: " << l4;
}
```
Possible output:
```
Locale names:
l1: C
l2: en_US.UTF-8
l3: LC_CTYPE=en_US.UTF-8
LC_NUMERIC=C
LC_TIME=C
LC_COLLATE=C
LC_MONETARY=C
LC_MESSAGES=C
LC_PAPER=C
LC_NAME=C
LC_ADDRESS=C
LC_TELEPHONE=C
LC_MEASUREMENT=C
LC_IDENTIFICATION=C
l4: *
```
### See also
| | |
| --- | --- |
| [(destructor)](~locale "cpp/locale/locale/~locale") | destructs the locale and the facets whose reference count becomes zero (public member function) |
cpp std::locale::operator= std::locale::operator=
======================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
const locale& operator=( const locale& other ) throw();
```
| | (until C++11) |
|
```
const locale& operator=( const locale& other ) noexcept;
```
| | (since C++11) |
Creates a copy of `other`, replacing the contents of `*this`. The reference counts of all facets held by `other` are incremented. The reference counts of all facets previously held by `*this` are decremented, and those facets whose reference count becomes zero are deleted.
### Return value
Returns `*this`, which is now a copy of `other`.
### Example
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
cpp std::locale::name std::locale::name
=================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
std::string name() const;
```
| | |
Returns the name of the locale, which is the name by which it is known to the operating system, such as `"POSIX"` or `"en_US.UTF8"` or `"English_United States.1252"`. If the locale is not a copy of a system-supplied locale, the string `"*"` is returned.
### Return value
The name of the locale or `"*"` if unnamed.
### Example
```
#include <locale>
#include <iostream>
#include <string>
int main()
{
std::locale loc(std::locale(), new std::ctype<char>);
std::cout << "The default locale is " << std::locale().name() << '\n'
<< "The user's locale is " << std::locale("").name() << '\n'
<< "A nameless locale is " << loc.name() << '\n';
}
```
Output:
```
The default locale is C
The user's locale is en_US.UTF8
A nameless locale is *
```
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
cpp std::locale::operator==, operator!= std::locale::operator==, operator!=
===================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
bool operator==( const locale& other ) const;
```
| (1) | |
|
```
bool operator!=( const locale& other ) const;
```
| (2) | (until C++20) |
Tests two locales for equality. Named locales are considered equal if their names are equal. Unnamed locales are considered equal if they are copies of each other.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| other | - | a `[std::locale](../locale "cpp/locale/locale")` object to compare |
### Return value
1) `true` if `other` is a copy of `*this` or has an identical name, `false` otherwise.
2) `false` if `other` is a copy of `*this` or has an identical name, `true` otherwise. ### Example
### See also
| | |
| --- | --- |
| [(constructor)](locale "cpp/locale/locale/locale") | constructs a new locale (public member function) |
| [name](name "cpp/locale/locale/name") | returns the name of the locale or "\*" if unnamed (public member function) |
cpp std::locale::classic std::locale::classic
====================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
static const locale& classic();
```
| | |
Obtains a reference to the C++ locale that implements the classic `"C"` locale semantics. This locale, unlike the global locale, cannot be altered.
### Parameters
none.
### Return value
Returns a reference to the `"C"` locale.
### Notes
Some of the standard-required facets, such as the UTF-8/UTF-32 conversion facet `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char32\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>`, have no equivalents in the `"C"` locale, but they are nevertheless present in the locale returned by `std::locale::classic()`, as in any other locale constructed in a C++ program.
### Example
### See also
| | |
| --- | --- |
| [global](global "cpp/locale/locale/global")
[static] | changes the global locale (public static member function) |
cpp std::locale::id::id std::locale::id::id
===================
| Defined in header `[<locale>](../../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
id();
```
| (1) | |
|
```
id(const id&) = delete;
```
| (2) | |
1) default constructor: creates an object of type `[std::locale::id](../id "cpp/locale/locale/id")` with implementation-specific content.
2) copy constructor is deleted; `[std::locale::id](../id "cpp/locale/locale/id")` is not copyable.
### Notes
Because locales and facets must be available for the IO stream objects with static storage duration, such as `[std::cout](../../../io/cout "cpp/io/cout")`, typical implementations let implicit default constructor zero-initialize the contents of `[std::locale::id](../id "cpp/locale/locale/id")` during static initialization (before constructors run for static objects), and when a facet is added to any locale for the first time, the locale completes initialization of the facet's `id`.
| programming_docs |
cpp std::locale::facet::facet std::locale::facet::facet
=========================
| Defined in header `[<locale>](../../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit facet( std::size_t refs = 0 );
```
| (1) | |
|
```
facet(const facet&) = delete;
```
| (2) | |
1) creates a facet with starting reference count `refs`. If `refs` is non-zero, the facet will not be deleted when the last locale referencing it goes out of scope. A facet with static or dynamic storage duration should always be constructed with a non-zero `refs`.
2) copy constructor is deleted; `[std::locale::facet](../facet "cpp/locale/locale/facet")` is not copyable.
cpp std::ctype<char>::ctype std::ctype<char>::ctype
=======================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit ctype( const mask* tbl = 0, bool del = false, std::size_t refs = 0);
```
| | |
Creates a `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
If `tbl` is null, `classic_table()` is used by all classification member functions. Otherwise, `tbl` must be a pointer to the first element of an array of masks, at least `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>::table\_size` in size, and that array is used by all of this facet's classification member functions.
If `del` is `true`, it is assumed that the array was allocated with `new[]`, and the destructor of this facet will call `delete[] tbl`.
### Parameters
| | | |
| --- | --- | --- |
| tbl | - | classification table to use or a null pointer |
| del | - | indicator whether the table needs to be deleted. |
| refs | - | starting reference count |
### Example
cpp std::ctype<char>::table std::ctype<char>::table
=======================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
const mask* table() const throw();
```
| | (until C++11) |
|
```
const mask* table() const noexcept;
```
| | (since C++11) |
Returns the classification table that was provided in the constructor of this instance of `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>`, or returns a copy of `classic_table()` if none was provided.
### Parameters
(none).
### Return value
A pointer to the first element in the classification table (which an array of size `std::ctype<char>::table_size`).
### Example
cpp std::ctype<char>::scan_is std::ctype<char>::scan\_is
==========================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
const char* scan_is (mask m, const char* beg, const char* end) const;
```
| (1) | |
Locates the first character in the character array `[beg, end)` that satisfies the classification mask `m`, that is, the first character `c` such that `table()[(unsigned char) c] & m` would return `true`.
If `(unsigned char)c >= [std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>::table\_size`, then an implementation-defined value is substituted instead of `table()[(unsigned char)c]`, possibly different for different values of `c`.
### Parameters
| | | |
| --- | --- | --- |
| m | - | mask to search for |
| beg | - | pointer to the first character in an array of characters to search |
| end | - | one past the end pointer for the array of characters to search |
### Return value
Pointer to the first character in `[beg, end)` that satisfies the mask, or `end` if no such character was found.
### Notes
Unlike the primary template `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)`, this specialization does not perform a virtual function call when classifying characters. To customize the behavior, a derived class may provide a non-default classification table to the base class constructor.
### Example
```
#include <locale>
#include <iostream>
#include <iterator>
int main()
{
std::locale loc("");
auto& f = std::use_facet<std::ctype<char>>(loc);
// skip until the first letter
char s1[] = " \t\t\n Test";
const char* p1 = f.scan_is(std::ctype_base::alpha, std::begin(s1), std::end(s1));
std::cout << "'" << p1 << "'\n";
// skip until the first letter
char s2[] = "123456789abcd";
const char* p2 = f.scan_is(std::ctype_base::alpha, std::begin(s2), std::end(s2));
std::cout << "'" << p2 << "'\n";
}
```
Output:
```
'Test'
'abcd'
```
### See also
| | |
| --- | --- |
| [do\_scan\_is](../ctype/scan_is "cpp/locale/ctype/scan is")
[virtual] | locates the first character in a sequence that conforms to given classification (virtual protected member function of `std::ctype<CharT>`) |
| [scan\_not](scan_not "cpp/locale/ctype char/scan not") | locates the first character in a sequence that fails given classification, using the classification table (public member function) |
cpp std::ctype<char>::~ctype std::ctype<char>::~ctype
========================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~ctype();
```
| | |
Destructs a `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` and implements a public destructor.
If, when this instance of `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` was constructed, a custom classification table was provided and the second argument to the constructor (the boolean `del`) was `true`, then this destructor executes `delete[] table()`.
cpp std::ctype<char>::classic_table std::ctype<char>::classic\_table
================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
static const mask* classic_table() throw();
```
| | (until C++11) |
|
```
static const mask* classic_table() noexcept;
```
| | (since C++11) |
Returns the classification table that matches the classification used by the minimal "C" locale.
### Parameters
(none).
### Return value
A pointer to the first element in the classification table (which an array of size `std::ctype<char>::table_size`).
### Notes
Default-constructed `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` facets use this table for classification.
### Example
cpp std::ctype<char>::is std::ctype<char>::is
====================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
bool is( mask m, char c ) const;
```
| (1) | |
|
```
const char* is( const char* low, const char* high, mask* vec ) const;
```
| (2) | |
1) Checks if the character `c` is classified by the mask `m` according to the classification table returned by the member function `table()`. Effectively calculates `table()[(unsigned char)c] & m`.
2) For every character in the character array `[low, high)`, reads its full classification mask from the classification table returned by the member function `table()` (that is, evaluates `table()[(unsigned char)*p]` and stores it in the corresponding element of the array pointed to by `vec`. If `(unsigned char)c >= [std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>::table\_size`, then an implementation-defined value is substituted instead of `table()[(unsigned char)c]`, possibly different for different values of `c`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | character to classify |
| m | - | mask to use for classifying a single character |
| low | - | pointer to the first character in an array of characters to classify |
| high | - | one past the end pointer for the array of characters to classify |
| vec | - | pointer to the first element of the array of masks to fill |
### Return value
1) `true` if `c` is classified by `m` in `table()`, `false` otherwise
2) `high`
### Notes
Unlike the primary template `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)`, this specialization does not perform a virtual function call when classifying characters. To customize the behavior, a derived class may provide a non-default classification table to the base class constructor.
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 28](https://cplusplus.github.io/LWG/issue28) | C++98 | overload (2) copied the values from `vec` into `table()`,which is the reverse of the intended behavior | corrected |
### See also
| | |
| --- | --- |
| [do\_is](../ctype/is "cpp/locale/ctype/is")
[virtual] | classifies a character or a character sequence (virtual protected member function of `std::ctype<CharT>`) |
cpp std::ctype<char>::scan_not std::ctype<char>::scan\_not
===========================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
const char* scan_not (mask m, const char* beg, const char* end) const;
```
| (1) | |
Locates the first character in the character array `[beg, end)` that does not satisfy the classification mask `m`, that is, the first character `c` such that `table()[(unsigned char)c] & m` would return `false`.
If `(unsigned char)c >= [std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>::table\_size`, then an implementation-defined value is substituted instead of `table()[(unsigned char)c]`, possibly different for different values of `c`.
### Parameters
| | | |
| --- | --- | --- |
| m | - | mask to search for |
| beg | - | pointer to the first character in an array of characters to search |
| end | - | one past the end pointer for the array of characters to search |
### Return value
Pointer to the first character in `[beg, end)` that does not satisfy the mask, or `end` if no such character was found.
### Notes
Unlike the primary template `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)`, this specialization does not perform a virtual function call when classifying characters. To customize the behavior, a derived class may provide a non-default classification table to the base class constructor.
### Example
```
#include <locale>
#include <iostream>
#include <iterator>
int main()
{
auto& f = std::use_facet<std::ctype<char>>(std::locale());
// skip leading whitespace
char s1[] = " \t\t\n Test";
const char* p1 = f.scan_not(std::ctype_base::space, std::begin(s1), std::end(s1));
std::cout << "'" << p1 << "'\n";
// skip leading digits
char s2[] = "123456789abcd";
const char* p2 = f.scan_not(std::ctype_base::digit, std::begin(s2), std::end(s2));
std::cout << "'" << p2 << "'\n";
}
```
Output:
```
'Test'
'abcd'
```
### See also
| | |
| --- | --- |
| [do\_scan\_not](../ctype/scan_not "cpp/locale/ctype/scan not")
[virtual] | locates the first character in a sequence that fails given classification (virtual protected member function of `std::ctype<CharT>`) |
| [scan\_is](scan_is "cpp/locale/ctype char/scan is") | locates the first character in a sequence that conforms to given classification, using the classification table (public member function) |
cpp std::numpunct<CharT>::numpunct std::numpunct<CharT>::numpunct
==============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit numpunct( std::size_t refs = 0 );
```
| | |
Creates a `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::numpunct<CharT>::thousands_sep, do_thousands_sep std::numpunct<CharT>::thousands\_sep, do\_thousands\_sep
========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
char_type thousands_sep() const;
```
| (1) | |
|
```
protected:
virtual char_type do_thousands_sep() const;
```
| (2) | |
1) Public member function, calls the member function `do_thousands_sep` of the most derived class.
2) Returns the character to be used as the separator between digit groups when parsing or formatting integers and integral parts of floating-point values. ### Return value
The object of type `char_type` to use as the thousands separator. The standard specializations of `std::numpunct` return `','` and `L','`.
### Example
```
#include <iostream>
#include <locale>
struct space_out : std::numpunct<char>
{
char do_thousands_sep() const { return ' '; } // separate with spaces
std::string do_grouping() const { return "\1"; } // groups of 1 digit
};
int main()
{
std::cout << "default locale: " << 12345678 << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new space_out));
std::cout << "locale with modified numpunct: " << 12345678 << '\n';
}
```
Output:
```
default locale: 12345678
locale with modified numpunct: 1 2 3 4 5 6 7 8
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 20](https://cplusplus.github.io/LWG/issue20) | C++98 | the return type was `string_type` | changed to `char_type` |
### See also
| | |
| --- | --- |
| [do\_grouping](grouping "cpp/locale/numpunct/grouping")
[virtual] | provides the numbers of digits between each pair of thousands separators (virtual protected member function) |
cpp std::numpunct<CharT>::decimal_point, do_decimal_point std::numpunct<CharT>::decimal\_point, do\_decimal\_point
========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
char_type decimal_point() const;
```
| (1) | |
|
```
protected:
virtual char_type do_decimal_point() const;
```
| (2) | |
1) Public member function, calls the member function `do_decimal_point` of the most derived class.
2) Returns the character to be used as the decimal separator between integer and fractional parts. ### Return value
The value of type `char_type` to use as the decimal separator. The standard specializations of `std::numpunct` return `'.'` and `L'.'`.
### Example
```
#include <iostream>
#include <locale>
struct slash : std::numpunct<char> {
char do_decimal_point() const { return '/'; } // separate with slash
};
int main()
{
std::cout.precision(10);
std::cout << "default locale: " << 1234.5678 << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new slash));
std::cout << "locale with modified numpunct: " << 1234.5678 << '\n';
}
```
Output:
```
default locale: 1234.5678
locale with modified numpunct: 1234/5678
```
cpp std::numpunct<CharT>::~numpunct std::numpunct<CharT>::~numpunct
===============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~numpunct();
```
| | |
Destructs a `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::numpunct](http://en.cppreference.com/w/cpp/locale/numpunct)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_numpunct : public std::numpunct<wchar_t>
{
Destructible_numpunct(std::size_t refs = 0) : numpunct(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_numpunct dc;
// std::numpunct<wchar_t> c; // compile error: protected destructor
}
```
cpp std::numpunct<CharT>::grouping, std::numpunct<CharT>::do_grouping std::numpunct<CharT>::grouping, std::numpunct<CharT>::do\_grouping
==================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
std::string grouping() const;
```
| (1) | |
|
```
protected:
virtual std::string do_grouping() const;
```
| (2) | |
1) Public member function, calls the member function `do_grouping` of the most derived class.
2) Returns an `[std::string](../../string/basic_string "cpp/string/basic string")` holding, in each `char` element, the number of digits in each group of the numeric output formatted by [`num_put::put()`](../num_put/put "cpp/locale/num put/put") (and, therefore, [`basic_ostream::operator<<`](../../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt")) The groups are stored as binary values: three-digit group is `'\3'`, and 51-digit group is `'3'`. The character at index zero of the returned string holds the number of digits in the rightmost group. The character at index 1 holds the number of digits in the second group from the right, etc. The grouping indicated by the last character in the returned string is reused to group all remaining digits in the (left part of) the number.
### Return value
The object of type `[std::string](../../string/basic_string "cpp/string/basic string")` holding the groups. The standard specializations of `std::numpunct` return an empty string, indicating no grouping. Typical groupings (e.g. the `en_US` locale) return `"\003"`.
### Example
```
#include <iostream>
#include <limits>
#include <locale>
struct space_out : std::numpunct<char>
{
char do_thousands_sep() const { return ' '; } // separate with spaces
std::string do_grouping() const { return "\1"; } // groups of 1 digit
};
struct g123 : std::numpunct<char>
{
std::string do_grouping() const { return "\1\2\3"; }
};
int main()
{
std::cout << "default locale: " << 12345678 << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new space_out));
std::cout << "locale with modified numpunct: " << 12345678 << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new g123));
std::cout << "Locale with \\1\\2\\3 grouping: " <<
std::numeric_limits<unsigned long long>::max() << '\n';
}
```
Output:
```
default locale: 12345678
locale with modified numpunct: 1 2 3 4 5 6 7 8
Locale with \1\2\3 grouping: 18,446,744,073,709,551,61,5
```
### See also
| | |
| --- | --- |
| [do\_thousands\_sep](thousands_sep "cpp/locale/numpunct/thousands sep")
[virtual] | provides the character to use as thousands separator (virtual protected member function) |
| programming_docs |
cpp std::numpunct<CharT>::truename, do_truename, falsename, do_falsename std::numpunct<CharT>::truename, do\_truename, falsename, do\_falsename
======================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
string_type truename() const;
```
| (1) | |
|
```
public:
string_type falsename() const;
```
| (2) | |
|
```
protected:
virtual string_type do_truename() const;
```
| (3) | |
|
```
protected:
virtual string_type do_falsename() const;
```
| (4) | |
1-2) Public member function, calls the member function `do_truename` and `do_falsename` of the most derived class respectively.
3) Returns the string to be used as the representation of the boolean value `true`.
4) Returns the string to be used as the representation of the boolean value `false`. ### Return value
1,3) The object of type `string_type` to use as the representation of `true`. The standard specializations of `std::numpunct` return `"true"` and `L"true"`.
2,4) The object of type `string_type` to use as the representation of `false`. The standard specializations of `std::numpunct` return `"false"` and `L"false"`. ### Example
```
#include <iostream>
#include <locale>
#include <iomanip>
struct custom_tf : std::numpunct<char> {
std::string do_truename() const { return "t"; }
std::string do_falsename() const { return "f"; }
};
int main()
{
std::cout << std::boolalpha;
// default boolalpha output
std::cout << "Default locale," << '\n'
<< " boolalpha true: " << true << '\n'
<< " boolalpha false: " << false << "\n\n";
// with custom_tf applied to locale
std::cout.imbue(std::locale(std::cout.getloc(), new custom_tf));
std::cout << "Locale with modified numpunct," << '\n'
<< " boolalpha true: " << true << '\n'
<< " boolalpha false: " << false << '\n';
}
```
Output:
```
Default locale,
boolalpha true: true
boolalpha false: false
Locale with modified numpunct,
boolalpha true: t
boolalpha false: f
```
cpp std::collate<CharT>::compare, std::collate<CharT>::do_compare std::collate<CharT>::compare, std::collate<CharT>::do\_compare
==============================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
int compare( const CharT* low1, const CharT* high1,
const CharT* low2, const CharT* high2 ) const;
```
| (1) | |
|
```
protected:
virtual int do_compare( const CharT* low1, const CharT* high1,
const CharT* low2, const CharT* high2 ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_compare` of the most derived class.
2) Compares the character sequence `[low1, high1)` to the character sequence `[low2, high2)`, using this locale's collation rules, and returns 1 if the first string follows the second, -1 if the first string precedes the second, zero if the two strings are equivalent. ### Parameters
| | | |
| --- | --- | --- |
| low1 | - | pointer to the first character of the first string |
| high1 | - | one past the end pointer for the first string |
| low2 | - | pointer to the first character of the second string |
| high2 | - | one past the end pointer for the second string |
### Return value
1 if the first string is greater than the second (that is, follows the second in the collation order), -1 if the first string is less than the second (precedes the second in the collation order), zero if the two strings are equivalent.
### Notes
When three-way comparison is not required (such as when providing a `Compare` argument to standard algorithms such as `[std::sort](../../algorithm/sort "cpp/algorithm/sort")`), [`std::locale::operator()`](../locale/operator() "cpp/locale/locale/operator()") may be more appropriate.
Collation order is the dictionary order: the position of the letter in the national alphabet (its *equivalence class*) has higher priority than its case or variant. Within an equivalence class, lowercase characters collate before their uppercase equivalents and locale-specific order may apply to the characters with diacritics. In some locales, groups of characters compare as single *collation units*. For example, `"ch"` in Czech follows `"h"` and precedes `"i"`, and `"dzs"` in Hungarian follows `"dz"` and precedes `"g"`.
### Example
```
#include <iostream>
#include <string>
#include <locale>
template<typename CharT>
void try_compare(const std::locale& l, const CharT* p1, const CharT* p2)
{
auto& f = std::use_facet<std::collate<CharT>>(l);
std::basic_string<CharT> s1(p1), s2(p2);
if(f.compare(&s1[0], &s1[0] + s1.size(),
&s2[0], &s2[0] + s2.size() ) < 0)
std::wcout << p1 << " before " << p2 << '\n';
else
std::wcout << p2 << " before " << p1 << '\n';
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wcout << "In the American locale: ";
try_compare(std::locale(), "hrnec", "chrt");
std::wcout << "In the Czech locale: ";
try_compare(std::locale("cs_CZ.utf8"), "hrnec", "chrt");
std::wcout << "In the American locale: ";
try_compare(std::locale(), L"år", L"ängel");
std::wcout << "In the Swedish locale: ";
try_compare(std::locale("sv_SE.utf8"), L"år", L"ängel");
}
```
Output:
```
In the American locale: chrt before hrnec
In the Czech locale: hrnec before chrt
In the American locale: ängel before år
In the Swedish locale: år before ängel
```
### See also
| | |
| --- | --- |
| [strcoll](../../string/byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [wcscoll](../../string/wide/wcscoll "cpp/string/wide/wcscoll") | compares two wide strings in accordance to the current locale (function) |
| [operator()](../locale/operator() "cpp/locale/locale/operator()") | lexicographically compares two strings using this locale's collate facet (public member function of `std::locale`) |
cpp std::collate<CharT>::transform, do_transform std::collate<CharT>::transform, do\_transform
=============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
string_type transform( const CharT* low, const CharT* high ) const;
```
| (1) | |
|
```
protected:
virtual string_type do_transform( const CharT* low, const CharT* high ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_transform` of the most derived class.
2) Converts the character sequence `[low, high)` to a string that, compared lexicographically (e.g. with `operator<` for strings) with the result of calling `transform()` on another string, produces the same result as calling `[do\_compare()](compare "cpp/locale/collate/compare")` on the same two strings. ### Parameters
| | | |
| --- | --- | --- |
| low | - | pointer to the first character in the sequence to transform |
| high | - | one past the end pointer for the sequence to transform |
### Return value
The string transformed so that lexicographic comparison of the transformed strings may be used instead of collating of the originals. In the "C" locale, the returned string is the exact copy of `[low, high)`. In other locales, the contents of the returned string are implementation-defined, and the size may be considerably longer.
### Notes
In addition to the use in collation, the implementation-specific format of the transformed string is known to [std::regex\_traits<>::transform\_primary](../../regex/regex_traits/transform_primary "cpp/regex/regex traits/transform primary"), which is able to extract the equivalence class information.
### Example
```
#include <iostream>
#include <iomanip>
#include <locale>
int main()
{
std::locale::global(std::locale("sv_SE.utf8"));
auto& f = std::use_facet<std::collate<wchar_t>>(std::locale());
std::wstring in1 = L"\u00e4ngel";
std::wstring in2 = L"\u00e5r";
std::wstring out1 = f.transform(&in1[0], &in1[0] + in1.size());
std::wstring out2 = f.transform(&in2[0], &in2[0] + in2.size());
std::wcout << "In the Swedish locale: ";
if(out1 < out2)
std::wcout << in1 << " before " << in2 << '\n';
else
std::wcout << in2 << " before " << in1 << '\n';
std::wcout << "In lexicographic comparison: ";
if(in1 < in2)
std::wcout << in1 << " before " << in2 << '\n';
else
std::wcout << in2 << " before " << in1 << '\n';
}
```
Output:
```
In the Swedish locale: år before ängel
In lexicographic comparison: ängel before år
```
### See also
| | |
| --- | --- |
| [strxfrm](../../string/byte/strxfrm "cpp/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| [wcsxfrm](../../string/wide/wcsxfrm "cpp/string/wide/wcsxfrm") | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
cpp std::collate<CharT>::collate std::collate<CharT>::collate
============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit collate( std::size_t refs = 0 );
```
| | |
Creates a `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::collate<CharT>::hash, std::collate<CharT>::do_hash std::collate<CharT>::hash, std::collate<CharT>::do\_hash
========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
long hash( const CharT* beg, const CharT* end ) const;
```
| (1) | |
|
```
protected:
virtual long do_hash( const CharT* beg, const CharT* end ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_hash` of the most derived class.
2) Converts the character sequence `[beg, end)` to an integer value that is equal to the hash obtained for all strings that collate equivalent in this locale (`[compare()](compare "cpp/locale/collate/compare")` returns `0`). For two strings that do not collate equivalent, the probability that their hashes are equal should be very small, approaching `1.0/[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned long>::max()`. ### Parameters
| | | |
| --- | --- | --- |
| beg | - | pointer to the first character in the sequence to hash |
| end | - | one past the end pointer for the sequence to hash |
### Return value
The hash value that respects collation order.
### Note
The system-supplied locales normally do not collate two strings as equivalent (`[compare()](compare "cpp/locale/collate/compare")` does not return `0`) if [`basic_string::operator==`](../../string/basic_string/operator_cmp "cpp/string/basic string/operator cmp") returns `false`, but a user-installed `[std::collate](../collate "cpp/locale/collate")` facet may provide different collation rules, for example, it may treat strings as equivalent if they have the same Unicode normalized form.
### Example
Demonstrates a locale-aware unordered container.
```
#include <iostream>
#include <string>
#include <locale>
#include <unordered_set>
struct CollateHash {
template<typename CharT>
long operator()(const std::basic_string<CharT>& s) const
{
return std::use_facet<std::collate<CharT>>(std::locale()).hash(
&s[0], &s[0] + s.size()
);
}
};
struct CollateEq {
template<typename CharT>
bool operator()(const std::basic_string<CharT>& s1,
const std::basic_string<CharT>& s2) const
{
return std::use_facet<std::collate<CharT>>(std::locale()).compare(
&s1[0], &s1[0] + s1.size(),
&s2[0], &s2[0] + s2.size()
) == 0;
}
};
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::unordered_set<std::wstring, CollateHash, CollateEq> s2 = {L"Foo", L"Bar"};
for(auto& str: s2)
std::wcout << str << ' ';
std::cout << '\n';
}
```
Possible output:
```
Bar Foo
```
### See also
| | |
| --- | --- |
| [std::hash<std::string>std::hash<std::u8string>std::hash<std::u16string>std::hash<std::u32string>std::hash<std::wstring>std::hash<std::pmr::string>std::hash<std::pmr::u8string>std::hash<std::pmr::u16string>std::hash<std::pmr::u32string>std::hash<std::pmr::wstring>](../../string/basic_string/hash "cpp/string/basic string/hash")
(C++11)(C++20)(C++11)(C++11)(C++11)(C++17)(C++20)(C++17)(C++17)(C++17) | hash support for strings (class template specialization) |
cpp std::collate<CharT>::~collate std::collate<CharT>::~collate
=============================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~collate();
```
| | |
Destructs a `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::collate](http://en.cppreference.com/w/cpp/locale/collate)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_collate : public std::collate<wchar_t>
{
Destructible_collate(std::size_t refs = 0) : collate(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_collate dc;
// std::collate<wchar_t> c; // compile error: protected destructor
}
```
cpp std::money_get<CharT,InputIt>::~money_get std::money\_get<CharT,InputIt>::~money\_get
===========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~money_get();
```
| | |
Destructs a `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_money_get : public std::money_get<wchar_t>
{
Destructible_money_get(std::size_t refs = 0) : money_get(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_money_get dc;
// std::money_get<wchar_t> c; // compile error: protected destructor
}
```
cpp std::money_get<CharT,InputIt>::money_get std::money\_get<CharT,InputIt>::money\_get
==========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit money_get( std::size_t refs = 0 );
```
| | |
Creates a `[std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::money_get<CharT,InputIt>::get, do_get std::money\_get<CharT,InputIt>::get, do\_get
============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get(iter_type beg, iter_type end, bool intl, std::ios_base& str,
std::ios_base::iostate& err, long double& units) const;
```
| (1) | |
|
```
iter_type get(iter_type beg, iter_type end, bool intl, std::ios_base& str,
std::ios_base::iostate& err, string_type& digits) const;
```
| (2) | |
|
```
protected:
virtual iter_type do_get(iter_type beg, iter_type end, bool intl, std::ios_base& str,
std::ios_base::iostate& err, long double& units) const;
```
| (3) | |
|
```
virtual iter_type do_get(iter_type beg, iter_type end, bool intl, std::ios_base& str,
std::ios_base::iostate& err, string_type& digits) const;
```
| (4) | |
Parses monetary value from an input iterator and writes the result to a `long double` or string.
1-2) Public member functions, call the member function `do_get` of the most derived class.
3-4) Reads characters from the input iterator `beg`, expecting to find a monetary value formatted according to the rules specified by the `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)` facet imbued in `str.getloc()` (`ct` for the rest of this page), the `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<CharT, intl>` facet imbued in `str.getloc()` (`mp` for the rest of this page), and the stream formatting flags obtained from `str.flags()`. If the input iterator `beg` becomes equal to `end` before the parsing was completed, sets both `failbit` and `eofbit` in `err`. If parsing fails for another reason, sets the `failbit` in `err`. Either way, does not modify the output parameter ((`units` or `digits`) on error.
If the parsing succeeds, does not change `err`, and stores the result in `units` or `digits`.
The formatting `[pattern](../money_base "cpp/locale/money base")` used by this function is always `mp.neg_format()`.
If `mp.grouping()` does not permit thousands separators, the first separator encountered is treated as a parsing error, otherwise they are treated as optional.
If `money_base::space` or `money_base::none` is the last element in the `[pattern](../money_base "cpp/locale/money base")`, the parser does not attempt to consume any whitespace after the other components of the monetary value were parsed. Otherwise, one or more whitespace characters are consumed where `money_base::space` appears.
If `showbase` flag is set in `str.flags()`, the currency symbol or currency string is required, if it is not set, the currency symbol is optional.
If the first character of the string returned by `mp.positive_sign()` or `mp.negative_sign()` is found in the `money_base::sign` position of the formatting pattern, it is consumed, and the rest of the characters in that string are expected and consumed after all other components of the monetary value. If both `mp.positive_sign()` and `mp.negative_sign()` are non-empty, the sign is required and must match the first character of one of these strings. If one of theses strings is empty, the sign is optional (and if it is absent, the sign of the result corresponds to the string that was empty). If both strings are empty, or have the same first character, the result is given the positive sign. If the output parameter is a string (`digits`) and the result is negative, the value `ct.widen('-')` is stored as the first character of the result.
Digits from the input are extracted in order in which they appear and are placed in `digits` (after widening by `ct.widen()` as necessary), or into a temporary buffer `buf1`, from which the value of `units` is constructed as if by.
```
static const char src[] = "0123456789-";
CharT atoms[sizeof(src)];
ct.widen(src, src + sizeof(src) - 1, atoms);
for (int i = 0; i < n; ++i)
buf2[i] = src[find(atoms, atoms+sizeof(src), buf1[i]) - atoms];
buf2[n] = 0;
sscanf(buf2, "%Lf", &units);
```
(where `n` is the number of characters extracted from the input and stored in `buf1` and `buf2` is another sufficiently large character buffer).
### Return value
An iterator pointing immediately after the last character recognized as a valid part of the monetary string input.
### Notes
The currency units are assumed to be the smallest non-fractional units of the currency: cents in the U.S, yen in Japan. Thus, the input sequence `"$1,056.23"` in a U.S. locale produces the number `105623.0` in `units` or a string `"105623"` in `digits`.
Because currency symbol is optional if `showbase` is off but the entire multicharacter `negative_sign()` is required, given the formatting pattern `{sign, value, space, symbol}` with `showbase` off and negative\_sign of `"-"`, the string `"-1.23 €"` parses as `-123` and leaves "€" unconsumed on the input stream, but if negative\_sign is `"()"`, the string `"(1.23 €)"` is consumed completely.
The I/O manipulator `[std::get\_money](../../io/manip/get_money "cpp/io/manip/get money")` offers a simpler interface to this function.
### Example
```
#include <iostream>
#include <sstream>
#include <locale>
void demo_money_get(std::locale loc, const std::string& input)
{
std::istringstream str(input);
str.imbue(loc);
long double units;
// note, the following can be written simple with std::get_money(units)
std::ios_base::iostate err = std::ios_base::goodbit;
std::istreambuf_iterator<char> ret =
std::use_facet<std::money_get<char>>(loc).get(
std::istreambuf_iterator<char>(str),
std::istreambuf_iterator<char>(),
false, str, err, units);
str.setstate(err);
std::istreambuf_iterator<char> last{};
if(str) {
std::cout << "Successfully parsed '" << str.str() << "' as "
<< units/100 << " units\n";
if(ret != last) {
std::cout << "Remaining content: '";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
std::cout << "'\n";
} else {
std::cout << "The input was fully consumed\n";
}
} else {
std::cout << "Parse failed. Unparsed string: '";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
std::cout << "'\n";
}
}
int main()
{
demo_money_get(std::locale("en_US.utf8"), "-$5.12 abc");
demo_money_get(std::locale("ms_MY.utf8"), "(RM5.12) def");
}
```
Output:
```
Successfully parsed '-$5.12 abc' as -5.12 units
Remaining content: ' abc'
Successfully parsed '(RM5.12) def' as -5.12 units
Remaining content: ' def'
```
### See also
| | |
| --- | --- |
| [moneypunct](../moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](../money_get "cpp/locale/money get")` and `[std::money\_put](../money_put "cpp/locale/money put")` (class template) |
| [money\_get](../money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) |
| [get\_money](../../io/manip/get_money "cpp/io/manip/get money")
(C++11) | parses a monetary value (function template) |
| programming_docs |
cpp std::money_put<CharT,OutputIt>::~money_put std::money\_put<CharT,OutputIt>::~money\_put
============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~money_put();
```
| | |
Destructs a `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_money_put : public std::money_put<wchar_t>
{
Destructible_money_put(std::size_t refs = 0) : money_put(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_money_put dc;
// std::money_put<wchar_t> c; // compile error: protected destructor
}
```
cpp std::money_put<CharT,OutputIt>::money_put std::money\_put<CharT,OutputIt>::money\_put
===========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit money_put( std::size_t refs = 0 );
```
| | |
Creates a `[std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::money_put<CharT,OutputIt>::put, do_put std::money\_put<CharT,OutputIt>::put, do\_put
=============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type put(iter_type out, bool intl, std::ios_base& f,
char_type fill, long double quant) const;
```
| (1) | |
|
```
iter_type put(iter_type out, bool intl, std::ios_base& f,
char_type fill, const string_type& quant) const;
```
| (2) | |
|
```
protected:
virtual iter_type do_put(iter_type out, bool intl, std::ios_base& str,
char_type fill, long double units) const;
```
| (3) | |
|
```
virtual iter_type do_put(iter_type out, bool intl, std::ios_base& str,
char_type fill, const string_type& digits) const;
```
| (4) | |
Formats monetary value and writes the result to output stream.
1-2) Public member functions, call the member function `do_put` of the most derived class.
3) The numeric arguments `units` is converted to a wide character string as if by `ct.widen(buf1, buf1 + [std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf1, "%.0Lf", units), buf2)`, where `ct` is the `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)` facet imbued in `str.getloc()` and `buf1` and `buf2` are sufficiently large character buffers. The resulting character string `buf2` is processed, formatted, and output to `out` as desribed below.
4) From the string argument `digits`, only the optional leading minus sign (as determined by comparing to `ct.widen('-')`, where `ct` is the `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)` facet imbued in `str.getloc()`) and the immediately following digit characters (as classified by `ct`) are taken as the character sequence to be processed, formatted, and output to `out` as described below. Given the character sequence from the previous steps, if the first character equals `ct.widen('-')`, calls `mp.neg_format()` to obtain the formatting `[pattern](../money_base "cpp/locale/money base")`, otherwise calls `mp.pos_format()`, where `mp` is the `[std::moneypunct](http://en.cppreference.com/w/cpp/locale/moneypunct)<CharT, intl>` facet imbued in `str.getloc()`.
Thousands separator and decimal point characters are inserted as required by `mp.grouping()`, `mp.frac_digits()`, `mp.decimal_point()`, and `mp.thousands_sep()`, and the resulting string is placed in the output sequence where `[value](../money_base "cpp/locale/money base")` appears in the formatting pattern.
If `str.flags() & str.showbase` is non-zero (the `[std::showbase](http://en.cppreference.com/w/cpp/io/manip/showbase)` manipulator was used), then the currency symbol or string is generated by calling `mp.curr_symbol()` and placed in the output sequence where `[symbol](../money_base "cpp/locale/money base")` appears in the formatting pattern.
If `mp.positive_sign()` (in case positive format pattern is used) or `mp.negative_sign()` (in case negative format pattern is used) returns a string with more than one character, the first character returned is placed in the output sequence where `[sign](../money_base "cpp/locale/money base")` appears in the formatting pattern, and the rest of the characters are placed after all other characters, for example, formatting pattern `{sign, value, space, symbol}` with units `123` and negative\_sign of `"-"` may result in `"-1.23 €"`, while negative\_sign of `"()"` would generate `"(1.23 €)"`.
If the number of characters generated for the specified format is less than the value returned by `str.width()`, then copies of `fill` are inserted to bring the total length of the output sequence to exactly `str.width()`, as follows:
* If `str.flags() & str.adjustfield` equals `str.internal`, the fill characters are inserted where `none` or `space` appears in the formatting pattern.
* Otherwise, if `str.flags() & str.adjustfield` equals `str.left`, the copies of `fill` are appended after all other characters
* Otherwise, the fill characters are placed before all other characters.
In the end, calls `str.width(0)` to cancel the effects of any `[std::setw](http://en.cppreference.com/w/cpp/io/manip/setw)`.
### Return value
An iterator pointing immediately after the last character produced.
### Notes
The currency units are assumed to be the smallest non-fractional units of the currency: cents in the U.S, yen in Japan.
### Example
```
#include <iostream>
#include <iomanip>
#include <locale>
struct my_punct : std::moneypunct_byname<char, false> {
my_punct(const char* name) : moneypunct_byname(name) {}
string_type do_negative_sign() const { return "()"; }
};
int main()
{
std::locale loc("ru_RU.utf8");
std::cout.imbue(loc);
long double units = -123.45;
std::cout << "In Russian locale, " << units << " prints as "
<< std::showbase;
// note, the following is equivalent to simply std::put_money(units)
std::use_facet<std::money_put<char>>(loc).put(
{std::cout}, false, std::cout, std::cout.fill(), units);
std::cout << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new my_punct("ru_RU.utf8")));
std::cout << "With negative_sign set to \"()\", it prints as ";
std::use_facet<std::money_put<char>>(loc).put(
{std::cout}, false, std::cout, std::cout.fill(), units);
std::cout << '\n';
}
```
Output:
```
In Russian locale, -123,45 prints as -1.23 руб
With negative_sign set to "()", it prints as (1.23 руб)
```
### See also
| | |
| --- | --- |
| [moneypunct](../moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](../money_get "cpp/locale/money get")` and `[std::money\_put](../money_put "cpp/locale/money put")` (class template) |
| [money\_get](../money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) |
| [put\_money](../../io/manip/put_money "cpp/io/manip/put money")
(C++11) | formats and outputs a monetary value (function template) |
cpp std::wbuffer_convert<Codecvt,Elem,Tr>::~wbuffer_convert std::wbuffer\_convert<Codecvt,Elem,Tr>::~wbuffer\_convert
=========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
~wbuffer_convert();
```
| | |
Destroys the `wbuffer_convert` object and deletes the pointer to the conversion facet.
### Notes
Some implementations are able to delete any facet, including the locale-specific facets with protected destructors. Other implementations require the facet to have a public destructor, similar to the locale-independent facets from [`<codecvt>`](../../header/codecvt "cpp/header/codecvt").
### Example
```
#include <locale>
#include <utility>
#include <iostream>
#include <codecvt>
// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template<class Facet>
struct deletable_facet : Facet
{
template<class ...Args>
deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
int main()
{
// GB18030 / UCS4 conversion, using locale-based facet directly
// typedef std::codecvt_byname<char32_t, char, std::mbstate_t> gbfacet_t;
// Compiler error: "calling a protected destructor of codecvt_byname<> in ~wbuffer_convert"
// std::wbuffer_convert<gbfacet_t, char32_t> gbto32(std::cout.rdbuf(),
// new gbfacet_t("zh_CN.gb18030"));
// GB18030 / UCS4 conversion facet using a facet with public destructor
typedef deletable_facet<std::codecvt_byname<char32_t, char, std::mbstate_t>> gbfacet_t;
std::wbuffer_convert<gbfacet_t, char32_t> gbto32(std::cout.rdbuf(),
new gbfacet_t("zh_CN.gb18030"));
} // destructor called here
```
### See also
| | |
| --- | --- |
| [(destructor)](../wstring_convert/~wstring_convert "cpp/locale/wstring convert/~wstring convert") | destructs the wstring\_convert and its conversion facet (public member function of `std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>`) |
cpp std::wbuffer_convert<Codecvt,Elem,Tr>::rdbuf std::wbuffer\_convert<Codecvt,Elem,Tr>::rdbuf
=============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
std::streambuf* rdbuf() const;
```
| (1) | |
|
```
std::streambuf* rdbuf( std::streambuf* bytebuf );
```
| (2) | |
1) returns the pointer to the underlying byte stream.
2) replaces the associated byte stream with `bytebuf` .
### Return value
1) the current underlying byte stream.
2) the previous byte stream.
### Example
```
#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
int main()
{
// convert UTF-8 to UCS4
std::stringbuf utf8buf(u8"z\u00df\u6c34\U0001d10b"); // or u8"zß水𝄋"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
std::wbuffer_convert<std::codecvt_utf8<wchar_t>> conv(&utf8buf);
std::wistream ucsbuf(&conv);
std::cout << "Reading from a UTF-8 stringbuf via wbuffer_convert:\n";
for(wchar_t c; ucsbuf.get(c); )
std::cout << std::hex << std::showbase << c << '\n';
// reuse the same wbuffer_convert to handle UCS4 to UTF-8 output
conv.rdbuf(std::cout.rdbuf());
std::wostream out(&conv);
std::cout << "Sending UCS4 data to std::cout via wbuffer_convert:\n";
out << L"z\u00df\u6c34\U0001d10b\n";
}
```
Output:
```
Reading from a UTF-8 stringbuf via wbuffer_convert:
0x7a
0xdf
0x6c34
0x1d10b
Sending UCS4 data to std::cout via wbuffer_convert:
zß水𝄋
```
### See also
| | |
| --- | --- |
| [(constructor)](wbuffer_convert "cpp/locale/wbuffer convert/wbuffer convert") | constructs a new wbuffer\_convert (public member function) |
cpp std::wbuffer_convert<Codecvt,Elem,Tr>::wbuffer_convert std::wbuffer\_convert<Codecvt,Elem,Tr>::wbuffer\_convert
========================================================
| | | |
| --- | --- | --- |
|
```
wbuffer_convert() : wbuffer_convert(nullptr) { }
```
| (1) | |
|
```
explicit wbuffer_convert( std::streambuf* bytebuf,
Codecvt* pcvt = new Codecvt,
state_type state = state_type() );
```
| (2) | |
|
```
wbuffer_convert(const std::wbuffer_convert&) = delete;
```
| (3) | (since C++14) |
1) Default constructor.
2) Constructs the `wbuffer_convert` object with the specified underlying byte stream, specified `codecvt` facet, and specified initial conversion state (all parameters are optional)
3) The copy constructor is deleted, `wbuffer_convert` is not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible")
### Parameters
| | | |
| --- | --- | --- |
| bytebuf | - | pointer to std::streambuf to serve as the underlying narrow character stream |
| pcvt | - | pointer to a standalone (not managed by a locale) `[std::codecvt](../codecvt "cpp/locale/codecvt")` facet. The behavior is undefined if this pointer is null. |
| state | - | the initial value of the character conversion state |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P0935R0](https://wg21.link/P0935R0) | C++11 | default constructor was explicit | made implicit |
### Example
```
#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
int main()
{
// wrap a UTF-8 string stream in a UCS4 wbuffer_convert
std::stringbuf utf8buf(u8"z\u00df\u6c34\U0001f34c"); // or u8"zß水🍌"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c";
std::wbuffer_convert<std::codecvt_utf8<wchar_t>> conv_in(&utf8buf);
std::wistream ucsbuf(&conv_in);
std::cout << "Reading from a UTF-8 stringbuf via wbuffer_convert:\n";
for(wchar_t c; ucsbuf.get(c); )
std::cout << std::hex << std::showbase << c << '\n';
// wrap a UTF-8 aware std::cout in a UCS4 wbuffer_convert to output UCS4
std::wbuffer_convert<std::codecvt_utf8<wchar_t>> conv_out(std::cout.rdbuf());
std::wostream out(&conv_out);
std::cout << "Sending UCS4 data to std::cout via wbuffer_convert:\n";
out << L"z\u00df\u6c34\U0001f34c\n";
}
```
Output:
```
Reading from a UTF-8 stringbuf via wbuffer_convert produces
0x7a
0xdf
0x6c34
0x1f34c
Sending UCS4 data to std::cout via wbuffer_convert:
zß水🍌
```
cpp std::wbuffer_convert<Codecvt,Elem,Tr>::state std::wbuffer\_convert<Codecvt,Elem,Tr>::state
=============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
state_type state() const;
```
| | |
Returns the current value of the conversion state, which is stored in this `wbuffer_convert` object. The conversion state may be explicitly set in the constructor and is updated by all conversion operations.
### Return value
The current conversion state.
### Example
### See also
| | |
| --- | --- |
| [state](../wstring_convert/state "cpp/locale/wstring convert/state") | returns the current conversion state (public member function of `std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>`) |
| [mbsinit](../../string/multibyte/mbsinit "cpp/string/multibyte/mbsinit") | checks if the mbstate\_t object represents initial shift state (function) |
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>:: ~wstring_convert std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>:: ~wstring\_convert
===============================================================================
| | | |
| --- | --- | --- |
|
```
~wstring_convert();
```
| | |
Destroys the `wstring_convert` object and deletes the pointer to the conversion facet.
### Notes
Some implementations are able to delete any facet, including the locale-specific facets with protected destructors. Other implementations require the facet to have a public destructor, similar to the locale-independent facets from [`<codecvt>`](../../header/codecvt "cpp/header/codecvt"). This is [LWG issue 721](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#721).
### Example
```
#include <locale>
#include <utility>
#include <codecvt>
// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template<class Facet>
struct deletable_facet : Facet
{
template<class ...Args>
deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
int main()
{
// GB18030 / UCS4 conversion, using locale-based facet directly
// typedef std::codecvt_byname<char32_t, char, std::mbstate_t> gbfacet_t;
// Compiler error: "calling a protected destructor of codecvt_byname<> in ~wstring_convert"
// std::wstring_convert<gbfacet_t> gbto32(new gbfacet_t("zh_CN.gb18030"));
// GB18030 / UCS4 conversion facet using a facet with public destructor
typedef deletable_facet<std::codecvt_byname<char32_t, char, std::mbstate_t>> gbfacet_t;
std::wstring_convert<gbfacet_t> gbto32(new gbfacet_t("zh_CN.gb18030"));
} // destructor called here
```
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::converted std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>::converted
======================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
std::size_t converted() const noexcept;
```
| | |
Returns the number of source characters that were processed by the most recent `[from\_bytes()](from_bytes "cpp/locale/wstring convert/from bytes")` or `[to\_bytes()](to_bytes "cpp/locale/wstring convert/to bytes")`.
### Return value
The number of characters consumed by the most recent conversion operation.
### Example
```
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main()
{
std::string utf8 = u8"z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
std::cout << "original UTF-8 string size: " << utf8.size() << '\n';
// the UTF-8 - UTF-32 standard conversion facet
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> cvt;
// UTF-8 to UTF-32
std::u32string utf32 = cvt.from_bytes(utf8);
std::cout << "UTF-32 string size: " << utf32.size() << '\n';
std::cout << "converted() == " << cvt.converted() << '\n';
// UTF-32 to UTF-8
utf8 = cvt.to_bytes(utf32);
std::cout << "new UTF-8 string size: " << utf8.size() << '\n';
std::cout << "converted() == " << cvt.converted() << '\n';
}
```
Output:
```
original UTF-8 string size: 10
UTF-32 string size: 4
converted() == 10
new UTF-8 string size: 10
converted() == 4
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2174](https://cplusplus.github.io/LWG/issue2174) | C++11 | `wstring_convert::converted` was not required to be noexcept | required |
### See also
| | |
| --- | --- |
| [to\_bytes](to_bytes "cpp/locale/wstring convert/to bytes") | converts a wide string into a byte string (public member function) |
| [from\_bytes](from_bytes "cpp/locale/wstring convert/from bytes") | converts a byte string into a wide string (public member function) |
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::wstring_convert std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>::wstring\_convert
=============================================================================
| | | |
| --- | --- | --- |
|
```
wstring_convert() : wstring_convert( new Codecvt ) { }
```
| (1) | |
|
```
explicit wstring_convert( Codecvt* pcvt );
```
| (2) | |
|
```
wstring_convert( Codecvt* pcvt, state_type state);
```
| (3) | |
|
```
explicit wstring_convert( const byte_string& byte_err,
const wide_string& wide_err = wide_string() );
```
| (4) | |
|
```
wstring_convert(const std::wstring_convert&) = delete;
```
| (5) | (since C++14) |
1) Default constructor.
2) Constructs the `wstring_convert` object with a specified conversion facet, using default-constructed values for the shift state and the error strings
3) Constructs the `wstring_convert` object with a specified conversion facet and specified shift state, using default-constructed values for the error strings
4) Constructs the `wstring_convert` object with specified error strings, using `new Codecvt` as the conversion facet and the default-constructed `state_type` as shift state.
5) The copy constructor is deleted, wstring\_convert is not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible")
### Parameters
| | | |
| --- | --- | --- |
| pcvt | - | pointer to the conversion facet of type `Codecvt` (behavior is undefined if this pointer is null) |
| state | - | initial value of the conversion shift state |
| byte\_err | - | narrow string to display on errors |
| wide\_err | - | wide string to display on errors |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P0935R0](https://wg21.link/P0935R0) | C++11 | default constructor was explicit | made implicit |
### Example
```
#include <locale>
#include <utility>
#include <codecvt>
// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template<class Facet>
struct deletable_facet : Facet
{
using Facet::Facet; // inherit constructors
~deletable_facet() {}
};
int main()
{
// UTF-16le / UCS4 conversion
std::wstring_convert<
std::codecvt_utf16<char32_t, 0x10ffff, std::little_endian>
> u16to32;
// UTF-8 / wide string conversion with custom messages
std::wstring_convert<std::codecvt_utf8<wchar_t>> u8towide("Error!", L"Error!");
// GB18030 / wide string conversion facet
typedef deletable_facet<std::codecvt_byname<wchar_t, char, std::mbstate_t>> F;
std::wstring_convert<F> gbtowide(new F("zh_CN.gb18030"));
}
```
| programming_docs |
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::from_bytes std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>::from\_bytes
========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
wide_string from_bytes( char byte );
```
| (1) | |
|
```
wide_string from_bytes( const char* ptr );
```
| (2) | |
|
```
wide_string from_bytes( const byte_string& str );
```
| (3) | |
|
```
wide_string from_bytes( const char* first, const char* last);
```
| (4) | |
Performs multibyte to wide conversion, using the codecvt facet supplied at construction.
1) Converts `byte` as if it was a string of length `1` to wide\_string.
2) Converts the null-terminated multibyte character sequence beginning at the character pointed to by `ptr` to wide\_string.
3) Converts the narrow string `str` to wide\_string.
4) Converts the narrow multibyte character sequence `[first, last)` to wide\_string.
In all cases, the conversion begins in initial shift state, unless non-initial starting state was provided to this `wstring_convert` constructor. The number of characters converted and the final value of the conversion state are remembered and can be accessed with `[state()](state "cpp/locale/wstring convert/state")` and `[converted()](converted "cpp/locale/wstring convert/converted")`.
### Return value
A `wide_string` object containing the results of multibyte to wide conversion. If the conversion failed and there was a user-supplied wide-error string provided to the constructor of this `wstring_convert`, returns that wide-error string.
### Exceptions
If this `wstring_convert` object was constructed without a user-supplied wide-error string, throws `[std::range\_error](../../error/range_error "cpp/error/range error")` on conversion failure.
### Example
```
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main()
{
std::string utf8 = u8"z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
// the UTF-8 / UTF-16 standard conversion facet
std::u16string utf16 = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(utf8.data());
std::cout << "UTF16 conversion produced " << utf16.size() << " code units:\n";
for (char16_t c : utf16)
std::cout << std::hex << std::showbase << c << '\n';
// the UTF-8 / UTF-32 standard conversion facet
std::u32string utf32 = std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t>{}.from_bytes(utf8);
std::cout << "UTF32 conversion produced " << std::dec << utf32.size() << " code units:\n";
for (char32_t c : utf32)
std::cout << std::hex << std::showbase << c << '\n';
}
```
Output:
```
UTF16 conversion produced 5 code units:
0x7a
0xdf
0x6c34
0xd834
0xdd0b
UTF32 conversion produced 4 code units:
0x7a
0xdf
0x6c34
0x1d10b
```
### See also
| | |
| --- | --- |
| [to\_bytes](to_bytes "cpp/locale/wstring convert/to bytes") | converts a wide string into a byte string (public member function) |
| [mbsrtowcs](../../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) |
| [do\_in](../codecvt/in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::state std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>::state
==================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
state_type state() const;
```
| | |
Returns the current value of the conversion state, which is stored in this `wstring_convert` object. The conversion state may be explicitly set in the constructor and is updated by all conversion operations.
### Return value
The current conversion state.
### Example
### See also
| | |
| --- | --- |
| [to\_bytes](to_bytes "cpp/locale/wstring convert/to bytes") | converts a wide string into a byte string (public member function) |
| [from\_bytes](from_bytes "cpp/locale/wstring convert/from bytes") | converts a byte string into a wide string (public member function) |
| [mbsinit](../../string/multibyte/mbsinit "cpp/string/multibyte/mbsinit") | checks if the mbstate\_t object represents initial shift state (function) |
cpp std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::to_bytes std::wstring\_convert<Codecvt,Elem,Wide\_alloc,Byte\_alloc>::to\_bytes
======================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
byte_string to_bytes( Elem wchar );
```
| (1) | |
|
```
byte_string to_bytes( const Elem* wptr );
```
| (2) | |
|
```
byte_string to_bytes( const wide_string& wstr );
```
| (3) | |
|
```
byte_string to_bytes( const Elem* first, const Elem* last);
```
| (4) | |
Performs wide to multibyte conversion, using the `codecvt` facet supplied at construction.
1) Converts `wchar` as if it was a string of length `1`, to `byte_string`.
2) Converts the null-terminated wide character sequence beginning at the wide character pointed to by `wptr`, to `byte_string`.
3) Converts the wide string `str` to `byte_string`.
4) Converts the wide character sequence `[first, last)` to `byte_string`. In all cases, the conversion begins in initial shift state, unless non-initial starting state was provided to this `wstring_convert` constructor. The number of characters converted and the final value of the conversion state are remembered and can be accessed with `[state()](state "cpp/locale/wstring convert/state")` and `[converted()](converted "cpp/locale/wstring convert/converted")`.
### Return value
A `byte_string` object containing the results of the wide to multibyte conversion. If the conversion failed and there was a user-supplied byte-error string provided to the constructor of this `wstring_convert`, returns that byte-error string.
### Exceptions
If this `wstring_convert` object was constructed without a user-supplied byte-error string, throws `[std::range\_error](../../error/range_error "cpp/error/range error")` on conversion failure.
### Example
```
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
#include <iomanip>
// utility function for output
void hex_print(const std::string& s)
{
std::cout << std::hex << std::setfill('0');
for(unsigned char c : s)
std::cout << std::setw(2) << static_cast<int>(c) << ' ';
std::cout << std::dec << '\n';
}
int main()
{
// wide character data
std::wstring wstr = L"z\u00df\u6c34\U0001f34c"; // or L"zß水🍌"
// wide to UTF-8
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1;
std::string u8str = conv1.to_bytes(wstr);
std::cout << "UTF-8 conversion produced " << u8str.size() << " bytes:\n";
hex_print(u8str);
// wide to UTF-16le
std::wstring_convert<std::codecvt_utf16<wchar_t, 0x10ffff, std::little_endian>> conv2;
std::string u16str = conv2.to_bytes(wstr);
std::cout << "UTF-16le conversion produced " << u16str.size() << " bytes:\n";
hex_print(u16str);
}
```
Output:
```
UTF-8 conversion produced 10 bytes:
7a c3 9f e6 b0 b4 f0 9f 8d 8c
UTF-16le conversion produced 10 bytes:
7a 00 df 00 34 6c 3c d8 4c df
```
### See also
| | |
| --- | --- |
| [from\_bytes](from_bytes "cpp/locale/wstring convert/from bytes") | converts a byte string into a wide string (public member function) |
| [wcsrtombs](../../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) |
| [do\_out](../codecvt/out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) |
cpp std::codecvt<InternT,ExternT,StateT>::out, do_out std::codecvt<InternT,ExternT,StateT>::out, do\_out
==================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
result out( StateT& state,
const InternT* from,
const InternT* from_end,
const InternT*& from_next,
ExternT* to,
ExternT* to_end,
ExternT*& to_next ) const;
```
| (1) | |
|
```
protected:
virtual result do_out( StateT& state,
const InternT* from,
const InternT* from_end,
const InternT*& from_next,
ExternT* to,
ExternT* to_end,
ExternT*& to_next ) const;
```
| (2) | |
1) public member function, calls the member function `do_out` of the most derived class.
2) If this `codecvt` facet defines a conversion, translates the internal characters from the source range `[from, from_end)` to external characters, placing the results in the subsequent locations starting at `to`. Converts no more than `from_end - from` internal characters and writes no more than `to_end - to` external characters. Leaves `from_next` and `to_next` pointing one beyond the last element successfully converted. If this `codecvt` facet does not define a conversion, no characters are converted. `to_next` is set to be equal to `to`, `state` is unchanged, and `[std::codecvt\_base::noconv](../codecvt_base "cpp/locale/codecvt base")` is returned.
`do_out(state, from, from + 1, from_next, to, to_end, to_next)` must return `ok` if.
* this `codecvt` facet is used by [`basic_filebuf`](../../io/basic_filebuf "cpp/io/basic filebuf"), and
* `do_out(state, from, from_end, from_next, to, to_end, to_next)` would return `ok` where `from != from_end`.
### Return value
A value of type `[std::codecvt\_base::result](../codecvt_base "cpp/locale/codecvt base")`, indicating the success status as follows:
| | |
| --- | --- |
| `ok` | conversion completed |
| `partial` | not enough space in the output buffer or unexpected end of source buffer |
| `error` | encountered a character that could not be converted |
| `noconv` | this facet is non-converting, no output written |
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` always returns `[std::codecvt\_base::noconv](../codecvt_base "cpp/locale/codecvt base")`.
### Notes
Requires that `from <= from_end && to <= to_end` and that `state` either representing the initial shift state or obtained by converting the preceding characters in the sequence.
While `codecvt` supports N:M conversions (e.g. UTF-16 to UTF-8, where two internal characters may be necessary to decide what external characters to output), `[std::basic\_filebuf](../../io/basic_filebuf "cpp/io/basic filebuf")` can only use `codecvt` facets that define a 1:N conversion, that is it must be able to process one internal character at a time when writing to a file.
When performing N:M conversions, this function may return `[std::codecvt\_base::partial](../codecvt_base "cpp/locale/codecvt base")` after consuming all source characters (`from_next == from_end`). This means that another internal character is needed to complete the conversion (e.g. when converting UTF-16 to UTF-8, if the last character in the source buffer is a high surrogate).
The effect on `state` is deliberately unspecified. In standard facets, it is used to maintain shift state like when calling `[std::wcsrtombs](http://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs)`, and is therefore updated to reflect the shift state after the last successfully converted character, but a user-defined facet is free to use it to maintain any other state, e.g. count the number of special characters encountered.
### Example
```
#include <iostream>
#include <string>
#include <locale>
int main()
{
std::locale::global(std::locale("en_US.utf8"));
auto& f = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(std::locale());
std::wstring internal = L"z\u00df\u6c34\U0001f34c"; // L"zß水🍌"
// note that the following can be done with wstring_convert
std::mbstate_t mb{}; // initial shift state
std::string external(internal.size() * f.max_length(), '\0');
const wchar_t* from_next;
char* to_next;
f.out(mb, &internal[0], &internal[internal.size()], from_next,
&external[0], &external[external.size()], to_next);
// error checking skipped for brevity
external.resize(to_next - &external[0]);
std::cout << "The string in narrow multibyte encoding: " << external << '\n';
}
```
Output:
```
The string in narrow multibyte encoding: zß水🍌
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 76](https://cplusplus.github.io/LWG/issue76) | C++98 | it was unclear whether the conversion is requiredto support taking one internal character at a time | only required if usedby [`basic_filebuf`](../../io/basic_filebuf "cpp/io/basic filebuf") |
### See also
| | |
| --- | --- |
| [overflow](../../io/basic_filebuf/overflow "cpp/io/basic filebuf/overflow")
[virtual] | writes characters to the associated file from the put area (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) |
| [to\_bytes](../wstring_convert/to_bytes "cpp/locale/wstring convert/to bytes") | converts a wide string into a byte string (public member function of `std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>`) |
| [wcsrtombs](../../string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) |
| [do\_in](in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function) |
cpp std::codecvt<InternT,ExternT,StateT>::codecvt std::codecvt<InternT,ExternT,StateT>::codecvt
=============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit codecvt( std::size_t refs = 0 );
```
| | |
Creates a `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::codecvt<InternT,ExternT,StateT>::length, do_length std::codecvt<InternT,ExternT,StateT>::length, do\_length
========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
int length( StateT& state,
const ExternT* from,
const ExternT* from_end,
std::size_t max ) const;
```
| (1) | |
|
```
protected:
virtual int do_length( StateT& state,
const ExternT* from,
const ExternT* from_end,
std::size_t max ) const;
```
| (2) | |
1) public member function, calls the member function `do_length` of the most derived class.
2) attempts to convert the `ExternT` characters from the character array defined by `[from, from_end)`, given initial conversion state `state`, to at most `max` `InternT` characters, and returns the number of `ExternT` characters that such conversion would consume. Modifies `state` as if by executing `do_in(state, from, from_end, from, to, to + max, to)` for some imaginary `[to, to + max)` output buffer. ### Return value
The number of `ExternT` characters that would be consumed if converted by `[do\_in()](in "cpp/locale/codecvt/in")` until either all `from_end - from` characters were consumed or `max` `InternT` characters were produced, or a conversion error occurred.
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` returns `[std::min](http://en.cppreference.com/w/cpp/algorithm/min)(max, from_end - from)`.
### Example
```
#include <locale>
#include <string>
#include <iostream>
int main()
{
using facet_type = std::codecvt<char16_t, char, std::mbstate_t>;
// narrow multibyte encoding
std::string s = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
std::setlocale(LC_ALL, "en_US.UTF-8");
facet_type const& codecvt_facet = std::use_facet<facet_type>(std::locale());
std::mbstate_t mb = std::mbstate_t();
std::cout << "Only the first "
<< codecvt_facet.length(mb, s.data(), s.data() + s.size(), 2)
<< " bytes out of " << s.size() << " would be consumed"
" to produce the first 2 characters\n";
}
```
Output:
```
Only the first 3 bytes out of 10 would be consumed to produce the first 2 characters
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 75](https://cplusplus.github.io/LWG/issue75) | C++98 | the effect on `state` was not specified | specified |
### See also
| | |
| --- | --- |
| [do\_in](in "cpp/locale/codecvt/in")
[virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function) |
cpp std::codecvt<InternT,ExternT,StateT>::max_length, do_max_length std::codecvt<InternT,ExternT,StateT>::max\_length, do\_max\_length
==================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
| | (1) | |
|
```
public:
int max_length() const throw();
```
| (until C++11) |
|
```
public:
int max_length() const noexcept;
```
| (since C++11) |
| | (2) | |
|
```
protected:
virtual int do_max_length() const throw();
```
| (until C++11) |
|
```
protected:
virtual int do_max_length() const noexcept;
```
| (since C++11) |
1) Public member function, calls the member function `do_max_length` of the most derived class.
2) Returns the maximum value that `do_length(state, from, from_end, 1)` can return for any valid range `[from, from_end)` and any valid `state`. ### Return value
The maximum number of `ExternT` characters that could be consumed if converted by `[in()](in "cpp/locale/codecvt/in")` to produce one `InternT` character.
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` returns `1`.
### Notes
If the encoding is state-dependent (`encoding() == -1`), then more than `max_length()` external characters may be consumed to produce one internal character.
### Example
```
#include <locale>
#include <iostream>
#include <codecvt>
int main()
{
std::cout << "In codecvt_utf8, the longest multibyte character is "
<< std::codecvt_utf8<wchar_t>().max_length() << " bytes long\n";
std::cout << "In header-consuming codecvt_utf8, the longest multibyte character is "
<< std::codecvt_utf8<wchar_t,
0x10ffff,
std::consume_header>().max_length() << " bytes long\n";
std::cout << "In this system's en_US.utf8, the longest multibyte character is "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale("en_US.utf8")
).max_length() << " bytes long\n";
std::cout << "In this system's zh_CN.gb18030, the longest multibyte character is "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale("zh_CN.gb18030")
).max_length() << " bytes long\n";
}
```
Output:
```
In codecvt_utf8, the longest multibyte character is 4 bytes long
In header-consuming codecvt_utf8, the longest multibyte character is 7 bytes long
In this system's en_US.utf8, the longest multibyte character is 6 bytes long
In this system's zh_CN.gb18030, the longest multibyte character is 4 bytes long
```
### See also
| | |
| --- | --- |
| MB\_CUR\_MAX | maximum number of bytes in a multibyte character in the current C locale(macro variable) |
| [do\_encoding](encoding "cpp/locale/codecvt/encoding")
[virtual] | returns the number of `ExternT` characters necessary to produce one `InternT` character, if constant (virtual protected member function) |
| programming_docs |
cpp std::codecvt<InternT,ExternT,StateT>::in, std::codecvt<InternT,ExternT,StateT>::do_in std::codecvt<InternT,ExternT,StateT>::in, std::codecvt<InternT,ExternT,StateT>::do\_in
======================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
result in( StateT& state,
const ExternT* from,
const ExternT* from_end,
const ExternT*& from_next,
InternT* to,
InternT* to_end,
InternT*& to_next ) const;
```
| (1) | |
|
```
protected:
virtual result do_in( StateT& state,
const ExternT* from,
const ExternT* from_end,
const ExternT*& from_next,
InternT* to,
InternT* to_end,
InternT*& to_next ) const;
```
| (2) | |
1) Public member function, calls the member function `do_in` of the most derived class.
2) If this `codecvt` facet defines a conversion, translates the external characters from the source range `[from, from_end)` to internal characters, placing the results in the subsequent locations starting at `to`. Converts no more than `from_end - from` external characters and writes no more than `to_end - to` internal characters. Leaves `from_next` and `to_next` pointing one beyond the last element successfully converted. If this `codecvt` facet does not define a conversion, no characters are converted. `to_next` is set to be equal to `to`, `state` is unchanged, and `[std::codecvt\_base::noconv](../codecvt_base "cpp/locale/codecvt base")` is returned.
`do_in(state, from, from_end, from_next, to, to + 1, to_next)` must return `ok` if.
* this `codecvt` facet is used by [`basic_filebuf`](../../io/basic_filebuf "cpp/io/basic filebuf"), and
* `do_in(state, from, from_end, from_next, to, to_end, to_next)` would return `ok` where `to != to_end`.
### Return value
A value of type `[std::codecvt\_base::result](../codecvt_base "cpp/locale/codecvt base")`, indicating the success status as follows:
| | |
| --- | --- |
| `ok` | conversion completed |
| `partial` | not enough space in the output buffer or unexpected end of source buffer |
| `error` | encountered a character that could not be converted |
| `noconv` | this facet is non-converting, no output written |
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` always returns `[std::codecvt\_base::noconv](../codecvt_base "cpp/locale/codecvt base")`.
### Notes
Requires that `from <= from_end && to <= to_end` and that `state` either representing the initial shift state or obtained by converting the preceding characters in the sequence.
The effect on `state` is deliberately unspecified. In standard facets, it is used to maintain shift state like when calling `[std::mbsrtowcs](../../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs")`, and is therefore updated to reflect the conversion state after the last processed external character, but a user-defined facet is free to use it to maintain any other state, e.g. count the number of special characters encountered.
### Example
```
#include <iostream>
#include <string>
#include <locale>
int main()
{
std::locale::global(std::locale("en_US.utf8"));
auto const& f = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>
(std::locale());
std::string external = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
// note that the following can be done with wstring_convert
std::mbstate_t mb = std::mbstate_t(); // initial shift state
std::wstring internal(external.size(), '\0');
const char* from_next;
wchar_t* to_next;
f.in(mb, &external[0], &external[external.size()], from_next,
&internal[0], &internal[internal.size()], to_next);
// error checking skipped for brevity
internal.resize(to_next - &internal[0]);
std::wcout << L"The string in wide encoding: " << internal << '\n';
}
```
Output:
```
The string in wide encoding: zß水𝄋
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 76](https://cplusplus.github.io/LWG/issue76) | C++98 | it was unclear whether the conversion is required tosupport producing one internal character at a time | only required if usedby [`basic_filebuf`](../../io/basic_filebuf "cpp/io/basic filebuf") |
### See also
| | |
| --- | --- |
| [underflow](../../io/basic_filebuf/underflow "cpp/io/basic filebuf/underflow")
[virtual] | reads from the associated file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) |
| [from\_bytes](../wstring_convert/from_bytes "cpp/locale/wstring convert/from bytes") | converts a byte string into a wide string (public member function of `std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>`) |
| [mbsrtowcs](../../string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) |
| [do\_out](out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function) |
cpp std::codecvt<InternT,ExternT,StateT>::~codecvt std::codecvt<InternT,ExternT,StateT>::~codecvt
==============================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~codecvt();
```
| | |
Destructs a `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t>
{
Destructible_codecvt(std::size_t refs = 0) : codecvt(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_codecvt dc;
// std::codecvt<wchar_t> c; // compile error: protected destructor
}
```
cpp std::codecvt<InternT,ExternT,StateT>::always_noconv, do_always_noconv std::codecvt<InternT,ExternT,StateT>::always\_noconv, do\_always\_noconv
========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
| | (1) | |
|
```
public:
bool always_noconv() const throw();
```
| (until C++11) |
|
```
public:
bool always_noconv() const noexcept;
```
| (since C++11) |
| | (2) | |
|
```
protected:
virtual bool do_always_noconv() const throw();
```
| (until C++11) |
|
```
protected:
virtual bool do_always_noconv() const noexcept;
```
| (since C++11) |
1) Public member function, calls the member function `do_always_noconv` of the most derived class.
2) Returns `true` if both `[do\_in()](in "cpp/locale/codecvt/in")` and `[do\_out()](out "cpp/locale/codecvt/out")` return `std::codecvt_base::noconv` for all valid inputs. ### Return value
`true` if this conversion facet performs no conversions, `false` otherwise.
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` returns `true`.
### Notes
This function may be used e.g. in the implementation of `[std::basic\_filebuf::underflow](../../io/basic_streambuf/underflow "cpp/io/basic streambuf/underflow")` and `[std::basic\_filebuf::overflow](../../io/basic_streambuf/overflow "cpp/io/basic streambuf/overflow")` to use bulk character copy instead of calling `[std::codecvt::in](in "cpp/locale/codecvt/in")` or `[std::codecvt::out](out "cpp/locale/codecvt/out")` if it is known that the locale imbued in the `[std::basic\_filebuf](../../io/basic_filebuf "cpp/io/basic filebuf")` does not perform any conversions.
### Example
```
#include <locale>
#include <iostream>
int main()
{
std::cout << "The non-converting char<->char codecvt::always_noconv() returns "
<< std::boolalpha
<< std::use_facet<std::codecvt<char, char, std::mbstate_t>>(
std::locale()
).always_noconv() << "\n"
<< "while wchar_t<->char codecvt::always_noconv() returns "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale()
).always_noconv() << "\n";
}
```
Output:
```
The non-converting char<->char codecvt::always_noconv() returns true
while wchar_t<->char codecvt::always_noconv() returns false
```
cpp std::codecvt<InternT,ExternT,StateT>::unshift, do_unshift std::codecvt<InternT,ExternT,StateT>::unshift, do\_unshift
==========================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
result unshift( StateT& state,
ExternT* to,
ExternT* to_end,
ExternT*& to_next) const;
```
| (1) | |
|
```
protected:
virtual result do_unshift( StateT& state,
ExternT* to,
ExternT* to_end,
ExternT*& to_next) const;
```
| (2) | |
1) public member function, calls the member function `do_unshift` of the most derived class.
2) if the encoding represented by this `codecvt` facet is state-dependent, and `state` represents a conversion state that is not the initial shift state, writes the characters necessary to return to the initial shift state. The characters are written to a character array whose first element is pointed to by `to`. No more than `to_end-to` characters are written. The parameter `to_next` is updated to point one past the last character written. ### Return value
A value of type `[std::codecvt\_base::result](../codecvt_base "cpp/locale/codecvt base")`, indicating the success status as follows:
| | |
| --- | --- |
| `ok` | all necessary characters were written. `state` now represents initial shift state |
| `partial` | not enough space in the output buffer. `to_next == to_end` |
| `error` | unspecified error occurred |
| `noconv` | the encoding is not state-dependent, no termination sequence necessary |
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` always returns `[std::codecvt\_base::noconv](../codecvt_base "cpp/locale/codecvt base")`.
### Notes
This function is called by `std::basic_filebuf::close()` and in other situations when finalizing a state-dependent multibyte character sequence.
### Example
### See also
| | |
| --- | --- |
| [wcrtomb](../../string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) |
| [do\_out](out "cpp/locale/codecvt/out")
[virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function) |
cpp std::codecvt<InternT,ExternT,StateT>::encoding, do_encoding std::codecvt<InternT,ExternT,StateT>::encoding, do\_encoding
============================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
| | (1) | |
|
```
public:
int encoding() const throw();
```
| (until C++11) |
|
```
public:
int encoding() const noexcept;
```
| (since C++11) |
| | (2) | |
|
```
protected:
virtual int do_encoding() const throw();
```
| (until C++11) |
|
```
protected:
virtual int do_encoding() const noexcept;
```
| (since C++11) |
1) public member function, calls the member function `do_encoding` of the most derived class.
2) if the encoding represented by this codecvt facet maps each internal character to the same, constant number of external characters, returns that number. If the encoding is variable-length (e.g. UTF-8 or UTF-16), returns `0`. If the encoding is state-dependent, returns `-1`. ### Return value
The exact number of `externT` characters that correspond to one `internT` character, if constant. `0` if the number varies, `-1` if the encoding is state-dependent.
The non-converting specialization `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<char, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` returns `1`.
### Example
```
#include <locale>
#include <iostream>
int main()
{
std::cout << "en_US.utf8 is a variable-length encoding, encoding() returns "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale("en_US.utf8")
).encoding() << '\n';
std::cout << "zh_CN.gb18030 is also variable-length, encoding() == "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale("zh_CN.gb18030")
).encoding() << '\n';
std::cout << "ru_RU.koi8r is a single-byte encoding encoding() == "
<< std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(
std::locale("ru_RU.koi8r")
).encoding() << '\n';
}
```
Output:
```
en_US.utf8 is a variable-length encoding, encoding() returns 0
zh_CN.gb18030 is also variable-length, encoding() == 0
ru_RU.koi8r is a single-byte encoding encoding() == 1
```
### See also
| | |
| --- | --- |
| MB\_CUR\_MAX | maximum number of bytes in a multibyte character in the current C locale(macro variable) |
| [do\_max\_length](max_length "cpp/locale/codecvt/max length")
[virtual] | returns the maximum number of `ExternT` characters that could be converted into a single `InternT` character (virtual protected member function) |
cpp std::time_get<CharT,InputIt>::get_date, std::time_get<CharT,InputIt>::do_get_date std::time\_get<CharT,InputIt>::get\_date, std::time\_get<CharT,InputIt>::do\_get\_date
======================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get_date( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t ) const;
```
| (1) | |
|
```
protected:
virtual iter_type do_get_date( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t ) const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_get_date()` of the most derived class.
2) Reads successive characters from the sequence `[beg, end)` and parses out the calendar date value using the default format expected by this locale, which is the same format as
| | |
| --- | --- |
| `"%x"` | (until C++11) |
| `"%d/%m/%y"`, `"%m/%d/%y"`, `"%y/%m/%d"`, and `"%y/%d/%m"`, depending on `[date\_order()](date_order "cpp/locale/time get/date order")` | (since C++11) |
as used by the functions `[std::get\_time()](../../io/manip/get_time "cpp/io/manip/get time")`, `[get()](get "cpp/locale/time get/get")`, and the POSIX function `strptime()`
The parsed date is stored in the corresponding fields of the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` structure pointed to by the argument `t`.
If the end iterator is reached before a valid date is read, the function sets `[std::ios\_base::eofbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. If a parsing error is encountered, the function sets `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. ### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace or `[std::collate](../collate "cpp/locale/collate")` to compare strings |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was recognized as a part of a valid date.
### Notes
For the alphabetic components of the default date format (if any), this function is usually case-insensitive.
If a parsing error is encountered, most implementations of this function leave `*t` unmodified.
The implementation may support other date formats besides the ones required by the standard.
### Example
```
#include <iostream>
#include <locale>
#include <sstream>
#include <iterator>
#include <ctime>
void try_get_date(const std::string& s)
{
std::cout << "Parsing the date out of '" << s <<
"' in the locale " << std::locale().name() << '\n';
std::istringstream str(s);
std::ios_base::iostate err = std::ios_base::goodbit;
std::tm t;
std::istreambuf_iterator<char> ret =
std::use_facet<std::time_get<char>>(str.getloc()).get_date(
{str}, {}, str, err, &t
);
str.setstate(err);
if(str) {
std::cout << "Day: " << t.tm_mday << ' '
<< "Month: " << t.tm_mon + 1 << ' '
<< "Year: " << t.tm_year + 1900 << '\n';
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, {}, std::ostreambuf_iterator<char>(std::cout));
std::cout << '\n';
}
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
try_get_date("02/01/2013");
try_get_date("02-01-2013");
std::locale::global(std::locale("ja_JP.utf8"));
try_get_date("2013年02月01日");
}
```
Output:
```
Parsing the date out of '02/01/2013' in the locale en_US.utf8
Day: 1 Month: 2 Year: 2013
Parsing the date out of '02-01-2013' in the locale en_US.utf8
Parse failed. Unparsed string: -01-2013
Parsing the date out of '2013年02月01日' in the locale ja_JP.utf8
Day: 1 Month: 2 Year: 2013
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::time_get std::time\_get<CharT,InputIt>::time\_get
========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit time_get( std::size_t refs = 0 );
```
| | |
Creates a `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
| programming_docs |
cpp std::time_get<CharT,InputIt>::get_weekday, std::time_get<CharT,InputIt>::do_get_weekday std::time\_get<CharT,InputIt>::get\_weekday, std::time\_get<CharT,InputIt>::do\_get\_weekday
============================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get_weekday( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (1) | |
|
```
protected:
virtual iter_type do_get_weekday( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (2) | |
1) public member function, calls the protected virtual member function `do_get_weekday` of the most derived class.
2) Reads successive characters from the sequence `[beg, end)` and parses out the weekday name (possibly abbreviated), using the default format for weekdays expected by this locale, which is the same format as `"%a"` as used by the functions `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")`, [`time_get::get`](get "cpp/locale/time get/get"), and the POSIX function `strptime()`
If it finds abbreviated name, followed by the characters that are valid for the full name, it continues reading until it consumes all the characters for the full name or finds a character that isn't expected, in which case parsing fails even if the first few characters were a valid abbreviation.
The parsed weekday is stored in the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` field `t->tm_wday`.
If the end iterator is reached before a valid weekday name is read, the function sets `[std::ios\_base::eofbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. If a parsing error is encountered, the function sets `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`.
### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace or `[std::collate](../collate "cpp/locale/collate")` to compare strings |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was recognized as a part of a valid weekname.
### Notes
This function is usually case-insensitive.
If a parsing error is encountered, most implementations of this function leave `*t` unmodified.
### Example
```
#include <iostream>
#include <locale>
#include <sstream>
#include <iterator>
void try_get_wday(const std::string& s)
{
std::cout << "Parsing the weekday out of '" << s <<
"' in the locale " << std::locale().name() << '\n';
std::istringstream str(s);
std::ios_base::iostate err = std::ios_base::goodbit;
std::tm t;
std::istreambuf_iterator<char> ret =
std::use_facet<std::time_get<char>>(str.getloc()).get_weekday(
{str}, {}, str, err, &t
);
str.setstate(err);
std::istreambuf_iterator<char> last{};
if(str) {
std::cout << "Successfully parsed, weekday number is " << t.tm_wday;
if(ret != last) {
std::cout << " Remaining content: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
} else {
std::cout << " the input was fully consumed";
}
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
}
std::cout << '\n';
}
int main()
{
std::locale::global(std::locale("lt_LT.utf8"));
try_get_wday("Št");
try_get_wday("Šeštadienis");
std::locale::global(std::locale("en_US.utf8"));
try_get_wday("SATELLITE");
std::locale::global(std::locale("ja_JP.utf8"));
try_get_wday("土曜日");
}
```
Output:
```
Parsing the weekday out of 'Št' in the locale lt_LT.utf8
Successfully parsed, weekday number is 6 the input was fully consumed
Parsing the weekday out of 'Šeštadienis' in the locale lt_LT.utf8
Successfully parsed, weekday number is 6 the input was fully consumed
Parsing the weekday out of 'SATELLITE' in the locale en_US.utf8
Successfully parsed, weekday number is 6 Remaining content: ELLITE
Parsing the weekday out of '土曜日' in the locale ja_JP.utf8
Successfully parsed, weekday number is 6 the input was fully consumed
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::get_monthname, std::time_get<CharT,InputIt>::do_get_monthname std::time\_get<CharT,InputIt>::get\_monthname, std::time\_get<CharT,InputIt>::do\_get\_monthname
================================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get_monthname( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (1) | |
|
```
protected:
virtual iter_type do_get_monthname( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (2) | |
1) public member function, calls the protected virtual member function `do_get_monthname` of the most derived class.
2) Reads successive characters from the sequence `[beg, end)` and parses out the month name (possibly abbreviated), using the default format for month names expected by this locale, which is the same format as `"%b"` as used by the functions `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")`, [`time_get::get`](get "cpp/locale/time get/get"), and the POSIX function `strptime()`
If it finds abbreviated name, followed by the characters that are valid for the full name, it continues reading until it consumes all the characters for the full name or finds a character that isn't expected, in which case parsing fails even if the first few characters were a valid abbreviation.
The parsed month is stored in the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` field `t->tm_mon`.
If the end iterator is reached before a valid month name is read, the function sets `[std::ios\_base::eofbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. If a parsing error is encountered, the function sets `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`.
### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace or `[std::collate](../collate "cpp/locale/collate")` to compare strings |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was recognized as a part of a valid month name.
### Notes
This function is usually case-insensitive.
If a parsing error is encountered, most implementations of this function leave `*t` unmodified.
### Example
```
#include <iostream>
#include <locale>
#include <sstream>
#include <iterator>
#include <ctime>
void try_get_mon(const std::string& s)
{
std::cout << "Parsing the month out of '" << s <<
"' in the locale " << std::locale().name() << '\n';
std::istringstream str(s);
std::ios_base::iostate err = std::ios_base::goodbit;
std::tm t;
std::istreambuf_iterator<char> ret =
std::use_facet<std::time_get<char>>(str.getloc()).get_monthname(
{str}, {}, str, err, &t
);
str.setstate(err);
std::istreambuf_iterator<char> last{};
if(str) {
std::cout << "Successfully parsed, month number is " << t.tm_mon;
if(ret != last) {
std::cout << ". Remaining content: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
} else {
std::cout << ". The input was fully consumed";
}
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
}
std::cout << '\n';
}
int main()
{
std::locale::global(std::locale("ja_JP.utf8"));
try_get_mon("2月");
std::locale::global(std::locale("th_TH.utf8"));
try_get_mon("กุมภาพันธ์");
std::locale::global(std::locale("el_GR.utf8"));
try_get_mon("Φεβ");
try_get_mon("Φεβρουάριος");
std::locale::global(std::locale("en_US.utf8"));
try_get_mon("Febrile");
}
```
Output:
```
Parsing the month out of '2月' in the locale ja_JP.utf8
Successfully parsed, month number is 1. The input was fully consumed
Parsing the month out of 'กุมภาพันธ์' in the locale th_TH.utf8
Successfully parsed, month number is 1. The input was fully consumed
Parsing the month out of 'Φεβ' in the locale el_GR.utf8
Successfully parsed, month number is 1. The input was fully consumed
Parsing the month out of 'Φεβρουάριος' in the locale el_GR.utf8
Successfully parsed, month number is 1. The input was fully consumed
Parsing the month out of 'Febrile' in the locale en_US.utf8
Parse failed. Unparsed string: ile
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::get_year, std::time_get<CharT,InputIt>::do_get_year std::time\_get<CharT,InputIt>::get\_year, std::time\_get<CharT,InputIt>::do\_get\_year
======================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get_year( iter_type s, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (1) | |
|
```
protected:
virtual iter_type do_get_year( iter_type s, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (2) | |
1) public member function, calls the protected virtual member function `do_get_year` of the most derived class.
2) Reads successive characters from the sequence `[beg, end)` and parses out the year using some implementation-defined format. Depending on the locale, two-digit years may be accepted, and it is implementation-defined which century they belong to. The parsed year is stored in the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` structure field `t->tm_year`.
If the end iterator is reached before a valid date is read, the function sets `[std::ios\_base::eofbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. If a parsing error is encountered, the function sets `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`.
### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace or `[std::collate](../collate "cpp/locale/collate")` to compare strings |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was recognized as a part of a valid year.
### Notes
For two-digit input values, many implementations use the same parsing rules as the conversion specifier `'%y'` as used by `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")`, `[std::time\_get::get()](get "cpp/locale/time get/get")`, and the POSIX function `strptime()`: two-digit integer is expected, the values in the range [69,99] results in values 1969 to 1999, range [00,68] results in 2000-2068. Four-digit inputs are typically accepted as-is.
If a parsing error is encountered, most implementations of this function leave `*t` unmodified.
### Example
```
#include <iostream>
#include <locale>
#include <sstream>
#include <iterator>
void try_get_year(const std::string& s)
{
std::cout << "Parsing the year out of '" << s <<
"' in the locale " << std::locale().name() << '\n';
std::istringstream str(s);
std::ios_base::iostate err = std::ios_base::goodbit;
std::tm t;
std::istreambuf_iterator<char> ret =
std::use_facet<std::time_get<char>>(str.getloc()).get_year(
{str}, {}, str, err, &t
);
str.setstate(err);
std::istreambuf_iterator<char> last{};
if (str) {
std::cout << "Successfully parsed, year is " << 1900 + t.tm_year;
if (ret != last) {
std::cout << " Remaining content: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
} else {
std::cout << " the input was fully consumed";
}
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
}
std::cout << '\n';
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
try_get_year("13");
try_get_year("2013");
std::locale::global(std::locale("ja_JP.utf8"));
try_get_year("2013年");
}
```
Possible output:
```
Parsing the year out of '13' in the locale en_US.utf8
Successfully parsed, year is 2013 the input was fully consumed
Parsing the year out of '2013' in the locale en_US.utf8
Successfully parsed, year is 2013 the input was fully consumed
Parsing the year out of '2013年' in the locale ja_JP.utf8
Successfully parsed, year is 2013 Remaining content: 年
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::get_time, std::time_get<CharT,InputIt>::do_get_time std::time\_get<CharT,InputIt>::get\_time, std::time\_get<CharT,InputIt>::do\_get\_time
======================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get_time( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (1) | |
|
```
protected:
virtual iter_type do_get_time( iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t) const;
```
| (2) | |
1) public member function, calls the protected virtual member function `do_get_time` of the most derived class.
2) Reads successive characters from the sequence `[beg, end)` and parses out the time value following the same rules as the format specifier `"%X"` (until C++11) `"%H:%M:%S"` (since C++11) as used by the functions `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")`, [`time_get::get`](get "cpp/locale/time get/get"), and the POSIX function `strptime()`. The parsed time is stored in the corresponding fields of the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` structure pointed to by the argument `t`. If the end iterator is reached before a valid value is read, the function sets `[std::ios\_base::eofbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. If a parsing error is encountered, the function sets `[std::ios\_base::failbit](../../io/ios_base/iostate "cpp/io/ios base/iostate")` in `err`. ### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was recognized as a part of a valid date.
### Notes
For the alphabetic components of the default time format (if any), this function is usually case-insensitive.
If a parsing error is encountered, most implementations of this function leave `*t` unmodified.
### Example
```
#include <iostream>
#include <locale>
#include <sstream>
#include <iterator>
void try_get_time(const std::string& s)
{
std::cout << "Parsing the time out of '" << s <<
"' in the locale " << std::locale().name() << '\n';
std::istringstream str(s);
std::ios_base::iostate err = std::ios_base::goodbit;
std::tm t;
std::istreambuf_iterator<char> ret =
std::use_facet<std::time_get<char>>(str.getloc()).get_time(
{str}, {}, str, err, &t
);
str.setstate(err);
if(str) {
std::cout << "Hours: " << t.tm_hour << ' '
<< "Minutes: " << t.tm_min << ' '
<< "Seconds: " << t.tm_sec << '\n';
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, {}, std::ostreambuf_iterator<char>(std::cout));
std::cout << '\n';
}
}
int main()
{
std::locale::global(std::locale("ru_RU.utf8"));
try_get_time("21:40:11");
try_get_time("21-40-11");
std::locale::global(std::locale("ja_JP.utf8"));
try_get_time("21時37分58秒");
}
```
Output:
```
Parsing the time out of '21:40:11' in the locale ru_RU.utf8
Hours: 21 Minutes: 40 Seconds: 11
Parsing the time out of '21-40-11' in the locale ru_RU.utf8
Parse failed. Unparsed string: -40-11
Parsing the time out of '21時37分58秒' in the locale ja_JP.utf8
Hours: 21 Minutes: 37 Seconds: 58
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::date_order, std::time_get<CharT,InputIt>::do_date_order std::time\_get<CharT,InputIt>::date\_order, std::time\_get<CharT,InputIt>::do\_date\_order
==========================================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
dateorder date_order() const;
```
| (1) | |
|
```
protected:
virtual dateorder do_date_order() const;
```
| (2) | |
1) Public member function, calls the protected virtual member function `do_date_order` of the most derived class.
2) Returns a value of type `[std::time\_base::dateorder](../time_base "cpp/locale/time base")`, which describes the default date format used by this locale (expected by `[get\_date()](get_date "cpp/locale/time get/get date")` and produced by `[std::strftime()](../../chrono/c/strftime "cpp/chrono/c/strftime")` with format specifier `'%x'`). The valid values (inherited from `[std::time\_base](../time_base "cpp/locale/time base")`) are:
| | |
| --- | --- |
| `no_order` | the format contains variable items (week day, Julian day, etc), or this function is not implemented |
| `dmy` | day, month, year (European locales) |
| `mdy` | month, day, year (American locales) |
| `ymd` | year, month, day (Asian locales) |
| `ydm` | year, day, month (rare) |
### Parameters
(none).
### Return value
A value of type `dateorder`.
### Notes
This function is optional, it may return `no_order` in every case.
### Example
```
#include <iostream>
#include <locale>
void show_date_order()
{
std::time_base::dateorder d = std::use_facet<std::time_get<char>>(
std::locale()
).date_order();
switch (d)
{
case std::time_base::no_order: std::cout << "no_order\n"; break;
case std::time_base::dmy: std::cout << "day, month, year\n"; break;
case std::time_base::mdy: std::cout << "month, day, year\n"; break;
case std::time_base::ymd: std::cout << "year, month, day\n"; break;
case std::time_base::ydm: std::cout << "year, day, month\n"; break;
}
}
int main()
{
std::locale::global(std::locale("en_US.utf8"));
std::cout << "In U.S. locale, the default date order is: ";
show_date_order();
std::locale::global(std::locale("ja_JP.utf8"));
std::cout << "In Japanese locale, the default date order is: ";
show_date_order();
std::locale::global(std::locale("de_DE.utf8"));
std::cout << "In German locale, the default date order is: ";
show_date_order();
}
```
Output:
```
In U.S. locale, the default date order is: month, day, year
In Japanese locale, the default date order is: year, month, day
In German locale, the default date order is: day, month, year
```
### See also
| | |
| --- | --- |
| [do\_get\_date](get_date "cpp/locale/time get/get date")
[virtual] | extracts month, day, and year from input stream (virtual protected member function) |
| [time\_base](../time_base "cpp/locale/time base") | defines date format constants (class) |
| programming_docs |
cpp std::time_get<CharT,InputIt>::get, std::time_get<CharT,InputIt>::do_get std::time\_get<CharT,InputIt>::get, std::time\_get<CharT,InputIt>::do\_get
==========================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type get(iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm* t,
const char_type* fmtbeg, const char_type* fmtend) const;
```
| (1) | (since C++11) |
|
```
protected:
virtual iter_type do_get(iter_type beg, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, std::tm *t,
char format, char modifier) const;
```
| (2) | (since C++11) |
1) Parses the date and time from the input character sequence `[beg, end)` according to the format provided in the character sequence `[fmtbeg, fmtend)`. The format is expected to follow the format described below, although actual processing of each format specifier can be customized by overriding `do_get`. The `get` function performs the following: First, clears the error bits in `err` by executing `err = [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)`. Then enters a loop, which terminates whenever any of the following conditions becomes true (checked in this order):
a) All characters have been read from the format string (`fmtbeg == fmtend`)
b) There was a parsing error (`err != [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)`)
c) All characters have been read from the input sequence (`beg == end`. If this condition terminates the loop, the function sets both `eofbit` and `failbit` in `err`
In the body of the loop, the following steps take place:
a) if the next character in the format string is `'%'`, followed by one or two characters that form a valid `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")` conversion specifier (see below), these characters are used in the call `do_get(beg, end, str, err, t, format, modifier)`, where `format` is the primary conversion specifier character, and `modifier` is the optional modifier (which appears between `%` and the format character, if present). If there is no modifier, the value `'\0'` is used. If the format string is ambiguous or ends too early to determine the conversion specifier after `'%'`, `eofbit` is set in `err` and the loop is terminated. If, after the call to `do_get`, no error bits are set in `err`, the function increments `fmtbeg` to point right after the conversion specifier and continues the loop.
b) If the next character is whitespace, as indicated by the locale provided in the stream `str` (i.e. `std::isspace(*fmtbeg, str.getloc()) == true`, the function keeps incrementing `fmtbeg` until it either becomes equal to `fmtend` or points to a non-whitespace character.
c) If the next character in the format string is equivalent to the next character in the input stream according to case-insensitive comparison, the function advances both sequences by one character `++fmtbeg, ++beg;` and continues the loop, Otherwise, it sets the `failbit` in `err`.
2) Parses one conversion specifier from the input sequence `[beg, end)` and updates the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` structure pointed to by `t` accordingly. First, clears the error bits in `err` by executing `err = [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)`. Then reads characters from the input sequence `[beg, end)` that are expected by the `[std::time\_get](../time_get "cpp/locale/time get")` format specifier formed by combining `'%'`, `modifier` (if not `'\0'`), and `format`. If the characters do not combine to form a valid conversion specifier, sets `failbit` in `err`. If the end of the input stream is reached after reading a character, sets `eofbit` in `err`. If the input string was parsed successfully, updates the corresponding fields of `*t`. For complex conversion specifiers, such as `'%x'` or `'%c'`, or the directives that use the modifiers `'E'` and `'O'`, the function may fail to determine some of the values to store in `*t`. In such case, it sets `eofbit` in `err` and leaves these fields in unspecified state. ### Parameters
| | | |
| --- | --- | --- |
| beg | - | iterator designating the start of the sequence to parse |
| end | - | one past the end iterator for the sequence to parse |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to skip whitespace or `[std::collate](../collate "cpp/locale/collate")` to compare strings |
| err | - | stream error flags object that is modified by this function to indicate errors |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object that will hold the result of this function call |
| fmtbeg | - | pointer to the first character of a sequence of char\_type characters specifying the conversion format The format string consists of zero or more conversion specifiers, whitespace characters, and ordinary characters (except `%`). Each ordinary character is expected to match one character in the input stream in case-insensitive comparison. Each whitespace character matches arbitrary whitespace in the input string. Each conversion specification begins with `%` character, optionally followed by `E` or `O` modifier (ignored if unsupported by the locale), followed by the character that determines the behavior of the specifier. The format specifiers match the POSIX function [`strptime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strptime.html):
| Conversion specifier | Explanation | Writes to fields |
| --- | --- | --- |
| `%` | matches a literal `%`. The full conversion specification must be `%%`. | (none) |
| `t` | matches any whitespace. | (none) |
| `n` | matches any whitespace. | (none) |
| Year |
| `Y` | parses full **year** as a 4 digit decimal number, leading zeroes permitted but not required | `tm_year` |
| `EY` | parses **year** in the alternative representation, e.g.平成23年 (year Heisei 23) which writes 2011 to tm\_year in ja\_JP locale | `tm_year` |
| `y` | parses last 2 digits of **year** as a decimal number. Range `[69,99]` results in values 1969 to 1999, range `[00,68]` results in 2000-2068 | `tm_year` |
| `Oy` | parses last 2 digits of **year** using the alternative numeric system, e.g. 十一 is parsed as 11 in ja\_JP locale | `tm_year` |
| `Ey` | parses **year** as offset from locale's alternative calendar period `%EC` | `tm_year` |
| `C` | parses the first 2 digits of **year** as a decimal number (range `[00,99]`) | `tm_year` |
| `EC` | parses the name of the base year (period) in the locale's alternative representation, e.g. 平成 (Heisei era) in ja\_JP | `tm_year` |
| Month |
| `b` | parses the month name, either full or abbreviated, e.g. `Oct` | `tm_mon` |
| `h` | synonym of `b` | `tm_mon` |
| `B` | synonym of `b` | `tm_mon` |
| `m` | parses the **month** as a decimal number (range `[01,12]`), leading zeroes permitted but not required | `tm_mon` |
| `Om` | parses the **month** using the alternative numeric system, e.g. 十二 parses as 12 in ja\_JP locale | `tm_mon` |
| Week |
| `U` | parses the **week of the year** as a decimal number (Sunday is the first day of the week) (range `[00,53]`), leading zeroes permitted but not required | `tm_year`, `tm_wday`, `tm_yday` |
| `OU` | parses the **week of the year**, as by `%U`, using the alternative numeric system, e.g. 五十二 parses as 52 in ja\_JP locale | `tm_year`, `tm_wday`, `tm_yday` |
| `W` | parses the **week of the year** as a decimal number (Monday is the first day of the week) (range `[00,53]`), leading zeroes permitted but not required | `tm_year`, `tm_wday`, `tm_yday` |
| `OW` | parses the **week of the year**, as by `%W`, using the alternative numeric system, e.g. 五十二 parses as 52 in ja\_JP locale | `tm_year`, `tm_wday`, `tm_yday` |
| Day of the year/month |
| `j` | parses **day of the year** as a decimal number (range `[001,366]`), leading zeroes permitted but not required | `tm_yday` |
| `d` | parses the **day of the month** as a decimal number (range `[01,31]`), leading zeroes permitted but not required | `tm_mday` |
| `Od` | parses the **day of the month** using the alternative numeric system, e.g 二十七 parses as 27 in ja\_JP locale, leading zeroes permitted but not required | `tm_mday` |
| `e` | synonym of `d` | `tm_mday` |
| `Oe` | synonym of `Od` | `tm_mday` |
| Day of the week |
| `a` | parses the name of the day of the week, either full or abbreviated, e.g. `Fri` | `tm_wday` |
| `A` | synonym of `a` | `tm_wday` |
| `w` | parses **weekday** as a decimal number, where Sunday is `0` (range `[0-6]`) | `tm_wday` |
| `Ow` | parses **weekday** as a decimal number, where Sunday is `0`, using the alternative numeric system, e.g. 二 parses as 2 in ja\_JP locale | `tm_wday` |
| Hour, minute, second |
| `H` | parses the **hour** as a decimal number, 24 hour clock (range `[00-23]`), leading zeroes permitted but not required | `tm_hour` |
| `OH` | parses **hour** from 24-hour clock using the alternative numeric system, e.g. 十八 parses as 18 in ja\_JP locale | `tm_hour` |
| `I` | parses **hour** as a decimal number, 12 hour clock (range `[01,12]`), leading zeroes permitted but not required | `tm_hour` |
| `OI` | parses **hour** from 12-hour clock using the alternative numeric system, e.g. 六 reads as 06 in ja\_JP locale | `tm_hour` |
| `M` | parses **minute** as a decimal number (range `[00,59]`), leading zeroes permitted but not required | `tm_min` |
| `OM` | parses **minute** using the alternative numeric system, e.g. 二十五 parses as 25 in ja\_JP locale | `tm_min` |
| `S` | parses **second** as a decimal number (range `[00,60]`), leading zeroes permitted but not required | `tm_sec` |
| `OS` | parses **second** using the alternative numeric system, e.g. 二十四 parses as 24 in ja\_JP locale | `tm_sec` |
| Other |
| `c` | parses the locale's standard date and time string format, e.g. `Sun Oct 17 04:41:13 2010` (locale dependent) | all |
| `Ec` | parses the locale's alternative date and time string format, e.g. expecting 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale | all |
| `x` | parses the locale's standard date representation | all |
| `Ex` | parses the locale's alternative date representation, e.g. expecting 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale | all |
| `X` | parses the locale's standard time representation | all |
| `EX` | parses the locale's alternative time representation | all |
| `D` | equivalent to **"%m / %d / %y "** | `tm_mon`, `tm_mday`, `tm_year` |
| `r` | parses locale's standard 12-hour clock time (in POSIX, **"%I : %M : %S %p"**) | `tm_hour`, `tm_min`, `tm_sec` |
| `R` | equivalent to **"%H : %M"** | `tm_hour`, `tm_min` |
| `T` | equivalent to **"%H : %M : %S"** | `tm_hour`, `tm_min`, `tm_sec` |
| `p` | parses the locale's equivalent of **a.m. or p.m.** | `tm_hour` |
Note: `tm_isdst` is not written to, and needs to be set explicitly for use with functions such as `mktime`. |
| fmtend | - | pointer one past the last character of a sequence of char\_type characters specifying the conversion format |
| format | - | the character that names a conversion specifier |
| modifier | - | the optional modifier that may appear between `%` and the conversion specifier |
### Return value
Iterator pointing one past the last character in `[beg, end)` that was parsed successfully.
### Notes
The case-insensitive comparison for the non-whitespace non-`'%'` characters in the format string, the `[std::collate](../collate "cpp/locale/collate")` facet of the locale provided by `str` is typically, but not necessarily, used.
If a parsing error is encountered, many implementations of this function leave `*t` completely untouched.
It's unspecified if these functions zero out the fields in `*t` that they do not set directly: portable programs should initialize every field to zero before calling `get()`.
### Example
```
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::istringstream ss("2011-Februar-18 23:12:34");
ss.imbue(std::locale("de_DE.utf8"));
auto& f = std::use_facet<std::time_get<char>>(std::locale("de_DE.utf8"));
std::tm t{};
std::string s = "%Y-%b-%d %H:%M:%S";
std::ios_base::iostate err = std::ios_base::goodbit;
auto ret = f.get({ss}, {}, ss, err, &t, &s[0], &s[0] + s.size());
ss.setstate(err);
std::istreambuf_iterator<char> last{};
if(ss) {
std::cout << "Successfully parsed as " << std::put_time(&t, "%c");
if(ret != last) {
std::cout << " Remaining content: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
} else {
std::cout << " The input was fully consumed";
}
} else {
std::cout << "Parse failed. Unparsed string: ";
std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout));
}
std::cout << '\n';
}
```
Output:
```
Successfully parsed, as Sun Feb 18 23:12:34 2011 The input was fully consumed
```
### See also
| | |
| --- | --- |
| [get\_time](../../io/manip/get_time "cpp/io/manip/get time")
(C++11) | parses a date/time value of specified format (function template) |
cpp std::time_get<CharT,InputIt>::~time_get std::time\_get<CharT,InputIt>::~time\_get
=========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~time_get();
```
| | |
Destructs a `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_time_get : public std::time_get<wchar_t>
{
Destructible_time_get(std::size_t refs = 0) : time_get(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_time_get dc;
// std::time_get<wchar_t> c; // compile error: protected destructor
}
```
cpp std::time_put<CharT,OutputIt>::time_put std::time\_put<CharT,OutputIt>::time\_put
=========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
explicit time_put( std::size_t refs = 0 );
```
| | |
Creates a `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)` facet and forwards the starting reference count `refs` to the base class constructor, [`locale::facet::facet()`](../locale/facet/facet "cpp/locale/locale/facet/facet").
### Parameters
| | | |
| --- | --- | --- |
| refs | - | starting reference count |
cpp std::time_put<CharT,OutputIt>::put, std::time_put<CharT,OutputIt>::do_put std::time\_put<CharT,OutputIt>::put, std::time\_put<CharT,OutputIt>::do\_put
============================================================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
public:
iter_type put( iter_type out, std::ios_base& str,
char_type fill, const std::tm* t,
const CharT* fmtbeg, const CharT* fmtend ) const;
```
| (1) | |
|
```
public:
iter_type put( iter_type out, std::ios_base& str,
char_type fill, const std::tm* t,
char format, char modifier = 0 ) const;
```
| (2) | |
|
```
protected:
virtual iter_type do_put( iter_type out, std::ios_base& str,
char_type fill, const std::tm* t,
char format, char modifier ) const;
```
| (3) | |
Converts the calendar date and time stored in the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object pointed to by `t` into a character string, according to the [format string](#Format_string) `[fmtbeg, fmtend)`. The format string is the same as used by `[std::strftime](http://en.cppreference.com/w/cpp/chrono/c/strftime)`, but each format specifier is processed by an individual call to `do_put()`, which can be customized by extending this facet.
1) Steps through the character sequence `[fmtbeg, fmtend)`, examining the characters. Every character that is not a part of a format sequence is written to the output iterator `out` immediately. To identify format sequences, this function narrows the next character `c` in `[fmtbeg, fmtend)` as if by `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char_type>(str.getloc()).narrow(c,0)` and if it equals `'%'`, the next one or two characters are compared to the list of format sequences recognized by `[std::strftime](../../chrono/c/strftime "cpp/chrono/c/strftime")` plus any additional implementation-defined formats supported by this locale. For each valid format sequence, a call to `do_put(out, str, fill, t, format, modifier)` is made, where `format` is the format sequence character, and `modifier` is the optional format sequence modifier (`'E'` or `'O'`). A value of `'\0'` is used if the modifier is absent.
2) Calls the `do_put` member function of the most derived class.
3) Converts the calendar date and time stored in the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object pointed to by `t` into a character string, according to the format conversion sequence formed by concatenating `'%'`, the value of `modifier` if not `'\0'`, and the value of `format`. The format is interpreted the same way as the function `[std::strftime](../../chrono/c/strftime "cpp/chrono/c/strftime")`, except that the formats that are described as locale-dependent are defined by this locale, and additional format specifiers may be supported (the `fill` argument is provided for these implementation-defined format specifiers to use). The string is written to the output iterator `out`. ### Parameters
| | | |
| --- | --- | --- |
| out | - | output iterator where the result of the conversion is written |
| str | - | a stream object that this function uses to obtain locale facets when needed, e.g. `[std::ctype](../ctype "cpp/locale/ctype")` to narrow characters |
| t | - | pointer to the `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object from which the date/time values are obtained |
| fmtbeg | - | pointer to the first character of a sequence of char\_type characters specifying the [conversion format](#Format_string) |
| fmtend | - | pointer one past the last character of a sequence of char\_type characters specifying the [conversion format](#Format_string) |
| fill | - | fill character (usually space) |
| format | - | the character that names a [conversion specifier](#Format_string) |
| modifier | - | the optional modifier that may appear between `%` and the [conversion specifier](#Format_string) |
### Format string
The format string consists of zero or more conversion specifiers and ordinary characters (except `%`). All ordinary characters, including the terminating null character, are copied to the output string without modification. Each conversion specification begins with `%` character, optionally followed by `E` or `O` modifier (ignored if unsupported by the locale), followed by the character that determines the behavior of the specifier. The following format specifiers are available:
| Conversion specifier | Explanation | Used fields |
| --- | --- | --- |
| `%` | writes literal `%`. The full conversion specification must be `%%`. | |
| `n`(C++11) | writes newline character | |
| `t`(C++11) | writes horizontal tab character | |
| Year |
| `Y` | writes **year** as a decimal number, e.g. 2017 | `tm_year` |
| `EY`(C++11) | writes **year** in the alternative representation, e.g.平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale | `tm_year` |
| `y` | writes last 2 digits of **year** as a decimal number (range `[00,99]`) | `tm_year` |
| `Oy`(C++11) | writes last 2 digits of **year** using the alternative numeric system, e.g. 十一 instead of 11 in ja\_JP locale | `tm_year` |
| `Ey`(C++11) | writes **year** as offset from locale's alternative calendar period `%EC` (locale-dependent) | `tm_year` |
| `C`(C++11) | writes first 2 digits of **year** as a decimal number (range `[00,99]`) | `tm_year` |
| `EC`(C++11) | writes name of the **base year (period)** in the locale's alternative representation, e.g. 平成 (Heisei era) in ja\_JP | `tm_year` |
| `G`(C++11) | writes **ISO 8601 week-based year**, i.e. the year that contains the specified week. In IS0 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
| `tm_year`, `tm_wday`, `tm_yday` |
| `g`(C++11) | writes last 2 digits of **ISO 8601 week-based year**, i.e. the year that contains the specified week (range `[00,99]`). In IS0 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
| `tm_year`, `tm_wday`, `tm_yday` |
| Month |
| `b` | writes **abbreviated month** name, e.g. `Oct` (locale dependent) | `tm_mon` |
| `h`(C++11) | synonym of `b` | `tm_mon` |
| `B` | writes **full month** name, e.g. `October` (locale dependent) | `tm_mon` |
| `m` | writes **month** as a decimal number (range `[01,12]`) | `tm_mon` |
| `Om`(C++11) | writes **month** using the alternative numeric system, e.g. 十二 instead of 12 in ja\_JP locale | `tm_mon` |
| Week |
| `U` | writes **week of the year** as a decimal number (Sunday is the first day of the week) (range `[00,53]`) | `tm_year`, `tm_wday`, `tm_yday` |
| `OU`(C++11) | writes **week of the year**, as by `%U`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale | `tm_year`, `tm_wday`, `tm_yday` |
| `W` | writes **week of the year** as a decimal number (Monday is the first day of the week) (range `[00,53]`) | `tm_year`, `tm_wday`, `tm_yday` |
| `OW`(C++11) | writes **week of the year**, as by `%W`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale | `tm_year`, `tm_wday`, `tm_yday` |
| `V`(C++11) | writes **ISO 8601 week of the year** (range `[01,53]`). In IS0 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
| `tm_year`, `tm_wday`, `tm_yday` |
| `OV`(C++11) | writes **week of the year**, as by `%V`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale | `tm_year`, `tm_wday`, `tm_yday` |
| Day of the year/month |
| `j` | writes **day of the year** as a decimal number (range `[001,366]`) | `tm_yday` |
| `d` | writes **day of the month** as a decimal number (range `[01,31]`) | `tm_mday` |
| `Od`(C++11) | writes zero-based **day of the month** using the alternative numeric system, e.g 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
| `e`(C++11) | writes **day of the month** as a decimal number (range `[1,31]`). Single digit is preceded by a space. | `tm_mday` |
| `Oe`(C++11) | writes one-based **day of the month** using the alternative numeric system, e.g. 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
| Day of the week |
| `a` | writes **abbreviated weekday** name, e.g. `Fri` (locale dependent) | `tm_wday` |
| `A` | writes **full weekday** name, e.g. `Friday` (locale dependent) | `tm_wday` |
| `w` | writes **weekday** as a decimal number, where Sunday is `0` (range `[0-6]`) | `tm_wday` |
| `Ow`(C++11) | writes **weekday**, where Sunday is `0`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale | `tm_wday` |
| `u`(C++11) | writes **weekday** as a decimal number, where Monday is `1` (ISO 8601 format) (range `[1-7]`) | `tm_wday` |
| `Ou`(C++11) | writes **weekday**, where Monday is `1`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale | `tm_wday` |
| Hour, minute, second |
| `H` | writes **hour** as a decimal number, 24 hour clock (range `[00-23]`) | `tm_hour` |
| `OH`(C++11) | writes **hour** from 24-hour clock using the alternative numeric system, e.g. 十八 instead of 18 in ja\_JP locale | `tm_hour` |
| `I` | writes **hour** as a decimal number, 12 hour clock (range `[01,12]`) | `tm_hour` |
| `OI`(C++11) | writes **hour** from 12-hour clock using the alternative numeric system, e.g. 六 instead of 06 in ja\_JP locale | `tm_hour` |
| `M` | writes **minute** as a decimal number (range `[00,59]`) | `tm_min` |
| `OM`(C++11) | writes **minute** using the alternative numeric system, e.g. 二十五 instead of 25 in ja\_JP locale | `tm_min` |
| `S` | writes **second** as a decimal number (range `[00,60]`) | `tm_sec` |
| `OS`(C++11) | writes **second** using the alternative numeric system, e.g. 二十四 instead of 24 in ja\_JP locale | `tm_sec` |
| Other |
| `c` | writes **standard date and time string**, e.g. `Sun Oct 17 04:41:13 2010` (locale dependent) | all |
| `Ec`(C++11) | writes **alternative date and time string**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale | all |
| `x` | writes localized **date representation** (locale dependent) | all |
| `Ex`(C++11) | writes **alternative date representation**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale | all |
| `X` | writes localized **time representation**, e.g. 18:40:20 or 6:40:20 PM (locale dependent) | all |
| `EX`(C++11) | writes **alternative time representation** (locale dependent) | all |
| `D`(C++11) | equivalent to **"%m/%d/%y"** | `tm_mon`, `tm_mday`, `tm_year` |
| `F`(C++11) | equivalent to **"%Y-%m-%d"** (the ISO 8601 date format) | `tm_mon`, `tm_mday`, `tm_year` |
| `r`(C++11) | writes localized **12-hour clock** time (locale dependent) | `tm_hour`, `tm_min`, `tm_sec` |
| `R`(C++11) | equivalent to **"%H:%M"** | `tm_hour`, `tm_min` |
| `T`(C++11) | equivalent to **"%H:%M:%S"** (the ISO 8601 time format) | `tm_hour`, `tm_min`, `tm_sec` |
| `p` | writes localized **a.m. or p.m.** (locale dependent) | `tm_hour` |
| `z`(C++11) | writes **offset from UTC** in the ISO 8601 format (e.g. `-0430`), or no characters if the time zone information is not available | `tm_isdst` |
| `Z` | writes locale-dependent **time zone name or abbreviation**, or no characters if the time zone information is not available | `tm_isdst` |
### Return value
Iterator pointing one past the last character that was produced .
### Notes
No error handling is provided.
The `fill` character is provided for those implementation-defined format specifiers and for the user-defined overrides of `do_put()` that use padding and filling logic. Such implementations typically make use of the formatting flags from `str`.
### Example
```
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
void try_time_put(const std::tm* t, const std::string& fmt)
{
std::cout.imbue(std::locale());
std::cout << "In the locale '" << std::cout.getloc().name() << "' : '";
std::use_facet<std::time_put<char>>(std::cout.getloc()).put(
{std::cout}, std::cout, ' ', t, &fmt[0], &fmt[0] + fmt.size());
std::cout << "'\n";
}
int main()
{
std::time_t t = std::time(NULL);
std::tm tm = *std::localtime(&t);
std::string fmt = "%c";
std::cout << "Using the format string '" << fmt
<< "' to format the time: " << std::ctime(&t) << '\n';
std::locale::global(std::locale("de_DE.utf8"));
try_time_put(&tm, fmt);
std::locale::global(std::locale("el_GR.utf8"));
try_time_put(&tm, fmt);
std::locale::global(std::locale("ja_JP.utf8"));
try_time_put(&tm, fmt);
}
```
Output:
```
Using the format string '%c' to format the time: Mon Feb 11 22:58:50 2013
In the locale 'de_DE.utf8' : 'Mo 11 Feb 2013 23:02:38 EST'
In the locale 'el_GR.utf8' : 'Δευ 11 Φεβ 2013 11:02:38 μμ EST'
In the locale 'ja_JP.utf8' : '2013年02月11日 23時02分38秒'
```
### See also
| | |
| --- | --- |
| [put\_time](../../io/manip/put_time "cpp/io/manip/put time")
(C++11) | formats and outputs a date/time value according to the specified format (function template) |
| [do\_get](../time_get/get "cpp/locale/time get/get")
[virtual] (C++11) | extracts date/time components from input stream, according to the specified format (virtual protected member function of `std::time_get<CharT,InputIt>`) |
| programming_docs |
cpp std::time_put<CharT,OutputIt>::~time_put std::time\_put<CharT,OutputIt>::~time\_put
==========================================
| Defined in header `[<locale>](../../header/locale "cpp/header/locale")` | | |
| --- | --- | --- |
|
```
protected: ~time_put();
```
| | |
Destructs a `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)` facet. This destructor is protected and virtual (due to [base class](../locale/facet "cpp/locale/locale/facet") destructor being virtual). An object of type `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)`, like most facets, can only be destroyed when the last `[std::locale](../locale "cpp/locale/locale")` object that implements this facet goes out of scope or if a user-defined class is derived from `[std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)` and implements a public destructor.
### Example
```
#include <iostream>
#include <locale>
struct Destructible_time_put : public std::time_put<wchar_t>
{
Destructible_time_put(std::size_t refs = 0) : time_put(refs) {}
// note: the implicit destructor is public
};
int main()
{
Destructible_time_put dc;
// std::time_put<wchar_t> c; // compile error: protected destructor
}
```
cpp std::allocator_arg std::allocator\_arg
===================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
struct allocator_arg_t { explicit allocator_arg_t() = default; };
```
| | (since C++11) |
|
```
constexpr std::allocator_arg_t allocator_arg = std::allocator_arg_t();
```
| | (since C++11) (until C++17) |
|
```
inline constexpr std::allocator_arg_t allocator_arg = std::allocator_arg_t();
```
| | (since C++17) |
`std::allocator_arg_t` is an empty class type used to disambiguate the overloads of constructors and member functions of allocator-aware objects, including `[std::tuple](../utility/tuple "cpp/utility/tuple")`, `[std::function](../utility/functional/function "cpp/utility/functional/function")`, `[std::packaged\_task](../thread/packaged_task "cpp/thread/packaged task")`, (until C++17)and `[std::promise](../thread/promise "cpp/thread/promise")`. `std::allocator_arg` is a constant of it.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | the default constructor was non-explicit, which could lead to ambiguity | made explicit |
### See also
| | |
| --- | --- |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
cpp std::allocator_traits std::allocator\_traits
======================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Alloc >
struct allocator_traits;
```
| | (since C++11) |
The `allocator_traits` class template provides the standardized way to access various properties of [Allocators](../named_req/allocator "cpp/named req/Allocator"). The standard containers and other standard library components access allocators through this template, which makes it possible to use any class type as an allocator, as long as the user-provided specialization of `allocator_traits` implements all required functionality.
The default, non-specialized, `allocator_traits` contains the following members:
### Member types
| Type | Definition |
| --- | --- |
| `allocator_type` | `Alloc` |
| `value_type` | `Alloc::value_type` |
| `pointer` | `Alloc::pointer` if present, otherwise `value_type*` |
| `const_pointer` | `Alloc::const_pointer` if present, otherwise `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<pointer>::rebind<const value_type>` |
| `void_pointer` | `Alloc::void_pointer` if present, otherwise `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<pointer>::rebind<void>` |
| `const_void_pointer` | `Alloc::const_void_pointer` if present, otherwise `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<pointer>::rebind<const void>` |
| `difference_type` | `Alloc::difference_type` if present, otherwise `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<pointer>::difference\_type` |
| `size_type` | `Alloc::size_type` if present, otherwise `[std::make\_unsigned](http://en.cppreference.com/w/cpp/types/make_unsigned)<difference_type>::type` |
| `propagate_on_container_copy_assignment` | `Alloc::propagate_on_container_copy_assignment` if present, otherwise `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` |
| `propagate_on_container_move_assignment` | `Alloc::propagate_on_container_move_assignment` if present, otherwise `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` |
| `propagate_on_container_swap` | `Alloc::propagate_on_container_swap` if present, otherwise `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` |
| `is_always_equal` | `Alloc::is_always_equal` if present, otherwise `[std::is\_empty](http://en.cppreference.com/w/cpp/types/is_empty)<Alloc>::type` |
### Member alias templates
| Type | Definition |
| --- | --- |
| `rebind_alloc<T>` | `Alloc::rebind<T>::other` if present, otherwise `Alloc<T, Args>` if this Alloc is `Alloc<U, Args>` |
| `rebind_traits<T>` | `std::allocator_traits<rebind_alloc<T>>` |
### Member functions
| | |
| --- | --- |
| [allocate](allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function) |
| [deallocate](allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function) |
| [construct](allocator_traits/construct "cpp/memory/allocator traits/construct")
[static] | constructs an object in the allocated storage (function template) |
| [destroy](allocator_traits/destroy "cpp/memory/allocator traits/destroy")
[static] | destructs an object stored in the allocated storage (function template) |
| [max\_size](allocator_traits/max_size "cpp/memory/allocator traits/max size")
[static] | returns the maximum object size supported by the allocator (public static member function) |
| [select\_on\_container\_copy\_construction](allocator_traits/select_on_container_copy_construction "cpp/memory/allocator traits/select on container copy construction")
[static] | obtains the allocator to use after copying a standard container (public static member function) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2108](https://cplusplus.github.io/LWG/issue2108) | C++11 | there was no way to show an allocator is stateless | `is_always_equal` provided |
### See also
| | |
| --- | --- |
| [allocator](allocator "cpp/memory/allocator") | the default allocator (class template) |
| [scoped\_allocator\_adaptor](scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")
(C++11) | implements multi-level allocator for multi-level containers (class template) |
| [pointer\_traits](pointer_traits "cpp/memory/pointer traits")
(C++11) | provides information about pointer-like types (class template) |
cpp std::uses_allocator_construction_args std::uses\_allocator\_construction\_args
========================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| `T` is not a specialization of `[std::pair](../utility/pair "cpp/utility/pair")` | | |
|
```
template< class T, class Alloc, class... Args >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
Args&&... args) noexcept;
```
| (1) | (since C++20) |
| `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")` | | |
|
```
template< class T, class Alloc, class Tuple1, class Tuple2 >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
std::piecewise_construct_t, Tuple1&& x, Tuple2&& y) noexcept;
```
| (2) | (since C++20) |
|
```
template< class T, class Alloc >
constexpr auto uses_allocator_construction_args( const Alloc& alloc ) noexcept;
```
| (3) | (since C++20) |
|
```
template< class T, class Alloc, class U, class V >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
U&& u, V&& v) noexcept;
```
| (4) | (since C++20) |
|
```
template< class T, class Alloc, class U, class V >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
std::pair<U, V>& pr ) noexcept;
```
| (5) | (since C++23) |
|
```
template< class T, class Alloc, class U, class V >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
const std::pair<U, V>& pr ) noexcept;
```
| (6) | (since C++20) |
|
```
template< class T, class Alloc, class U, class V >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
std::pair<U, V>&& pr ) noexcept;
```
| (7) | (since C++20) |
|
```
template< class T, class Alloc, class U, class V >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
const std::pair<U, V>&& pr ) noexcept;
```
| (8) | (since C++23) |
|
```
template< class T, class Alloc, class NonPair >
constexpr auto uses_allocator_construction_args( const Alloc& alloc,
NonPair&& non_pair ) noexcept;
```
| (9) | (since C++20) |
Prepares the argument list needed to create an object of the given type `T` by means of [uses-allocator construction](uses_allocator "cpp/memory/uses allocator").
1) This overload participates in overload resolution only if `T` is not a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. Returns `[std::tuple](../utility/tuple "cpp/utility/tuple")` determined as follows: * If `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T, Alloc>` is `false` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args...>` is `true`, returns `[std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`
* Otherwise, if `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T, Alloc>` is `true` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, [std::allocator\_arg\_t](http://en.cppreference.com/w/cpp/memory/allocator_arg_t), const Alloc&, Args...>` is `true`, returns `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<[std::allocator\_arg\_t](http://en.cppreference.com/w/cpp/memory/allocator_arg_t), const Alloc&, Args&&...>([std::allocator\_arg](http://en.cppreference.com/w/cpp/memory/allocator_arg), alloc, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`
* Otherwise, if `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T, Alloc>` is `true` and `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, Args..., const Alloc&>` is `true`, returns `[std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)..., alloc)`
* Otherwise, the program is ill-formed
2) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. For `T` that is `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<T1, T2>`, equivalent to
```
return std::make_tuple( std::piecewise_construct,
std::apply( [&alloc](auto&&... args1) {
return std::uses_allocator_construction_args<T1>( alloc,
std::forward<decltype(args1)>(args1)...);
}, std::forward<Tuple1>(x)),
std::apply( [&alloc](auto&&... args2) {
return std::uses_allocator_construction_args<T2>( alloc,
std::forward<decltype(args2)>(args2)...);
}, std::forward<Tuple2>(y))
);
```
3) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. Equivalent to
```
return std::uses_allocator_construction_args<T>(alloc,
std::piecewise_construct, std::tuple<>{}, std::tuple<>{}
);
```
4) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. Equivalent to
```
return std::uses_allocator_construction_args<T>( alloc,
std::piecewise_construct,
std::forward_as_tuple(std::forward<U>(u)),
std::forward_as_tuple(std::forward<V>(v))
);
```
5-6) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. Equivalent to
```
return std::uses_allocator_construction_args<T>( alloc,
std::piecewise_construct,
std::forward_as_tuple(pr.first),
std::forward_as_tuple(pr.second)
);
```
7-8) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`. Equivalent to
```
return std::uses_allocator_construction_args<T>( alloc,
std::piecewise_construct,
std::forward_as_tuple(std::get<0>(std::move(pr))),
std::forward_as_tuple(std::get<1>(std::move(pr))));
```
9) This overload participates in overload resolution only if `T` is a specialization of `[std::pair](../utility/pair "cpp/utility/pair")`, and given the exposition-only function template
```
template< class A, class B >
void /*deduce-as-pair*/( const std::pair<A, B>& );
```
, `/*deduce-as-pair*/(non_pair)` is ill-formed when considered as an unevaluated operand.
Let the exposition-only class `*pair-constructor*` be defined as.
```
class /*pair-constructor*/ {
const Alloc& alloc_; // exposition only
NonPair& u_; // exposition only
constexpr reconstruct(const std::remove_cv<T>& p) const // exposition only
{
return std::make_obj_using_allocator<std::remove_cv<T>>(alloc_, p);
}
constexpr reconstruct(std::remove_cv<T>&& p) const // exposition only
{
return std::make_obj_using_allocator<std::remove_cv<T>>(alloc_, std::move(p));
}
public:
constexpr operator std::remove_cv<T>() const
{
return reconstruct(std::forward<NonPair>(u_));
}
};
```
This overload is equivalent to `return [std::make\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/make_tuple)(pair_construction);`, where `pair_construction` is a value of type `*pair-constructor*` whose `*alloc\_*` and `*u\_*` members are `alloc` and `non_pair` respectively. ### Parameters
| | | |
| --- | --- | --- |
| alloc | - | the allocator to use. |
| args | - | the arguments to pass to `T`'s constructor |
| x | - | tuple of arguments to pass to the constructors of `T`'s `first` data member |
| y | - | tuple of arguments to pass to the constructors of `T`'s `second` data member |
| u | - | single argument to pass to the constructor of `T`'s `first` data member |
| v | - | single argument to pass to the constructor of `T`'s `second` data member |
| pr | - | a pair whose `first` data member will be passed to the constructor of `T`'s `first` data member and `second` data member will be passed to the constructor of `T`'s `second` data member |
| non\_pair | - | single argument to convert to a `[std::pair](../utility/pair "cpp/utility/pair")` for further construction |
### Return value
`[std::tuple](../utility/tuple "cpp/utility/tuple")` of arguments suitable for passing to the constructor of `T`.
### Example
### Notes
The overloads (2-9) provide allocator propagation into `[std::pair](../utility/pair "cpp/utility/pair")`, which supports neither leading-allocator nor trailing-allocator calling conventions (unlike, e.g. `[std::tuple](../utility/tuple "cpp/utility/tuple")`, which uses leading-allocator convention).
When used in uses-allocator construction, the conversion function of `*pair-constructor*` converts the provided argument to `[std::pair](../utility/pair "cpp/utility/pair")` at first, and then constructs the result from that `[std::pair](../utility/pair "cpp/utility/pair")` by uses-allocator construction.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3525](https://cplusplus.github.io/LWG/issue3525) | C++20 | no overload could handle non-`pair` types convertible to `pair` | reconstructing overload added |
### See also
| | |
| --- | --- |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
| [make\_obj\_using\_allocator](make_obj_using_allocator "cpp/memory/make obj using allocator")
(C++20) | creates an object of the given type by means of uses-allocator construction (function template) |
| [uninitialized\_construct\_using\_allocator](uninitialized_construct_using_allocator "cpp/memory/uninitialized construct using allocator")
(C++20) | creates an object of the given type at specified memory location by means of uses-allocator construction (function template) |
cpp std::allocator std::allocator
==============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
struct allocator;
```
| (1) | |
|
```
template<>
struct allocator<void>;
```
| (2) | (deprecated in C++17) (removed in C++20) |
The `std::allocator` class template is the default [Allocator](../named_req/allocator "cpp/named req/Allocator") used by all standard library containers if no user-specified allocator is provided. The default allocator is stateless, that is, all instances of the given allocator are interchangeable, compare equal and can deallocate memory allocated by any other instance of the same allocator type.
| | |
| --- | --- |
| The explicit specialization for `void` lacks the member typedefs `reference`, `const_reference`, `size_type` and `difference_type`. This specialization declares no member functions. | (until C++20) |
| | |
| --- | --- |
| The default allocator satisfies [allocator completeness requirements](../named_req/allocator#Allocator_completeness_requirements "cpp/named req/Allocator"). | (since C++17) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
| `pointer` (deprecated in C++17)(removed in C++20) | `T*` |
| `const_pointer` (deprecated in C++17)(removed in C++20) | `const T*` |
| `reference` (deprecated in C++17)(removed in C++20) | `T&` |
| `const_reference` (deprecated in C++17)(removed in C++20) | `const T&` |
| `size_type` | `[std::size\_t](../types/size_t "cpp/types/size t")` |
| `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
| `propagate_on_container_move_assignment`(C++11) | `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` |
| `rebind` (deprecated in C++17)(removed in C++20) | `template< class U > struct rebind { typedef allocator<U> other; };` |
| `is_always_equal`(C++11)(deprecated in C++23) | `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` |
### Member functions
| | |
| --- | --- |
| [(constructor)](allocator/allocator "cpp/memory/allocator/allocator") | creates a new allocator instance (public member function) |
| [(destructor)](allocator/~allocator "cpp/memory/allocator/~allocator") | destructs an allocator instance (public member function) |
| [address](allocator/address "cpp/memory/allocator/address")
(until C++20) | obtains the address of an object, even if `operator&` is overloaded (public member function) |
| [allocate](allocator/allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function) |
| [allocate\_at\_least](allocator/allocate_at_least "cpp/memory/allocator/allocate at least")
(C++23) | allocates uninitialized storage at least as large as requested size (public member function) |
| [deallocate](allocator/deallocate "cpp/memory/allocator/deallocate") | deallocates storage (public member function) |
| [max\_size](allocator/max_size "cpp/memory/allocator/max size")
(until C++20) | returns the largest supported allocation size (public member function) |
| [construct](allocator/construct "cpp/memory/allocator/construct")
(until C++20) | constructs an object in allocated storage (public member function) |
| [destroy](allocator/destroy "cpp/memory/allocator/destroy")
(until C++20) | destructs an object in allocated storage (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](allocator/operator_cmp "cpp/memory/allocator/operator cmp")
(removed in C++20) | compares two allocator instances (public member function) |
### Notes
The member template class `rebind` provides a way to obtain an allocator for a different type. For example, `std::list<T, A>` allocates nodes of some internal type `Node<T>`, using the allocator `A::rebind<Node<T>>::other` (until C++11)`[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<Node<T>>`, which is implemented in terms of `A::rebind<Node<T>>::other` if A is an `std::allocator` (since C++11).
Member type `is_always_equal` is deprecated via [LWG issue 3170](https://cplusplus.github.io/LWG/issue3170), because it makes custom allocators derived from `std::allocator` treated as always equal by default. `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<std::allocator<T>>::is\_always\_equal` is not deprecated and its member constant `value` is `true` for any `T`.
### Example
```
#include <memory>
#include <iostream>
#include <string>
int main()
{
{
// default allocator for ints
std::allocator<int> alloc;
// demonstrating the few directly usable members
static_assert(std::is_same_v<int, decltype(alloc)::value_type>);
int* p = alloc.allocate(1); // space for one int
alloc.deallocate(p, 1); // and it is gone
// Even those can be used through traits though, so no need
using traits_t = std::allocator_traits<decltype(alloc)>; // The matching trait
p = traits_t::allocate(alloc, 1);
traits_t::construct(alloc, p, 7); // construct the int
std::cout << *p << '\n';
traits_t::deallocate(alloc, p, 1); // deallocate space for one int
}
{
// default allocator for strings
std::allocator<std::string> alloc;
// matching traits
using traits_t = std::allocator_traits<decltype(alloc)>;
// Rebinding the allocator using the trait for strings gets the same type
traits_t::rebind_alloc<std::string> alloc_ = alloc;
std::string* p = traits_t::allocate(alloc, 2); // space for 2 strings
traits_t::construct(alloc, p, "foo");
traits_t::construct(alloc, p + 1, "bar");
std::cout << p[0] << ' ' << p[1] << '\n';
traits_t::destroy(alloc, p + 1);
traits_t::destroy(alloc, p);
traits_t::deallocate(alloc, p, 2);
}
}
```
Output:
```
7
foo bar
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2103](https://cplusplus.github.io/LWG/issue2103) | C++11 | redundant comparison between `allocator` might be required | `propagate_on_container_move_assignment` provided |
| [LWG 2108](https://cplusplus.github.io/LWG/issue2108) | C++11 | there was no way to show `allocator` is stateless | `is_always_equal` provided |
### See also
| | |
| --- | --- |
| [allocator\_traits](allocator_traits "cpp/memory/allocator traits")
(C++11) | provides information about allocator types (class template) |
| [scoped\_allocator\_adaptor](scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")
(C++11) | implements multi-level allocator for multi-level containers (class template) |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
| programming_docs |
cpp std::pmr::get_default_resource std::pmr::get\_default\_resource
================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* get_default_resource() noexcept;
```
| | (since C++17) |
Gets the default memory resource pointer.
The *default memory resource pointer* is used by certain facilities when an explicit memory resource is not supplied. The initial default memory resource pointer is the return value of `[std::pmr::new\_delete\_resource](new_delete_resource "cpp/memory/new delete resource")`.
This function is thread-safe. Previous call to `[std::pmr::set\_default\_resource](set_default_resource "cpp/memory/set default resource")` *synchronizes with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the subsequent `std::pmr::get_default_resource` calls.
### Return value
Returns the value of the default memory resource pointer.
### See also
| | |
| --- | --- |
| [set\_default\_resource](set_default_resource "cpp/memory/set default resource")
(C++17) | sets the default `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` (function) |
| [new\_delete\_resource](new_delete_resource "cpp/memory/new delete resource")
(C++17) | returns a static program-wide `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` that uses the global `[operator new](new/operator_new "cpp/memory/new/operator new")` and `[operator delete](new/operator_delete "cpp/memory/new/operator delete")` to allocate and deallocate memory (function) |
cpp std::pmr::synchronized_pool_resource std::pmr::synchronized\_pool\_resource
======================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
class synchronized_pool_resource : public std::pmr::memory_resource;
```
| | (since C++17) |
The class `std::pmr::synchronized_pool_resource` is a general-purpose memory resource class with the following properties:
* It owns the allocated memory and frees it on destruction, even if `deallocate` has not been called for some of the allocated blocks.
* It consists of a collection of *pools* that serves request for different block sizes. Each pool manages a collection of *chunks* that are then divided into blocks of uniform size.
* Calls to [`do_allocate`](synchronized_pool_resource/do_allocate "cpp/memory/synchronized pool resource/do allocate") are dispatched to the pool serving the smallest blocks accommodating the requested size.
* Exhausting memory in the pool causes the next allocation request for that pool to allocate an additional chunk of memory from the *upstream allocator* to replenish the pool. The chunk size obtained increases geometrically.
* Allocations requests that exceed the largest block size are served from the *upstream allocator* directly.
* The largest block size and maximum chunk size may be tuned by passing a `[std::pmr::pool\_options](pool_options "cpp/memory/pool options")` struct to its constructor.
`synchronized_pool_resource` may be accessed from multiple threads without external synchronization, and may have thread-specific pools to reduce synchronization costs. If the memory resource is only accessed from one thread, [`unsynchronized_pool_resource`](unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource") is more efficient.
### Member functions
| | |
| --- | --- |
| [(constructor)](synchronized_pool_resource/synchronized_pool_resource "cpp/memory/synchronized pool resource/synchronized pool resource") | Constructs a `synchronized_pool_resource` (public member function) |
| [(destructor)](synchronized_pool_resource/~synchronized_pool_resource "cpp/memory/synchronized pool resource/~synchronized pool resource")
[virtual] | Destroys a `synchronized_pool_resource`, releasing all allocated memory (virtual public member function) |
| operator=
[deleted] | Copy assignment operator is deleted. `synchronized_pool_resource` is not copy assignable (public member function) |
| Public member functions |
| [release](synchronized_pool_resource/release "cpp/memory/synchronized pool resource/release") | Release all allocated memory (public member function) |
| [upstream\_resource](synchronized_pool_resource/upstream_resource "cpp/memory/synchronized pool resource/upstream resource") | Returns a pointer to the upstream memory resource (public member function) |
| [options](synchronized_pool_resource/options "cpp/memory/synchronized pool resource/options") | Returns the options that control the pooling behavior of this resource (public member function) |
| Protected member functions |
| [do\_allocate](synchronized_pool_resource/do_allocate "cpp/memory/synchronized pool resource/do allocate")
[virtual] | Allocate memory (virtual protected member function) |
| [do\_deallocate](synchronized_pool_resource/do_deallocate "cpp/memory/synchronized pool resource/do deallocate")
[virtual] | Return memory to the pool (virtual protected member function) |
| [do\_is\_equal](synchronized_pool_resource/do_is_equal "cpp/memory/synchronized pool resource/do is equal")
[virtual] | Compare for equality with another `memory_resource` (virtual protected member function) |
cpp std::to_address std::to\_address
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Ptr >
constexpr auto to_address(const Ptr& p) noexcept;
```
| (1) | (since C++20) |
|
```
template< class T >
constexpr T* to_address(T* p) noexcept;
```
| (2) | (since C++20) |
Obtain the address represented by `p` without forming a reference to the object pointed to by `p`.
1) [Fancy pointer](../named_req/allocator#Fancy_pointers "cpp/named req/Allocator") overload: If the expression `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Ptr>::to\_address(p)` is well-formed, returns the result of that expression. Otherwise, returns `std::to_address(p.operator->())`.
2) Raw pointer overload: If `T` is a function type, the program is ill-formed. Otherwise, returns `p` unmodified. ### Parameters
| | | |
| --- | --- | --- |
| p | - | fancy or raw pointer |
### Return value
Raw pointer that represents the same address as `p` does.
### Possible implementation
| |
| --- |
|
```
template<class T>
constexpr T* to_address(T* p) noexcept
{
static_assert(!std::is_function_v<T>);
return p;
}
template<class T>
constexpr auto to_address(const T& p) noexcept
{
if constexpr (requires{ std::pointer_traits<T>::to_address(p); }) {
return std::pointer_traits<T>::to_address(p);
} else {
return std::to_address(p.operator->());
}
}
```
|
### Notes
`std::to_address` can be used even when `p` does not reference storage that has an object constructed in it, in which case `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(\*p)` cannot be used because there's no valid object for the parameter of `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)` to bind to.
The fancy pointer overload of `to_address` inspects the `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Ptr>` specialization. If instantiating that specialization is itself ill-formed (typically because `element_type` cannot be defined), that results in a hard error outside the immediate context and renders the program ill-formed.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_to_address`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <memory>
template<class A>
auto allocator_new(A& a)
{
auto p = a.allocate(1);
try {
std::allocator_traits<A>::construct(a, std::to_address(p));
} catch (...) {
a.deallocate(p, 1);
throw;
}
return p;
}
template<class A>
void allocator_delete(A& a, typename std::allocator_traits<A>::pointer p)
{
std::allocator_traits<A>::destroy(a, std::to_address(p));
a.deallocate(p, 1);
}
int main()
{
std::allocator<int> a;
auto p = allocator_new(a);
allocator_delete(a, p);
}
```
### See also
| | |
| --- | --- |
| [pointer\_traits](pointer_traits "cpp/memory/pointer traits")
(C++11) | provides information about pointer-like types (class template) |
| [to\_address](pointer_traits/to_address "cpp/memory/pointer traits/to address")
[static] (C++20)(optional) | obtains a raw pointer from a fancy pointer (inverse of `pointer_to`) (public static member function of `std::pointer_traits<Ptr>`) |
cpp std::raw_storage_iterator std::raw\_storage\_iterator
===========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class OutputIt, class T >
class raw_storage_iterator
: public std::iterator<std::output_iterator_tag, void, void, void, void>;
```
| | (until C++17) |
|
```
template< class OutputIt, class T >
class raw_storage_iterator;
```
| | (since C++17) (deprecated) (removed in C++20) |
The output iterator `std::raw_storage_iterator` makes it possible for standard algorithms to store results in uninitialized memory. Whenever the algorithm writes an object of type `T` to the dereferenced iterator, the object is copy-constructed into the location in the uninitialized storage pointed to by the iterator. The template parameter `OutputIt` is any type that meets the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") and has `operator*` defined to return an object, for which `operator&` returns an object of type `T*`. Usually, the type `T*` is used as `OutputIt`.
### Type requirements
| |
| --- |
| -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](raw_storage_iterator/raw_storage_iterator "cpp/memory/raw storage iterator/raw storage iterator") | creates a new `raw_storage_iterator` (public member function) |
| [operator=](raw_storage_iterator/operator= "cpp/memory/raw storage iterator/operator=") | constructs an object at the pointed-to location in the buffer (public member function) |
| [operator\*](raw_storage_iterator/operator* "cpp/memory/raw storage iterator/operator*") | dereferences the iterator (public member function) |
| [operator++operator++(int)](raw_storage_iterator/operator_arith "cpp/memory/raw storage iterator/operator arith") | advances the iterator (public member function) |
| [base](raw_storage_iterator/base "cpp/memory/raw storage iterator/base")
(since C++17) | provides access to the wrapped iterator (public member function) |
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Example
```
#include <iostream>
#include <string>
#include <memory>
#include <algorithm>
int main()
{
const std::string s[] = {"This", "is", "a", "test", "."};
std::string* p = std::allocator<std::string>().allocate(5);
std::copy(std::begin(s), std::end(s),
std::raw_storage_iterator<std::string*, std::string>(p));
for(std::string* i = p; i!=p+5; ++i) {
std::cout << *i << '\n';
i->~basic_string<char>();
}
std::allocator<std::string>().deallocate(p, 5);
}
```
Output:
```
This
is
a
test
.
```
### See also
| | |
| --- | --- |
| [allocator\_traits](allocator_traits "cpp/memory/allocator traits")
(C++11) | provides information about allocator types (class template) |
| [scoped\_allocator\_adaptor](scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")
(C++11) | implements multi-level allocator for multi-level containers (class template) |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
cpp std::uninitialized_fill std::uninitialized\_fill
========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class ForwardIt, class T >
void uninitialized_fill( ForwardIt first, ForwardIt last, const T& value );
```
| (1) | |
|
```
template< class ExecutionPolicy, class ForwardIt, class T >
void uninitialized_fill( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value );
```
| (2) | (since C++17) |
1) Copies the given `value` to an uninitialized memory area, defined by the range `[first, last)` as if by
```
for (; first != last; ++first)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type(value);
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static_cast<void*>(&e)` | (until C++11) |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (since C++11)(until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of the elements to initialize |
| value | - | the value to construct the elements with |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. Applying `&*` to a `ForwardIt` value must yield a pointer to its value type. (until C++11) |
### Return value
(none).
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt, class T>
void uninitialized_fill(ForwardIt first, ForwardIt last, const T& value)
{
using V = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; current != last; ++current) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) V(value);
}
} catch (...) {
for (; first != current; ++first) {
first->~V();
}
throw;
}
}
```
|
### Example
```
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
int main()
{
std::string* p;
std::size_t sz;
std::tie(p, sz) = std::get_temporary_buffer<std::string>(4);
std::uninitialized_fill(p, p+sz, "Example");
for (std::string* i = p; i != p+sz; ++i) {
std::cout << *i << '\n';
i->~basic_string<char>();
}
std::return_temporary_buffer(p);
}
```
Output:
```
Example
Example
Example
Example
```
### See also
| | |
| --- | --- |
| [uninitialized\_fill\_n](uninitialized_fill_n "cpp/memory/uninitialized fill n") | copies an object to an uninitialized area of memory, defined by a start and a count (function template) |
| [ranges::uninitialized\_fill](ranges/uninitialized_fill "cpp/memory/ranges/uninitialized fill")
(C++20) | copies an object to an uninitialized area of memory, defined by a range (niebloid) |
cpp std::uninitialized_default_construct std::uninitialized\_default\_construct
======================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class ForwardIt >
void uninitialized_default_construct( ForwardIt first, ForwardIt last);
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt >
void uninitialized_default_construct( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last );
```
| (2) | (since C++17) |
1) Constructs objects of type `typename iterator_traits<ForwardIt>::value_type` in the uninitialized storage designated by the range `[first, last)` by [default-initialization](../language/default_initialization "cpp/language/default initialization"), as if by
```
for (; first != last; ++first)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type;
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of the elements to initialize |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
(none).
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt>
void uninitialized_default_construct(ForwardIt first, ForwardIt last)
{
using Value = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; current != last; ++current) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) Value;
}
} catch (...) {
std::destroy(first, current);
throw;
}
}
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
int main()
{
struct S { std::string m{ "Default value" }; };
constexpr int n {3};
alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(mem)};
auto last {first + n};
std::uninitialized_default_construct(first, last);
for (auto it {first}; it != last; ++it) {
std::cout << it->m << '\n';
}
std::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_default_construct
// generally does not zero-fill the given uninitialized memory area.
int v[] { 1, 2, 3, 4 };
const int original[] { 1, 2, 3, 4 };
std::uninitialized_default_construct(std::begin(v), std::end(v));
// for (const int i : v) { std::cout << i << ' '; }
// Maybe undefined behavior, pending CWG 1997.
std::cout <<
(std::memcmp(v, original, sizeof(v)) == 0 ? "Unmodified\n" : "Modified\n");
// The result is unspecified.
}
```
Possible output:
```
Default value
Default value
Default value
Unmodified
```
### See also
| | |
| --- | --- |
| [uninitialized\_default\_construct\_n](uninitialized_default_construct_n "cpp/memory/uninitialized default construct n")
(C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
| [uninitialized\_value\_construct](uninitialized_value_construct "cpp/memory/uninitialized value construct")
(C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (function template) |
| [ranges::uninitialized\_default\_construct](ranges/uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct")
(C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| programming_docs |
cpp std::allocate_at_least std::allocate\_at\_least
========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Alloc >
[[nodiscard]] constexpr std::allocation_result<
typename std::allocator_traits<Alloc>::pointer>
allocate_at_least( Alloc& a, std::size_t n );
```
| | (since C++23) |
`std::allocate_at_least` calls `a.allocate_at_least(n)` and returns its result if the call is well-formed, otherwise, it is equivalent to `return {a.allocate(n), n};`.
For an [Allocator](../named_req/allocator "cpp/named req/Allocator") `a`, `std::allocator_at_least` tries to allocate a storage for at least `n` `Alloc::value_type` objects, and provides a fallback mechanism (like those provided by `[std::allocator\_traits](allocator_traits "cpp/memory/allocator traits")`) that allocates a storage for exact `n` objects.
### Parameters
| | | |
| --- | --- | --- |
| a | - | an allocator used for allocating storage |
| n | - | the lower bound of number of objects to allocate storage for |
### Return value
`a.allocate_at_least(n)` if it is well-formed, otherwise, `{a.allocate(n), n}`.
### Exceptions
Throws what and when the selected allocation function throws.
### Notes
The `allocate_at_least` member function of [Allocator](../named_req/allocator "cpp/named req/Allocator") types are mainly provided for contiguous containers, e.g. `[std::vector](../container/vector "cpp/container/vector")` and `[std::basic\_string](../string/basic_string "cpp/string/basic string")`, in order to reduce reallocation by making their capacity match the actually allocated size when possible. Because `std::allocate_at_least` provides a fallback mechanism, it can be directly used where appropriate.
Given an allocator object `a` of type `Alloc`, let `result` denote the value returned from `std::allocate_at_least(a, n)`, the storage should be deallocated by `a.deallocate(result.ptr, m)` (typically called via `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Alloc>::deallocate(a, result.ptr, m)`) in order to avoid memory leak.
The argument `m` used in deallocation must be not less than `n` and not greater than `result.count`, otherwise, the behavior is undefined. Note that `n` is always equal to `result.count` if the allocator does not support `allocate_at_least`, which means that `m` is required to be equal to `n`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_allocate_at_least`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [allocate\_at\_least](allocator/allocate_at_least "cpp/memory/allocator/allocate at least")
(C++23) | allocates uninitialized storage at least as large as requested size (public member function of `std::allocator<T>`) |
| [allocator\_traits](allocator_traits "cpp/memory/allocator traits")
(C++11) | provides information about allocator types (class template) |
cpp C memory management library C memory management library
===========================
### Functions
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| --- |
| [malloc](c/malloc "cpp/memory/c/malloc") | allocates memory (function) |
| [aligned\_alloc](c/aligned_alloc "cpp/memory/c/aligned alloc")
(C++17) | allocates aligned memory (function) |
| [calloc](c/calloc "cpp/memory/c/calloc") | allocates and zeroes memory (function) |
| [realloc](c/realloc "cpp/memory/c/realloc") | expands or shrinks previously allocated memory block (function) |
| [free](c/free "cpp/memory/c/free") | deallocates previously allocated memory (function) |
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/memory "c/memory") for C memory management library |
cpp std::pmr::new_delete_resource std::pmr::new\_delete\_resource
===============================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* new_delete_resource() noexcept;
```
| | (since C++17) |
Returns a pointer to a `memory_resource` that uses the global `[operator new](new/operator_new "cpp/memory/new/operator new")` and `[operator delete](new/operator_delete "cpp/memory/new/operator delete")` to allocate memory.
### Return value
Returns a pointer `p` to a static storage duration object of a type derived from `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")`, with the following properties:
* its `allocate()` function uses `::[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` to allocate memory;
* its `deallocate()` function uses `::[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)` to deallocate memory;
* for any `memory_resource` `r`, `p->is_equal(r)` returns `&r == p`.
The same value is returned every time this function is called.
cpp std::uninitialized_value_construct_n std::uninitialized\_value\_construct\_n
=======================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class ForwardIt, class Size >
ForwardIt uninitialized_value_construct_n( ForwardIt first, Size n );
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size >
ForwardIt uninitialized_value_construct_n( ExecutionPolicy&& policy, ForwardIt first, Size n );
```
| (2) | (since C++17) |
1) Constructs `n` objects of type `typename iterator_traits<ForwardIt>::value_type` in the uninitialized storage starting at `first` by [value-initialization](../language/value_initialization "cpp/language/value initialization"), as if by
```
for (; n > 0; (void) ++first, --n)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type();
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to initialize |
| n | - | the number of elements to initialize |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
The end of the range of objects (i.e., `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(first, n)`).
### Complexity
Linear in `n`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt, class Size>
ForwardIt uninitialized_value_construct_n( ForwardIt first, Size n )
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; n > 0 ; (void) ++current, --n) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) T();
}
return current;
} catch (...) {
std::destroy(first, current);
throw;
}
}
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "Default value" }; };
constexpr int n {3};
alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(mem)};
auto last = std::uninitialized_value_construct_n(first, n);
for (auto it {first}; it != last; ++it) {
std::cout << it->m << '\n';
}
std::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_value_construct_n
// zero-initializes the given uninitialized memory area.
int v[] { 1, 2, 3, 4 };
for (const int i : v) { std::cout << i << ' '; }
std::cout << '\n';
std::uninitialized_value_construct_n(std::begin(v), std::size(v));
for (const int i : v) { std::cout << i << ' '; }
std::cout << '\n';
}
```
Output:
```
Default value
Default value
Default value
1 2 3 4
0 0 0 0
```
### See also
| | |
| --- | --- |
| [uninitialized\_value\_construct](uninitialized_value_construct "cpp/memory/uninitialized value construct")
(C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (function template) |
| [uninitialized\_default\_construct\_n](uninitialized_default_construct_n "cpp/memory/uninitialized default construct n")
(C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
| [ranges::uninitialized\_value\_construct\_n](ranges/uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n")
(C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) |
cpp std::bad_weak_ptr std::bad\_weak\_ptr
===================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
class bad_weak_ptr;
```
| | (since C++11) |
`std::bad_weak_ptr` is the type of the object thrown as exceptions by the constructors of `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` that take `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` as the argument, when the `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` refers to an already deleted object.
![std-bad weak ptr-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs a new `bad_weak_ptr` object (public member function) |
| operator= | replaces the `bad_weak_ptr` object (public member function) |
| what | returns the explanatory string (public member function) |
std::bad\_weak\_ptr::bad\_weak\_ptr
------------------------------------
| | | |
| --- | --- | --- |
|
```
bad_weak_ptr() noexcept;
```
| (1) | (since C++11) |
|
```
bad_weak_ptr( const bad_weak_ptr& other ) noexcept;
```
| (2) | (since C++11) |
Constructs a new `bad_weak_ptr` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../error/exception/what "cpp/error/exception/what").
1) Default constructor.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_weak_ptr` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to copy |
std::bad\_weak\_ptr::operator=
-------------------------------
| | | |
| --- | --- | --- |
|
```
bad_weak_ptr& operator=( const bad_weak_ptr& other ) noexcept;
```
| | (since C++11) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_weak_ptr` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::bad\_weak\_ptr::what
--------------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const noexcept;
```
| | (since C++11) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::exception](../error/exception "cpp/error/exception")
---------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
### Example
```
#include <memory>
#include <iostream>
int main()
{
std::shared_ptr<int> p1(new int(42));
std::weak_ptr<int> wp(p1);
p1.reset();
try {
std::shared_ptr<int> p2(wp);
} catch(const std::bad_weak_ptr& e) {
std::cout << e.what() << '\n';
}
}
```
Possible output:
```
std::bad_weak_ptr
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2376](https://cplusplus.github.io/LWG/issue2376) | C++11 | calling `what` on a default-constructed `bad_weak_ptr` was required to return `"bad_weak_ptr"` | the return value is implementation-defined |
### See also
| | |
| --- | --- |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
| [weak\_ptr](weak_ptr "cpp/memory/weak ptr")
(C++11) | weak reference to an object managed by `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` (class template) |
cpp std::destroy_n std::destroy\_n
===============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class ForwardIt, class Size >
ForwardIt destroy_n( ForwardIt first, Size n );
```
| (since C++17) (until C++20) |
|
```
template< class ForwardIt, class Size >
constexpr ForwardIt destroy_n( ForwardIt first, Size n );
```
| (since C++20) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size >
ForwardIt destroy_n( ExecutionPolicy&& policy, ForwardIt first, Size n );
```
| (2) | (since C++17) |
1) Destroys the `n` objects in the range starting at `first`, as if by
```
for (; n > 0; (void) ++first, --n)
std::destroy_at(std::addressof(*first));
```
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to destroy |
| n | - | the number of elements to destroy |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
The end of the range of objects that has been destroyed (i.e., `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(first, n)`).
### Complexity
Linear in `n`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt, class Size>
constexpr // since C++20
ForwardIt destroy_n( ForwardIt first, Size n )
{
for (; n > 0; (void) ++first, --n)
std::destroy_at(std::addressof(*first));
return first;
}
```
|
### Example
The following example demonstrates how to use `destroy_n` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
std::destroy_n(ptr, 8);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [destroy](destroy "cpp/memory/destroy")
(C++17) | destroys a range of objects (function template) |
| [destroy\_at](destroy_at "cpp/memory/destroy at")
(C++17) | destroys an object at a given address (function template) |
| [ranges::destroy\_n](ranges/destroy_n "cpp/memory/ranges/destroy n")
(C++20) | destroys a number of objects in a range (niebloid) |
cpp std::uses_allocator std::uses\_allocator
====================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc > struct uses_allocator;
```
| | (since C++11) |
If `T` has a member typedef `allocator_type` which is convertible from `Alloc` or is an alias of `[std::experimental::erased\_type](https://en.cppreference.com/w/cpp/experimental/erased_type "cpp/experimental/erased type")` (library fundamentals TS), the member constant `value` is `true`. Otherwise `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class T, class Alloc >
inline constexpr bool uses_allocator_v = uses_allocator<T, Alloc>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../types/integral_constant "cpp/types/integral constant")
----------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `T` uses allocator `Alloc`, `false` otherwise (public static member constant) |
### Member functions
| | |
| --- | --- |
| operator bool | converts the object to `bool`, returns `value` (public member function) |
| operator()
(C++14) | returns `value` (public member function) |
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `bool` |
| `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` |
### Uses-allocator construction
There are three conventions of passing an allocator `alloc` to a constructor of some type `T`:
* if `T` does not use a compatible allocator (`std::uses_allocator_v<T, Alloc>` is false), then `alloc` is ignored.
* otherwise, `std::uses_allocator_v<T, Alloc>` is true, and
+ if `T` uses the *leading-allocator convention* (is invocable as `T([std::allocator\_arg](http://en.cppreference.com/w/cpp/memory/allocator_arg), alloc, args...)`), then uses-allocator construction uses this form
+ if `T` uses the *trailing-allocator convention* (is invocable as `T(args..., alloc)`), then uses-allocator construction uses this form
+ otherwise, the program is ill-formed (this means `std::uses_allocator_v<T, Alloc>` is true, but the type does not follow either of the two allowed conventions)
* As a special case, `[std::pair](../utility/pair "cpp/utility/pair")` is treated as a uses-allocator type even though `std::uses_allocator` is false for pairs (unlike e.g. `[std::tuple](../utility/tuple "cpp/utility/tuple")`): see pair-specific overloads of `[std::pmr::polymorphic\_allocator::construct](polymorphic_allocator/construct "cpp/memory/polymorphic allocator/construct")` and `[std::scoped\_allocator\_adaptor::construct](scoped_allocator_adaptor/construct "cpp/memory/scoped allocator adaptor/construct")` (until C++20)`[std::uses\_allocator\_construction\_args](uses_allocator_construction_args "cpp/memory/uses allocator construction args")` (since C++20)
| | |
| --- | --- |
| The utility functions `[std::make\_obj\_using\_allocator](make_obj_using_allocator "cpp/memory/make obj using allocator")`, and `[std::uninitialized\_construct\_using\_allocator](uninitialized_construct_using_allocator "cpp/memory/uninitialized construct using allocator")` may be used to explicitly create an object following the above protocol, and `[std::uses\_allocator\_construction\_args](uses_allocator_construction_args "cpp/memory/uses allocator construction args")` can be used to prepare the argument list that matches the flavor of uses-allocator construction expected by the type. | (since C++20) |
### Specializations
Custom specializations of the type trait `std::uses_allocator` are allowed for types that do not have the member typedef `allocator_type` but satisfy one of the following two requirements:
1) `T` has a constructor which takes `[std::allocator\_arg\_t](allocator_arg_t "cpp/memory/allocator arg t")` as the first argument, and `Alloc` as the second argument.
2) `T` has a constructor which takes `Alloc` as the last argument. In the above, `Alloc` is a type that satisfies [Allocator](../named_req/allocator "cpp/named req/Allocator") or is a pointer type convertible to `std::experimental::pmr::memory_resource*` (library fundamentals TS).
The following specializations are already provided by the standard library:
| | |
| --- | --- |
| [std::uses\_allocator<std::tuple>](../utility/tuple/uses_allocator "cpp/utility/tuple/uses allocator")
(C++11) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::queue>](../container/queue/uses_allocator "cpp/container/queue/uses allocator")
(C++11) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::priority\_queue>](../container/priority_queue/uses_allocator "cpp/container/priority queue/uses allocator")
(C++11) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::stack>](../container/stack/uses_allocator "cpp/container/stack/uses allocator")
(C++11) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::flat\_map>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_map/uses_allocator&action=edit&redlink=1 "cpp/container/flat map/uses allocator (page does not exist)")
(C++23) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::flat\_set>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_set/uses_allocator&action=edit&redlink=1 "cpp/container/flat set/uses allocator (page does not exist)")
(C++23) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::flat\_multimap>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multimap/uses_allocator&action=edit&redlink=1 "cpp/container/flat multimap/uses allocator (page does not exist)")
(C++23) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::flat\_multiset>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multiset/uses_allocator&action=edit&redlink=1 "cpp/container/flat multiset/uses allocator (page does not exist)")
(C++23) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::function>](../utility/functional/function/uses_allocator "cpp/utility/functional/function/uses allocator")
(C++11) (until C++17) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::promise>](../thread/promise/uses_allocator "cpp/thread/promise/uses allocator")
(C++11) | specializes the `std::uses_allocator` type trait (class template specialization) |
| [std::uses\_allocator<std::packaged\_task>](../thread/packaged_task/uses_allocator "cpp/thread/packaged task/uses allocator")
(C++11) (until C++17) | specializes the `std::uses_allocator` type trait (class template specialization) |
### Notes
This type trait is used by `[std::tuple](../utility/tuple "cpp/utility/tuple")`, `[std::scoped\_allocator\_adaptor](scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")`, and `[std::pmr::polymorphic\_allocator](polymorphic_allocator "cpp/memory/polymorphic allocator")`. It may also be used by custom allocators or wrapper types to determine whether the object or member being constructed is itself capable of using an allocator (e.g. is a container), in which case an allocator should be passed to its constructor.
### See also
| | |
| --- | --- |
| [allocator\_arg](allocator_arg "cpp/memory/allocator arg")
(C++11) | an object of type `[std::allocator\_arg\_t](allocator_arg_t "cpp/memory/allocator arg t")` used to select allocator-aware constructors (constant) |
| [allocator\_arg\_t](allocator_arg_t "cpp/memory/allocator arg t")
(C++11) | tag type used to select allocator-aware constructor overloads (class) |
| [uses\_allocator\_construction\_args](uses_allocator_construction_args "cpp/memory/uses allocator construction args")
(C++20) | prepares the argument list matching the flavor of uses-allocator construction required by the given type (function template) |
| [make\_obj\_using\_allocator](make_obj_using_allocator "cpp/memory/make obj using allocator")
(C++20) | creates an object of the given type by means of uses-allocator construction (function template) |
| [uninitialized\_construct\_using\_allocator](uninitialized_construct_using_allocator "cpp/memory/uninitialized construct using allocator")
(C++20) | creates an object of the given type at specified memory location by means of uses-allocator construction (function template) |
| [scoped\_allocator\_adaptor](scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")
(C++11) | implements multi-level allocator for multi-level containers (class template) |
| programming_docs |
cpp std::make_obj_using_allocator std::make\_obj\_using\_allocator
================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc, class... Args >
constexpr T make_obj_using_allocator( const Alloc& alloc, Args&&... args );
```
| | (since C++20) |
Creates an object of the given type `T` by means of [uses-allocator construction](uses_allocator "cpp/memory/uses allocator").
Equivalent to.
```
return std::make_from_tuple<T>(
std::uses_allocator_construction_args<T>(alloc, std::forward<Args>(args)...)
);
```
### Parameters
| | | |
| --- | --- | --- |
| alloc | - | the allocator to use. |
| args | - | the arguments to pass to T's constructor |
### Return value
The newly-created object of type `T`.
### Exceptions
May throw any exception thrown by the constructor of `T`, typically including `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")`.
### Example
### See also
| | |
| --- | --- |
| [uses\_allocator\_construction\_args](uses_allocator_construction_args "cpp/memory/uses allocator construction args")
(C++20) | prepares the argument list matching the flavor of uses-allocator construction required by the given type (function template) |
| [uninitialized\_construct\_using\_allocator](uninitialized_construct_using_allocator "cpp/memory/uninitialized construct using allocator")
(C++20) | creates an object of the given type at specified memory location by means of uses-allocator construction (function template) |
cpp std::uninitialized_default_construct_n std::uninitialized\_default\_construct\_n
=========================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class ForwardIt, class Size >
ForwardIt uninitialized_default_construct_n( ForwardIt first, Size n );
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size >
ForwardIt uninitialized_default_construct_n( ExecutionPolicy&& policy, ForwardIt first, Size n );
```
| (2) | (since C++17) |
1) Constructs `n` objects of type `typename iterator_traits<ForwardIt>::value_type` in the uninitialized storage starting at `first` by [default-initialization](../language/default_initialization "cpp/language/default initialization"), as if by
```
for (; n > 0; (void) ++first, --n)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type;
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to initialize |
| n | - | the number of elements to construct |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
The end of the range of objects (i.e., `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(first, n)`).
### Complexity
Linear in `n`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt, class Size>
ForwardIt uninitialized_default_construct_n( ForwardIt first, Size n )
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; n > 0 ; (void) ++current, --n) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) T;
}
return current;
} catch (...) {
std::destroy(first, current);
throw;
}
}
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "Default value" }; };
constexpr int n {3};
alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(mem)};
auto last = std::uninitialized_default_construct_n(first, n);
for (auto it {first}; it != last; ++it) {
std::cout << it->m << '\n';
}
std::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_default_construct_n
// generally does not zero-initialize the given uninitialized memory area.
int v[] { 1, 2, 3, 4 };
const int original[] { 1, 2, 3, 4 };
std::uninitialized_default_construct_n(std::begin(v), std::size(v));
// for (const int i : v) { std::cout << i << ' '; }
// Maybe undefined behavior, pending CWG 1997.
std::cout <<
(std::memcmp(v, original, sizeof(v)) == 0 ? "Unmodified\n" : "Modified\n");
// The result is unspecified.
}
```
Possible output:
```
Default value
Default value
Default value
Unmodified
```
### See also
| | |
| --- | --- |
| [uninitialized\_default\_construct](uninitialized_default_construct "cpp/memory/uninitialized default construct")
(C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (function template) |
| [uninitialized\_value\_construct\_n](uninitialized_value_construct_n "cpp/memory/uninitialized value construct n")
(C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
| [ranges::uninitialized\_default\_construct\_n](ranges/uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n")
(C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) |
cpp std::auto_ptr std::auto\_ptr
==============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T > class auto_ptr;
```
| (1) | (deprecated in C++11) (removed in C++17) |
|
```
template<> class auto_ptr<void>;
```
| (2) | (deprecated in C++11) (removed in C++17) |
`auto_ptr` is a smart pointer that manages an object obtained via [new expression](../language/new "cpp/language/new") and deletes that object when `auto_ptr` itself is destroyed. It may be used to provide exception safety for dynamically allocated objects, for passing ownership of dynamically allocated objects into functions and for returning dynamically allocated objects from functions.
Copying an `auto_ptr` copies the pointer and transfers ownership to the destination: both copy construction and copy assignment of `auto_ptr` modify their right-hand arguments, and the "copy" is not equal to the original. Because of these unusual copy semantics, `auto_ptr` may not be placed in standard containers. `[std::unique\_ptr](unique_ptr "cpp/memory/unique ptr")` is preferred for this and other uses. (since C++11).
2) Specialization for type `void` is provided, it declares the typedef `element_type`, but no member functions. An additional class template `auto_ptr_ref` is referred to throughout the documentation. It is an implementation-defined type that holds a reference to `auto_ptr`. The implementation is allowed to provide the template with a different name or implement the functions returning it or accepting it as parameter in other ways.
### Member types
| Member type | Definition |
| --- | --- |
| `element_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](auto_ptr/auto_ptr "cpp/memory/auto ptr/auto ptr") | creates a new `auto_ptr` (public member function) |
| [(destructor)](auto_ptr/~auto_ptr "cpp/memory/auto ptr/~auto ptr") | destroys an `auto_ptr` and the managed object (public member function) |
| [operator=](auto_ptr/operator= "cpp/memory/auto ptr/operator=") | transfers ownership from another `auto_ptr` (public member function) |
| [operator auto\_ptr<Y>operator auto\_ptr\_ref<Y>](auto_ptr/operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr") | converts the managed pointer to a pointer to different type (public member function) |
| Observers |
| [get](auto_ptr/get "cpp/memory/auto ptr/get") | returns a pointer to the managed object (public member function) |
| [operator\*operator->](auto_ptr/operator* "cpp/memory/auto ptr/operator*") | accesses the managed object (public member function) |
| Modifiers |
| [reset](auto_ptr/reset "cpp/memory/auto ptr/reset") | replaces the managed object (public member function) |
| [release](auto_ptr/release "cpp/memory/auto ptr/release") | releases ownership of the managed object (public member function) |
cpp std::inout_ptr_t std::inout\_ptr\_t
==================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Smart, class Pointer, class... Args >
class inout_ptr_t;
```
| | (since C++23) |
`inout_ptr_t` is used to adapt types such as smart pointers for foreign functions that reset ownership via a `Pointer*` (usually `T**` for some object type `T`) or `void**` parameter.
`inout_ptr_t` captures additional arguments on construction, provides a storage for the result which such an aforementioned foreign function accesses, releases the ownership held by the adapted `Smart` object, and finally resets the adapted `Smart` object with the result and the captured arguments when it is destroyed.
`inout_ptr_t` behaves as if it holds following non-static data members:
* a `Smart&` reference, which is bound to the adapted object on construction,
* for every `T` in `Args...`, a member of type `T`, which is an argument captured on construction and used for resetting while destruction, and
* a member subobject that suitable for storing a `Pointer` within it and providing a `void*` object, where the `Pointer` or `void*` object is generally exposed to a foreign function for ownership resetting.
If `Smart` is not a pointer type, `release()` is called at most once on the adapted object. Implementations may call `release()` within constructor, or before resetting within destructor if the `Pointer` value is not null.
Users can control whether each argument for resetting is captured by copy or by reference, by specifying an object type or a reference type in `Args...` respectively.
### Template parameters
| | | |
| --- | --- | --- |
| Smart | - | the type of the object (typically a smart pointer) to adapt |
| Pointer | - | type of the object (typically a raw pointer) to which a foreign function accesses for ownership resetting |
| Args... | - | type of captured arguments used for resetting the adapted object |
| Type requirements |
| -`Pointer` must meet the requirements of [NullablePointer](../named_req/nullablepointer "cpp/named req/NullablePointer"). |
| -The program is ill-formed if `Smart` is a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` specialization. |
### Specializations
Unlike most class templates in the standard library, program-defined specializations of `inout_ptr_t` that depend on at least one program-defined type need not meet the requirements for the primary template.
This license allows a program-defined specialization to expose the raw pointer stored within a non-standard smart pointer to foreign functions.
### Member functions
| | |
| --- | --- |
| [(constructor)](inout_ptr_t/inout_ptr_t "cpp/memory/inout ptr t/inout ptr t")
(C++23) | constructs an `inout_ptr_t` (public member function) |
| operator=
[deleted](C++23) | `inout_ptr_t` is not assignable (public member function) |
| [(destructor)](inout_ptr_t/~inout_ptr_t "cpp/memory/inout ptr t/~inout ptr t")
(C++23) | resets the adapted smart pointer after releasing its ownership (public member function) |
| [operator Pointer\*operator void\*\*](inout_ptr_t/operator_ptr "cpp/memory/inout ptr t/operator ptr")
(C++23) | converts the `inout_ptr_t` to the address of the storage for output (public member function) |
### Non-member functions
| | |
| --- | --- |
| [inout\_ptr](inout_ptr_t/inout_ptr "cpp/memory/inout ptr t/inout ptr")
(C++23) | creates an `inout_ptr_t` with an associated smart pointer and resetting arguments (function template) |
### Notes
`inout_ptr_t` expects that the foreign functions release the ownership represented by the value of the pointed-to `Pointer`, and then re-initialize it. As such operation requires unique ownership, the usage with `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` is forbidden.
The typical usage of `inout_ptr_t` is creating its temporary objects by `std::inout_ptr`, which resets the adapted smart pointer immediately. E.g. given a setter function and a smart pointer of appropriate type declared with `int foreign_resetter(T**);` and `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<T, D> up;` respectively,
```
if (int ec = foreign_resetter(std::inout_ptr(up)) {
return ec;
}
```
is roughly equivalent to.
```
T *raw_p = up.get();
up.release();
int ec = foreign_resetter(&raw_p);
up.reset(raw_p);
if (ec != 0) {
return ec;
}
```
It is not recommended to create an `inout_ptr_t` object of a [storage duration](../language/storage_duration "cpp/language/storage duration") other than automatic storage duration, because such code is likely to produce dangling references and result in undefined behavior on destruction.
Captured arguments are typically packed into a `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Args...>`. Implementations may use different mechanism to provide the `Pointer` or `void*` object they need hold.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_out_ptr`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [out\_ptr\_t](out_ptr_t "cpp/memory/out ptr t")
(C++23) | interoperates with foreign pointer setters and resets a smart pointer on destruction (class template) |
| [unique\_ptr](unique_ptr "cpp/memory/unique ptr")
(C++11) | smart pointer with unique object ownership semantics (class template) |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::pmr::polymorphic_allocator std::pmr::polymorphic\_allocator
================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
template< class T >
class polymorphic_allocator;
```
| | (since C++17) (until C++20) |
|
```
template< class T = std::byte >
class polymorphic_allocator;
```
| | (since C++20) |
The class template `std::pmr::polymorphic_allocator` is an [Allocator](../named_req/allocator "cpp/named req/Allocator") which exhibits different allocation behavior depending upon the `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` from which it is constructed. Since `memory_resource` uses runtime polymorphism to manage allocations, different container instances with `polymorphic_allocator` as their static allocator type are interoperable, but can behave as if they had different allocator types.
All specializations of `polymorphic_allocator` meet the [Allocator completeness requirements](../named_req/allocator#Allocator_completeness_requirements "cpp/named req/Allocator").
The `polymorphic_allocator::construct` member function does [uses-allocator construction](uses_allocator#Uses-allocator_construction "cpp/memory/uses allocator"), so that the elements of a container using a `polymorphic_allocator` will use that same allocator for their own allocations. For example, a `[std::pmr::vector](http://en.cppreference.com/w/cpp/container/vector)<[std::pmr::string](http://en.cppreference.com/w/cpp/string/basic_string)>` will use the same `memory_resource` for the `vector`'s storage and each `string`'s storage.
### Member types
| Member type | definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](polymorphic_allocator/polymorphic_allocator "cpp/memory/polymorphic allocator/polymorphic allocator") | Constructs a `polymorphic_allocator` (public member function) |
| (destructor)
(implicitly declared) | Implicitly declared destructor (public member function) |
| operator=
[deleted] | Copy assignment operator is deleted (public member function) |
| Public member functions |
| [allocate](polymorphic_allocator/allocate "cpp/memory/polymorphic allocator/allocate") | Allocate memory (public member function) |
| [deallocate](polymorphic_allocator/deallocate "cpp/memory/polymorphic allocator/deallocate") | Deallocate memory (public member function) |
| [construct](polymorphic_allocator/construct "cpp/memory/polymorphic allocator/construct") | Constructs an object in allocated storage (public member function) |
| [destroy](polymorphic_allocator/destroy "cpp/memory/polymorphic allocator/destroy")
(deprecated in C++20) | Destroys an object in allocated storage (public member function) |
| [allocate\_bytes](polymorphic_allocator/allocate_bytes "cpp/memory/polymorphic allocator/allocate bytes")
(C++20) | Allocate raw aligned memory from the underlying resource (public member function) |
| [deallocate\_bytes](polymorphic_allocator/deallocate_bytes "cpp/memory/polymorphic allocator/deallocate bytes")
(C++20) | Free raw memory obtained from allocate\_bytes (public member function) |
| [allocate\_object](polymorphic_allocator/allocate_object "cpp/memory/polymorphic allocator/allocate object")
(C++20) | Allocates raw memory suitable for an object or an array (public member function) |
| [deallocate\_object](polymorphic_allocator/deallocate_object "cpp/memory/polymorphic allocator/deallocate object")
(C++20) | Frees raw memory obtained by allocate\_object (public member function) |
| [new\_object](polymorphic_allocator/new_object "cpp/memory/polymorphic allocator/new object")
(C++20) | Allocates and constructs an object (public member function) |
| [delete\_object](polymorphic_allocator/delete_object "cpp/memory/polymorphic allocator/delete object")
(C++20) | Destroys and deallocates an object (public member function) |
| [select\_on\_container\_copy\_construction](polymorphic_allocator/select_on_container_copy_construction "cpp/memory/polymorphic allocator/select on container copy construction") | Create a new `polymorphic_allocator` for use by a container's copy constructor (public member function) |
| [resource](polymorphic_allocator/resource "cpp/memory/polymorphic allocator/resource") | Returns a pointer to the underlying memory resource (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](polymorphic_allocator/operator_eq "cpp/memory/polymorphic allocator/operator eq")
(removed in C++20) | compare two `polymorphic_allocator`s (function) |
### Notes
`polymorphic_allocator` does not propagate on container copy assignment, move assignment, or swap. As a result, move assignment of a `polymorphic_allocator`-using container can throw, and swapping two `polymorphic_allocator`-using containers whose allocators do not compare equal results in undefined behavior.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_polymorphic_allocator`](../feature_test#Library_features "cpp/feature test") |
### See also
| | |
| --- | --- |
| [memory\_resource](memory_resource "cpp/memory/memory resource")
(C++17) | an abstract interface for classes that encapsulate memory resources (class) |
| programming_docs |
cpp std::pointer_traits std::pointer\_traits
====================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Ptr > struct pointer_traits;
```
| (1) | (since C++11) |
|
```
template< class T > struct pointer_traits<T*>;
```
| (2) | (since C++11) |
The `pointer_traits` class template provides the standardized way to access certain properties of pointer-like types ([fancy pointers](../named_req/allocator#Fancy_pointers "cpp/named req/Allocator"), such as [`boost::interprocess::offset_ptr`](http://www.boost.org/doc/libs/release/doc/html/interprocess/offset_ptr.html)). The standard template `[std::allocator\_traits](allocator_traits "cpp/memory/allocator traits")` relies on `pointer_traits` to determine the defaults for various typedefs required by [Allocator](../named_req/allocator "cpp/named req/Allocator").
1) The non-specialized `pointer_traits` declares the following types: ### Member types
| Type | Definition |
| --- | --- |
| `pointer` | `Ptr` |
| `element_type` | `Ptr::element_type` if present. Otherwise `T` if `Ptr` is a template specialization `Template<T, Args...>`. Otherwise, the `pointer_traits` specialization is ill-formed |
| `difference_type` | `Ptr::difference_type` if present, otherwise `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
### Member alias templates
| Template | Definition |
| --- | --- |
| `template <class U> using rebind` | `Ptr::rebind<U>` if exists, otherwise `Template<U, Args...>` if `Ptr` is a template specialization `Template<T, Args...>` |
### Member functions
| | |
| --- | --- |
| [pointer\_to](pointer_traits/pointer_to "cpp/memory/pointer traits/pointer to")
[static] | obtains a dereferenceable pointer to its argument (public static member function) |
| Optional member functions of program-defined specializations |
| [to\_address](pointer_traits/to_address "cpp/memory/pointer traits/to address")
[static] (C++20)(optional) | obtains a raw pointer from a fancy pointer (inverse of `pointer_to`) (public static member function) |
2) A specialization is provided for pointer types, `T*`, which declares the following types: ### Member types
| Type | Definition |
| --- | --- |
| `pointer` | `T*` |
| `element_type` | `T` |
| `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
### Member alias templates
| Template | Definition |
| --- | --- |
| `template< class U > using rebind` | `U*` |
### Member functions
| | |
| --- | --- |
| [pointer\_to](pointer_traits/pointer_to "cpp/memory/pointer traits/pointer to")
[static] | obtains a dereferenceable pointer to its argument (public static member function) |
### Notes
The rebind member template alias makes it possible, given a pointer-like type that points to `T`, to obtain the same pointer-like type that points to `U`. For example,
```
using another_pointer = std::pointer_traits<std::shared_ptr<int>>::rebind<double>;
static_assert(std::is_same<another_pointer, std::shared_ptr<double>>::value);
```
| | |
| --- | --- |
| A specialization for user-defined fancy pointer types may provide an additional static member function `to_address` to customize the behavior of `std::to_address`. | (since C++20) |
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_constexpr_memory`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <memory>
#include <iostream>
template <class Ptr>
struct BlockList
{
// Predefine a memory block
struct block;
// Define a pointer to a memory block from the kind of pointer Ptr s
// If Ptr is any kind of T*, block_ptr_t is block*
// If Ptr is smart_ptr<T>, block_ptr_t is smart_ptr<block>
using block_ptr_t = typename std::pointer_traits<Ptr>::template rebind<block>;
struct block
{
std::size_t size{};
block_ptr_t next_block{};
};
block_ptr_t free_blocks;
};
int main()
{
[[maybe_unused]]
BlockList<int*> bl1;
// The type of bl1.free_blocks is BlockList<int*>:: block*
BlockList<std::shared_ptr<char>> bl2;
// The type of bl2.free_blocks is
// std::shared_ptr< BlockList<std::shared_ptr<char> >::block>
std::cout << bl2.free_blocks.use_count() << '\n';
}
```
Output:
```
0
```
### See also
| | |
| --- | --- |
| [allocator\_traits](allocator_traits "cpp/memory/allocator traits")
(C++11) | provides information about allocator types (class template) |
| [addressof](addressof "cpp/memory/addressof")
(C++11) | obtains actual address of an object, even if the *&* operator is overloaded (function template) |
cpp std::enable_shared_from_this std::enable\_shared\_from\_this
===============================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T > class enable_shared_from_this;
```
| | (since C++11) |
`std::enable_shared_from_this` allows an object `t` that is currently managed by a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` named `pt` to safely generate additional `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` instances `pt1, pt2, ...` that all share ownership of `t` with `pt`.
Publicly inheriting from `std::enable_shared_from_this<T>` provides the type `T` with a member function `shared_from_this`. If an object `t` of type `T` is managed by a `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` named `pt`, then calling `T::shared_from_this` will return a new `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` that shares ownership of `t` with `pt`.
### Member functions
| | |
| --- | --- |
| [(constructor)](enable_shared_from_this/enable_shared_from_this "cpp/memory/enable shared from this/enable shared from this") | constructs an `enable_shared_from_this` object (protected member function) |
| [(destructor)](enable_shared_from_this/~enable_shared_from_this "cpp/memory/enable shared from this/~enable shared from this") | destroys an `enable_shared_from_this` object (protected member function) |
| [operator=](enable_shared_from_this/operator= "cpp/memory/enable shared from this/operator=") | returns a reference to `this` (protected member function) |
| [shared\_from\_this](enable_shared_from_this/shared_from_this "cpp/memory/enable shared from this/shared from this") | returns a `shared_ptr` which shares ownership of `*this` (public member function) |
| [weak\_from\_this](enable_shared_from_this/weak_from_this "cpp/memory/enable shared from this/weak from this")
(C++17) | returns the `weak_ptr` which shares ownership of `*this` (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `weak_this` (private)(C++17) | `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` object tracking the control block of the first shared owner of `*this`. Exposition only |
### Notes
A common implementation for `enable_shared_from_this` is to hold a weak reference (such as `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")`) to `this`. The constructors of `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` detect the presence of an unambiguous and accessible (ie. public inheritance is mandatory) (since C++17) `enable_shared_from_this` base and assign the newly created `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` to the internally stored weak reference if not already owned by a live `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` (since C++17). Constructing a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` for an object that is already managed by another `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` will not consult the internally stored weak reference and thus will lead to undefined behavior.
It is permitted to call `shared_from_this` only on a previously shared object, i.e. on an object managed by `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>`. Otherwise the behavior is undefined (until C++17)`[std::bad\_weak\_ptr](bad_weak_ptr "cpp/memory/bad weak ptr")` is thrown (by the shared\_ptr constructor from a default-constructed `weak_this`) (since C++17).
`enable_shared_from_this` provides the safe alternative to an expression like `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(this)`, which is likely to result in `this` being destructed more than once by multiple owners that are unaware of each other (see example below).
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_enable_shared_from_this`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <memory>
#include <iostream>
struct Good : std::enable_shared_from_this<Good> // note: public inheritance
{
std::shared_ptr<Good> getptr() {
return shared_from_this();
}
};
struct Best : std::enable_shared_from_this<Best> // note: public inheritance
{
std::shared_ptr<Best> getptr() {
return shared_from_this();
}
// No public constructor, only a factory function,
// so there's no way to have getptr return nullptr.
[[nodiscard]] static std::shared_ptr<Best> create() {
// Not using std::make_shared<Best> because the c'tor is private.
return std::shared_ptr<Best>(new Best());
}
private:
Best() = default;
};
struct Bad
{
std::shared_ptr<Bad> getptr() {
return std::shared_ptr<Bad>(this);
}
~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
void testGood()
{
// Good: the two shared_ptr's share the same object
std::shared_ptr<Good> good0 = std::make_shared<Good>();
std::shared_ptr<Good> good1 = good0->getptr();
std::cout << "good1.use_count() = " << good1.use_count() << '\n';
}
void misuseGood()
{
// Bad: shared_from_this is called without having std::shared_ptr owning the caller
try {
Good not_so_good;
std::shared_ptr<Good> gp1 = not_so_good.getptr();
} catch(std::bad_weak_ptr& e) {
// undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
std::cout << e.what() << '\n';
}
}
void testBest()
{
// Best: Same but can't stack-allocate it:
std::shared_ptr<Best> best0 = Best::create();
std::shared_ptr<Best> best1 = best0->getptr();
std::cout << "best1.use_count() = " << best1.use_count() << '\n';
// Best stackBest; // <- Will not compile because Best::Best() is private.
}
void testBad()
{
// Bad, each shared_ptr thinks it's the only owner of the object
std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
std::shared_ptr<Bad> bad1 = bad0->getptr();
std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
} // UB: double-delete of Bad
int main()
{
testGood();
misuseGood();
testBest();
testBad();
}
```
Possible output:
```
good1.use_count() = 2
bad_weak_ptr
best1.use_count() = 2
bad1.use_count() = 1
Bad::~Bad() called
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption
```
### See also
| | |
| --- | --- |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::weak_ptr std::weak\_ptr
==============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T > class weak_ptr;
```
| | (since C++11) |
`std::weak_ptr` is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")`. It must be converted to `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` in order to access the referenced object.
`std::weak_ptr` models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, `std::weak_ptr` is used to track the object, and it is converted to `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` to assume temporary ownership. If the original `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` is destroyed at this time, the object's lifetime is extended until the temporary `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` is destroyed as well.
Another use for `std::weak_ptr` is to break reference cycles formed by objects managed by `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")`. If such cycle is orphaned (i.e., there are no outside shared pointers into the cycle), the `shared_ptr` reference counts cannot reach zero and the memory is leaked. To prevent this, one of the pointers in the cycle [can be made weak](weak_ptr/~weak_ptr#Example "cpp/memory/weak ptr/~weak ptr").
### Member types
| Member type | Definition |
| --- | --- |
| `element_type` |
| | |
| --- | --- |
| `T`. | (until C++17) |
| `[std::remove\_extent\_t](http://en.cppreference.com/w/cpp/types/remove_extent)<T>` | (since C++17) |
|
### Member functions
| | |
| --- | --- |
| [(constructor)](weak_ptr/weak_ptr "cpp/memory/weak ptr/weak ptr") | creates a new `weak_ptr` (public member function) |
| [(destructor)](weak_ptr/~weak_ptr "cpp/memory/weak ptr/~weak ptr") | destroys a `weak_ptr` (public member function) |
| [operator=](weak_ptr/operator= "cpp/memory/weak ptr/operator=") | assigns the `weak_ptr` (public member function) |
| Modifiers |
| [reset](weak_ptr/reset "cpp/memory/weak ptr/reset") | releases the ownership of the managed object (public member function) |
| [swap](weak_ptr/swap "cpp/memory/weak ptr/swap") | swaps the managed objects (public member function) |
| Observers |
| [use\_count](weak_ptr/use_count "cpp/memory/weak ptr/use count") | returns the number of `shared_ptr` objects that manage the object (public member function) |
| [expired](weak_ptr/expired "cpp/memory/weak ptr/expired") | checks whether the referenced object was already deleted (public member function) |
| [lock](weak_ptr/lock "cpp/memory/weak ptr/lock") | creates a `shared_ptr` that manages the referenced object (public member function) |
| [owner\_before](weak_ptr/owner_before "cpp/memory/weak ptr/owner before") | provides owner-based ordering of weak pointers (public member function) |
### Non-member functions
| | |
| --- | --- |
| [std::swap(std::weak\_ptr)](weak_ptr/swap2 "cpp/memory/weak ptr/swap2")
(C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
### Helper classes
| | |
| --- | --- |
| [std::atomic<std::weak\_ptr>](weak_ptr/atomic2 "cpp/memory/weak ptr/atomic2")
(C++20) | atomic weak pointer (class template specialization) |
### [Deduction guides](weak_ptr/deduction_guides "cpp/memory/weak ptr/deduction guides") (since C++17)
### Notes
Like `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")`, a typical implementation of `weak_ptr` stores two pointers:
* a pointer to the control block; and
* the stored pointer of the `shared_ptr` it was constructed from.
A separate stored pointer is necessary to ensure that converting a `shared_ptr` to `weak_ptr` and then back works correctly, even for aliased `shared_ptr`s. It is not possible to access the stored pointer in a `weak_ptr` without locking it into a `shared_ptr`.
### Example
Demonstrates how lock is used to ensure validity of the pointer.
```
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void observe()
{
std::cout << "gw.use_count() == " << gw.use_count() << "; ";
// we have to make a copy of shared pointer before usage:
if (std::shared_ptr<int> spt = gw.lock()) {
std::cout << "*spt == " << *spt << '\n';
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
observe();
}
observe();
}
```
Output:
```
gw.use_count() == 1; *spt == 42
gw.use_count() == 0; gw is expired
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3001](https://cplusplus.github.io/LWG/issue3001) | C++17 | `element_type` was not updated for array support | updated |
### See also
| | |
| --- | --- |
| [unique\_ptr](unique_ptr "cpp/memory/unique ptr")
(C++11) | smart pointer with unique object ownership semantics (class template) |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::allocation_result std::allocation\_result
=======================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Pointer >
struct allocation_result {
Pointer ptr;
std::size_t count;
};
```
| | (since C++23) |
`allocation_result` specializations are return types of the `allocate_at_least` member function of appropriate [Allocator](../named_req/allocator "cpp/named req/Allocator") types (e.g. [`std::allocator::allocate_at_least`](allocator/allocate_at_least "cpp/memory/allocator/allocate at least")) and [`std::allocate_at_least`](allocate_at_least "cpp/memory/allocate at least").
Every specialization of `allocation_result` has no base classes or declared members other than `ptr` and `count`, thus it is suitable for [aggregate initialization](../language/aggregate_initialization "cpp/language/aggregate initialization") and [structured binding](../language/structured_binding "cpp/language/structured binding").
### Template parameters
| | | |
| --- | --- | --- |
| Pointer | - | typically `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Alloc>::pointer`, where `Alloc` is an [Allocator](../named_req/allocator "cpp/named req/Allocator") type |
### Member objects
| | |
| --- | --- |
| ptr
(C++23) | typically used for the address of the first element in the storage allocated by `allocate_at_least` (public member object) |
| count
(C++23) | typically used for the actual number of elements in the storage allocated by `allocate_at_least` (public member object) |
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_allocate_at_least`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [allocate\_at\_least](allocator/allocate_at_least "cpp/memory/allocator/allocate at least")
(C++23) | allocates uninitialized storage at least as large as requested size (public member function of `std::allocator<T>`) |
| [allocate\_at\_least](allocate_at_least "cpp/memory/allocate at least")
(C++23) | allocates storage at least as large as the requested size via an allocator (function template) |
cpp std::addressof std::addressof
==============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
T* addressof( T& arg ) noexcept;
```
| (since C++11) (until C++17) |
|
```
template< class T >
constexpr T* addressof( T& arg ) noexcept;
```
| (since C++17) |
|
```
template <class T>
const T* addressof( const T&& ) = delete;
```
| (2) | (since C++17) |
1) Obtains the actual address of the object or function `arg`, even in presence of overloaded `operator&`.
2) Rvalue overload is deleted to prevent taking the address of `const` rvalues.
| | |
| --- | --- |
| The expression `std::addressof(E)` is a [constant subexpression](../language/constant_expression "cpp/language/constant expression"), if `E` is an lvalue constant subexpression. | (since C++17) |
### Parameters
| | | |
| --- | --- | --- |
| arg | - | lvalue object or function |
### Return value
Pointer to `arg`.
### Possible implementation
The implementation below is not `constexpr` (which requires compiler support).
| |
| --- |
|
```
template<class T>
typename std::enable_if<std::is_object<T>::value, T*>::type addressof(T& arg) noexcept
{
return reinterpret_cast<T*>(
&const_cast<char&>(
reinterpret_cast<const volatile char&>(arg)));
}
template<class T>
typename std::enable_if<!std::is_object<T>::value, T*>::type addressof(T& arg) noexcept
{
return &arg;
}
```
|
Correct implementation of this function requires compiler support: [GNU libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/include/bits/move.h#L47-L50), [LLVM libc++](https://github.com/llvm/llvm-project/blob/main/libcxx/include/__memory/addressof.h#L21-L28), [Microsoft STL](https://github.com/microsoft/STL/blob/main/stl/inc/xstddef#L251-L254).
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_addressof_constexpr`](../feature_test#Library_features "cpp/feature test") |
### Example
`operator&` may be overloaded for a pointer wrapper class to obtain a pointer to pointer:
```
#include <iostream>
#include <memory>
template<class T>
struct Ptr {
T* pad; // add pad to show difference between 'this' and 'data'
T* data;
Ptr(T* arg) : pad(nullptr), data(arg)
{
std::cout << "Ctor this = " << this << std::endl;
}
~Ptr() { delete data; }
T** operator&() { return &data; }
};
template<class T>
void f(Ptr<T>* p)
{
std::cout << "Ptr overload called with p = " << p << '\n';
}
void f(int** p)
{
std::cout << "int** overload called with p = " << p << '\n';
}
int main()
{
Ptr<int> p(new int(42));
f(&p); // calls int** overload
f(std::addressof(p)); // calls Ptr<int>* overload, (= this)
}
```
Possible output:
```
Ctor this = 0x7fff59ae6e88
int** overload called with p = 0x7fff59ae6e90
Ptr overload called with p = 0x7fff59ae6e88
```
### See also
| | |
| --- | --- |
| [allocator](allocator "cpp/memory/allocator") | the default allocator (class template) |
| [pointer\_to](pointer_traits/pointer_to "cpp/memory/pointer traits/pointer to")
[static] | obtains a dereferenceable pointer to its argument (public static member function of `std::pointer_traits<Ptr>`) |
| programming_docs |
cpp std::pmr::null_memory_resource std::pmr::null\_memory\_resource
================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* null_memory_resource() noexcept;
```
| | (since C++17) |
Returns a pointer to a `memory_resource` that doesn't perform any allocation.
### Return value
Returns a pointer `p` to a static storage duration object of a type derived from `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")`, with the following properties:
* its `allocate()` function always throws `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")`;
* its `deallocate()` function has no effect;
* for any `memory_resource` `r`, `p->is_equal(r)` returns `&r == p`.
The same value is returned every time this function is called.
### Example
The program demos the main usage of `null_memory_resouce`: ensure that a memory pool which requires memory allocated on the stack will NOT allocate memory on the heap if it needs more memory.
```
#include <array>
#include <cstddef>
#include <iostream>
#include <memory_resource>
#include <string>
#include <unordered_map>
int main()
{
// allocate memory on the stack
std::array<std::byte, 20000> buf;
// without fallback memory allocation on heap
std::pmr::monotonic_buffer_resource pool{ buf.data(), buf.size(),
std::pmr::null_memory_resource() };
// allocate too much memory
std::pmr::unordered_map<long, std::pmr::string> coll{ &pool };
try
{
for (std::size_t i = 0; i < buf.size(); ++i)
{
coll.emplace(i, "just a string with number " + std::to_string(i));
if (i && i % 50 == 0)
std::clog << "size: " << i << "...\n";
}
}
catch(const std::bad_alloc& e)
{
std::cerr << e.what() << '\n';
}
std::cout << "size: " << coll.size() << '\n';
}
```
Possible output:
```
size: 50...
size: 100...
size: 150...
std::bad_alloc
size: 183
```
cpp std::construct_at std::construct\_at
==================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template<class T, class... Args>
constexpr T* construct_at( T* p, Args&&... args );
```
| | (since C++20) |
Creates a `T` object initialized with arguments `args...` at given address `p`. Specialization of this function template participates in overload resolution only if `::new([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<void\*>()) T([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...)` is well-formed in an unevaluated context.
Equivalent to.
```
return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
T(std::forward<Args>(args)...);
```
except that `construct_at` may be used in evaluation of [constant expressions](../language/constant_expression "cpp/language/constant expression").
When `construct_at` is called in the evaluation of some constant expression `e`, the argument `p` must point to either storage obtained by `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>::allocate` or an object whose lifetime began within the evaluation of `e`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the uninitialized storage on which a `T` object will be constructed |
| args... | - | arguments used for initialization |
### Return value
`p`.
### Example
```
#include <iostream>
#include <memory>
struct S {
int x;
float y;
double z;
S(int x, float y, double z) : x{x}, y{y}, z{z} { std::cout << "S::S();\n"; }
~S() { std::cout << "S::~S();\n"; }
void print() const {
std::cout << "S { x=" << x << "; y=" << y << "; z=" << z << "; };\n";
}
};
int main()
{
alignas(S) unsigned char storage[sizeof(S)];
S* ptr = std::construct_at(reinterpret_cast<S*>(storage), 42, 2.71828f, 3.1415);
ptr->print();
std::destroy_at(ptr);
}
```
Output:
```
S::S();
S { x=42; y=2.71828; z=3.1415; };
S::~S();
```
### See also
| | |
| --- | --- |
| [allocate](allocator/allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function of `std::allocator<T>`) |
| [construct](allocator_traits/construct "cpp/memory/allocator traits/construct")
[static] | constructs an object in the allocated storage (function template) |
| [destroy\_at](destroy_at "cpp/memory/destroy at")
(C++17) | destroys an object at a given address (function template) |
| [ranges::construct\_at](ranges/construct_at "cpp/memory/ranges/construct at")
(C++20) | creates an object at a given address (niebloid) |
cpp std::uninitialized_value_construct std::uninitialized\_value\_construct
====================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class ForwardIt >
void uninitialized_value_construct( ForwardIt first, ForwardIt last);
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt >
void uninitialized_value_construct( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last );
```
| (2) | (since C++17) |
1) Constructs objects of type `typename iterator_traits<ForwardIt>::value_type` in the uninitialized storage designated by the range `[first, last)` by [value-initialization](../language/value_initialization "cpp/language/value initialization"), as if by
```
for (; first != last; ++first)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type();
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of the elements to initialize |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
(none).
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class ForwardIt>
void uninitialized_value_construct(ForwardIt first, ForwardIt last)
{
using Value = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; current != last; ++current) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) Value();
}
} catch (...) {
std::destroy(first, current);
throw;
}
}
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "Default value" }; };
constexpr int n {3};
alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(mem)};
auto last {first + n};
std::uninitialized_value_construct(first, last);
for (auto it {first}; it != last; ++it) {
std::cout << it->m << '\n';
}
std::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_value_construct
// zero-fills the given uninitialized memory area.
int v[] { 1, 2, 3, 4 };
for (const int i : v) { std::cout << i << ' '; }
std::cout << '\n';
std::uninitialized_value_construct(std::begin(v), std::end(v));
for (const int i : v) { std::cout << i << ' '; }
std::cout << '\n';
}
```
Output:
```
Default value
Default value
Default value
1 2 3 4
0 0 0 0
```
### See also
| | |
| --- | --- |
| [uninitialized\_value\_construct\_n](uninitialized_value_construct_n "cpp/memory/uninitialized value construct n")
(C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
| [uninitialized\_default\_construct](uninitialized_default_construct "cpp/memory/uninitialized default construct")
(C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (function template) |
| [ranges::uninitialized\_value\_construct](ranges/uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct")
(C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) |
cpp std::pmr::unsynchronized_pool_resource std::pmr::unsynchronized\_pool\_resource
========================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
class unsynchronized_pool_resource : public std::pmr::memory_resource;
```
| | (since C++17) |
The class `std::pmr::unsynchronized_pool_resource` is a general-purpose memory resource class with the following properties:
* It owns the allocated memory and frees it on destruction, even if `deallocate` has not been called for some of the allocated blocks.
* It consists of a collection of *pools* that serves requests for different block sizes. Each pool manages a collection of *chunks* that are then divided into blocks of uniform size.
* Calls to [`do_allocate`](unsynchronized_pool_resource/do_allocate "cpp/memory/unsynchronized pool resource/do allocate") are dispatched to the pool serving the smallest blocks accommodating the requested size.
* Exhausting memory in the pool causes the next allocation request for that pool to allocate an additional chunk of memory from the *upstream allocator* to replenish the pool. The chunk size obtained increases geometrically.
* Allocations requests that exceed the largest block size are served from the *upstream allocator* directly.
* The largest block size and maximum chunk size may be tuned by passing a `[std::pmr::pool\_options](pool_options "cpp/memory/pool options")` struct to its constructor.
`unsynchronized_pool_resource` is not thread-safe, and cannot be accessed from multiple threads simultaneously; use [`synchronized_pool_resource`](synchronized_pool_resource "cpp/memory/synchronized pool resource") if access from multiple threads is required.
### Member functions
| | |
| --- | --- |
| [(constructor)](unsynchronized_pool_resource/unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource/unsynchronized pool resource") | Constructs a `unsynchronized_pool_resource` (public member function) |
| [(destructor)](unsynchronized_pool_resource/~unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource/~unsynchronized pool resource")
[virtual] | Destroys a `unsynchronized_pool_resource`, releasing all allocated memory (virtual public member function) |
| operator=
[deleted] | Copy assignment operator is deleted. `unsynchronized_pool_resource` is not copy assignable (public member function) |
| Public member functions |
| [release](unsynchronized_pool_resource/release "cpp/memory/unsynchronized pool resource/release") | Release all allocated memory (public member function) |
| [upstream\_resource](unsynchronized_pool_resource/upstream_resource "cpp/memory/unsynchronized pool resource/upstream resource") | Returns a pointer to the upstream memory resource (public member function) |
| [options](unsynchronized_pool_resource/options "cpp/memory/unsynchronized pool resource/options") | Returns the options that control the pooling behavior of this resource (public member function) |
| Protected member functions |
| [do\_allocate](unsynchronized_pool_resource/do_allocate "cpp/memory/unsynchronized pool resource/do allocate")
[virtual] | Allocate memory (virtual protected member function) |
| [do\_deallocate](unsynchronized_pool_resource/do_deallocate "cpp/memory/unsynchronized pool resource/do deallocate")
[virtual] | Return memory to the pool (virtual protected member function) |
| [do\_is\_equal](unsynchronized_pool_resource/do_is_equal "cpp/memory/unsynchronized pool resource/do is equal")
[virtual] | Compare for equality with another `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` (virtual protected member function) |
cpp std::pmr::monotonic_buffer_resource std::pmr::monotonic\_buffer\_resource
=====================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
class monotonic_buffer_resource : public std::pmr::memory_resource;
```
| | (since C++17) |
The class `std::pmr::monotonic_buffer_resource` is a special-purpose memory resource class that releases the allocated memory only when the resource is destroyed. It is intended for very fast memory allocations in situations where memory is used to build up a few objects and then is released all at once.
`monotonic_buffer_resource` can be constructed with an initial buffer. If there is no initial buffer, or if the buffer is exhausted, additional buffers are obtained from an *upstream memory resource* supplied at construction. The size of buffers obtained follows a geometric progression.
`monotonic_buffer_resource` is not thread-safe.
### Member functions
| | |
| --- | --- |
| [(constructor)](monotonic_buffer_resource/monotonic_buffer_resource "cpp/memory/monotonic buffer resource/monotonic buffer resource") | Constructs a `monotonic_buffer_resource` (public member function) |
| [(destructor)](monotonic_buffer_resource/~monotonic_buffer_resource "cpp/memory/monotonic buffer resource/~monotonic buffer resource")
[virtual] | Destroys a `monotonic_buffer_resource`, releasing all allocated memory (virtual public member function) |
| operator=
[deleted] | Copy assignment operator is deleted. `monotonic_buffer_resource` is not copy assignable (public member function) |
| Public member functions |
| [release](monotonic_buffer_resource/release "cpp/memory/monotonic buffer resource/release") | Release all allocated memory (public member function) |
| [upstream\_resource](monotonic_buffer_resource/upstream_resource "cpp/memory/monotonic buffer resource/upstream resource") | Returns a pointer to the upstream memory resource (public member function) |
| Protected member functions |
| [do\_allocate](monotonic_buffer_resource/do_allocate "cpp/memory/monotonic buffer resource/do allocate")
[virtual] | Allocate memory (virtual protected member function) |
| [do\_deallocate](monotonic_buffer_resource/do_deallocate "cpp/memory/monotonic buffer resource/do deallocate")
[virtual] | No-op (virtual protected member function) |
| [do\_is\_equal](monotonic_buffer_resource/do_is_equal "cpp/memory/monotonic buffer resource/do is equal")
[virtual] | Compare for equality with another `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` (virtual protected member function) |
### Example
The program measures the time of creating huge double-linked lists using the following allocators:
* default standard allocator,
* default `pmr` allocator,
* `pmr` allocator with monotonic resource but without explicit memory buffer,
* `pmr` allocator with monotonic resource and external memory buffer (on stack).
```
#include <list>
#include <array>
#include <chrono>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <memory_resource>
template <typename Func>
auto benchmark(Func test_func, int iterations) {
const auto start = std::chrono::system_clock::now();
while (iterations-- > 0) { test_func(); }
const auto stop = std::chrono::system_clock::now();
const auto secs = std::chrono::duration<double>(stop - start);
return secs.count();
}
int main()
{
constexpr int iterations{100};
constexpr int total_nodes{2'00'000};
auto default_std_alloc = [total_nodes] {
std::list<int> list;
for (int i{}; i != total_nodes; ++i) { list.push_back(i); }
};
auto default_pmr_alloc = [total_nodes] {
std::pmr::list<int> list;
for (int i{}; i != total_nodes; ++i) { list.push_back(i); }
};
auto pmr_alloc_no_buf = [total_nodes] {
std::pmr::monotonic_buffer_resource mbr;
std::pmr::polymorphic_allocator<int> pa{&mbr};
std::pmr::list<int> list{pa};
for (int i{}; i != total_nodes; ++i) { list.push_back(i); }
};
auto pmr_alloc_and_buf = [total_nodes] {
std::array<std::byte, total_nodes * 32> buffer; // enough to fit in all nodes
std::pmr::monotonic_buffer_resource mbr{buffer.data(), buffer.size()};
std::pmr::polymorphic_allocator<int> pa{&mbr};
std::pmr::list<int> list{pa};
for (int i{}; i != total_nodes; ++i) { list.push_back(i); }
};
const double t1 = benchmark(default_std_alloc, iterations);
const double t2 = benchmark(default_pmr_alloc, iterations);
const double t3 = benchmark(pmr_alloc_no_buf , iterations);
const double t4 = benchmark(pmr_alloc_and_buf, iterations);
std::cout << std::fixed << std::setprecision(3)
<< "t1 (default std alloc): " << t1 << " sec; t1/t1: " << t1/t1 << '\n'
<< "t2 (default pmr alloc): " << t2 << " sec; t1/t2: " << t1/t2 << '\n'
<< "t3 (pmr alloc no buf): " << t3 << " sec; t1/t3: " << t1/t3 << '\n'
<< "t4 (pmr alloc and buf): " << t4 << " sec; t1/t4: " << t1/t4 << '\n';
}
```
Possible output:
```
t1 (default std alloc): 0.720 sec; t1/t1: 1.000
t2 (default pmr alloc): 0.915 sec; t1/t2: 0.787
t3 (pmr alloc no buf): 0.370 sec; t1/t3: 1.945
t4 (pmr alloc and buf): 0.247 sec; t1/t4: 2.914
```
cpp std::shared_ptr std::shared\_ptr
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T > class shared_ptr;
```
| | (since C++11) |
`std::shared_ptr` is a smart pointer that retains shared ownership of an object through a pointer. Several `shared_ptr` objects may own the same object. The object is destroyed and its memory deallocated when either of the following happens:
* the last remaining `shared_ptr` owning the object is destroyed;
* the last remaining `shared_ptr` owning the object is assigned another pointer via `[operator=](shared_ptr/operator= "cpp/memory/shared ptr/operator=")` or `[reset()](shared_ptr/reset "cpp/memory/shared ptr/reset")`.
The object is destroyed using [delete-expression](../language/delete "cpp/language/delete") or a custom deleter that is supplied to `shared_ptr` during construction.
A `shared_ptr` can share ownership of an object while storing a pointer to another object. This feature can be used to point to member objects while owning the object they belong to. The stored pointer is the one accessed by `[get()](shared_ptr/get "cpp/memory/shared ptr/get")`, the dereference and the comparison operators. The managed pointer is the one passed to the deleter when use count reaches zero.
A `shared_ptr` may also own no objects, in which case it is called *empty* (an empty `shared_ptr` may have a non-null stored pointer if the aliasing constructor was used to create it).
All specializations of `shared_ptr` meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), and [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable") and are [contextually convertible](../language/implicit_cast "cpp/language/implicit cast") to `bool`.
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of `shared_ptr` without additional synchronization even if these instances are copies and share ownership of the same object. If multiple threads of execution access the same instance of `shared_ptr` without synchronization and any of those accesses uses a non-const member function of `shared_ptr` then a data race will occur; the [`shared_ptr` overloads of atomic functions](shared_ptr/atomic "cpp/memory/shared ptr/atomic") can be used to prevent the data race.
### Member types
| Member type | Definition |
| --- | --- |
| `element_type` |
| | |
| --- | --- |
| `T` | (until C++17) |
| `[std::remove\_extent\_t](http://en.cppreference.com/w/cpp/types/remove_extent)<T>` | (since C++17) |
|
| `weak_type` (since C++17) | `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](shared_ptr/shared_ptr "cpp/memory/shared ptr/shared ptr") | constructs new `shared_ptr` (public member function) |
| [(destructor)](shared_ptr/~shared_ptr "cpp/memory/shared ptr/~shared ptr") | destructs the owned object if no more `shared_ptr`s link to it (public member function) |
| [operator=](shared_ptr/operator= "cpp/memory/shared ptr/operator=") | assigns the `shared_ptr` (public member function) |
| Modifiers |
| [reset](shared_ptr/reset "cpp/memory/shared ptr/reset") | replaces the managed object (public member function) |
| [swap](shared_ptr/swap "cpp/memory/shared ptr/swap") | swaps the managed objects (public member function) |
| Observers |
| [get](shared_ptr/get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
| [operator\*operator->](shared_ptr/operator* "cpp/memory/shared ptr/operator*") | dereferences the stored pointer (public member function) |
| [operator[]](shared_ptr/operator_at "cpp/memory/shared ptr/operator at")
(C++17) | provides indexed access to the stored array (public member function) |
| [use\_count](shared_ptr/use_count "cpp/memory/shared ptr/use count") | returns the number of `shared_ptr` objects referring to the same managed object (public member function) |
| [unique](shared_ptr/unique "cpp/memory/shared ptr/unique")
(until C++20) | checks whether the managed object is managed only by the current `shared_ptr` instance (public member function) |
| [operator bool](shared_ptr/operator_bool "cpp/memory/shared ptr/operator bool") | checks if the stored pointer is not null (public member function) |
| [owner\_before](shared_ptr/owner_before "cpp/memory/shared ptr/owner before") | provides owner-based ordering of shared pointers (public member function) |
### Non-member functions
| | |
| --- | --- |
| [make\_sharedmake\_shared\_for\_overwrite](shared_ptr/make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
| [allocate\_sharedallocate\_shared\_for\_overwrite](shared_ptr/allocate_shared "cpp/memory/shared ptr/allocate shared")
(C++20) | creates a shared pointer that manages a new object allocated using an allocator (function template) |
| [static\_pointer\_castdynamic\_pointer\_castconst\_pointer\_castreinterpret\_pointer\_cast](shared_ptr/pointer_cast "cpp/memory/shared ptr/pointer cast")
(C++17) | applies [`static_cast`](../language/static_cast "cpp/language/static cast"), [`dynamic_cast`](../language/dynamic_cast "cpp/language/dynamic cast"), [`const_cast`](../language/const_cast "cpp/language/const cast"), or [`reinterpret_cast`](../language/reinterpret_cast "cpp/language/reinterpret cast") to the stored pointer (function template) |
| [get\_deleter](shared_ptr/get_deleter "cpp/memory/shared ptr/get deleter") | returns the deleter of specified type, if owned (function template) |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](shared_ptr/operator_cmp "cpp/memory/shared ptr/operator cmp")
(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares with another `shared_ptr` or with `nullptr` (function template) |
| [operator<<](shared_ptr/operator_ltlt "cpp/memory/shared ptr/operator ltlt") | outputs the value of the stored pointer to an output stream (function template) |
| [std::swap(std::shared\_ptr)](shared_ptr/swap2 "cpp/memory/shared ptr/swap2")
(C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
| | |
| --- | --- |
| [std::atomic\_is\_lock\_free(std::shared\_ptr)std::atomic\_load(std::shared\_ptr)std::atomic\_load\_explicit(std::shared\_ptr)std::atomic\_store(std::shared\_ptr)std::atomic\_store\_explicit(std::shared\_ptr)std::atomic\_exchange(std::shared\_ptr)std::atomic\_exchange\_explicit(std::shared\_ptr)std::atomic\_compare\_exchange\_weak(std::shared\_ptr)std::atomic\_compare\_exchange\_strong(std::shared\_ptr)std::atomic\_compare\_exchange\_weak\_explicit(std::shared\_ptr)std::atomic\_compare\_exchange\_strong\_explicit(std::shared\_ptr)](shared_ptr/atomic "cpp/memory/shared ptr/atomic")
(deprecated in C++20) | specializes atomic operations for `std::shared_ptr` (function template) |
### Helper classes
| | |
| --- | --- |
| [std::atomic<std::shared\_ptr>](shared_ptr/atomic2 "cpp/memory/shared ptr/atomic2")
(C++20) | atomic shared pointer (class template specialization) |
| [std::hash<std::shared\_ptr>](shared_ptr/hash "cpp/memory/shared ptr/hash")
(C++11) | hash support for `std::shared_ptr` (class template specialization) |
### [Deduction guides](shared_ptr/deduction_guides "cpp/memory/shared ptr/deduction guides")(since C++17)
### Notes
The ownership of an object can only be shared with another `shared_ptr` by copy constructing or copy assigning its value to another `shared_ptr`. Constructing a new `shared_ptr` using the raw underlying pointer owned by another `shared_ptr` leads to undefined behavior.
`std::shared_ptr` may be used with an [incomplete type](../language/incomplete_type "cpp/language/incomplete type") `T`. However, the constructor from a raw pointer (`template<class Y> shared_ptr(Y*)`) and the `template<class Y> void reset(Y*)` member function may only be called with a pointer to a complete type (note that `[std::unique\_ptr](unique_ptr "cpp/memory/unique ptr")` may be constructed from a raw pointer to an incomplete type).
The `T` in `std::shared_ptr<T>` may be a function type: in this case it manages a pointer to function, rather than an object pointer. This is sometimes used to keep a dynamic library or a plugin loaded as long as any of its functions are referenced:
```
void del(void(*)()) {}
void fun() {}
int main(){
std::shared_ptr<void()> ee(fun, del);
(*ee)();
}
```
### Implementation notes
In a typical implementation, `shared_ptr` holds only two pointers:
* the stored pointer (one returned by `[get()](shared_ptr/get "cpp/memory/shared ptr/get")`);
* a pointer to *control block*.
The control block is a dynamically-allocated object that holds:
* either a pointer to the managed object or the managed object itself;
* the deleter (type-erased);
* the allocator (type-erased);
* the number of `shared_ptr`s that own the managed object;
* the number of `weak_ptr`s that refer to the managed object.
When `shared_ptr` is created by calling `[std::make\_shared](shared_ptr/make_shared "cpp/memory/shared ptr/make shared")` or `[std::allocate\_shared](shared_ptr/allocate_shared "cpp/memory/shared ptr/allocate shared")`, the memory for both the control block and the managed object is created with a single allocation. The managed object is constructed in-place in a data member of the control block. When `shared_ptr` is created via one of the `shared_ptr` constructors, the managed object and the control block must be allocated separately. In this case, the control block stores a pointer to the managed object.
The pointer held by the `shared_ptr` directly is the one returned by `[get()](shared_ptr/get "cpp/memory/shared ptr/get")`, while the pointer/object held by the control block is the one that will be deleted when the number of shared owners reaches zero. These pointers are not necessarily equal.
The destructor of `shared_ptr` decrements the number of shared owners of the control block. If that counter reaches zero, the control block calls the destructor of the managed object. The control block does not deallocate itself until the `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` counter reaches zero as well.
In existing implementations, the number of weak pointers is incremented ([[1]](https://stackoverflow.com/questions/43297517/stdshared-ptr-internals-weak-count-more-than-expected), [[2]](https://www.reddit.com/r/cpp/comments/3eia29/stdshared_ptrs_secret_constructor/ctfeh1p)) if there is a shared pointer to the same control block.
To satisfy thread safety requirements, the reference counters are typically incremented using an equivalent of `[std::atomic::fetch\_add](../atomic/atomic/fetch_add "cpp/atomic/atomic/fetch add")` with `[std::memory\_order\_relaxed](../atomic/memory_order "cpp/atomic/memory order")` (decrementing requires stronger ordering to safely destroy the control block).
### Example
```
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
struct Base
{
Base() { std::cout << " Base::Base()\n"; }
// Note: non-virtual destructor is OK here
~Base() { std::cout << " Base::~Base()\n"; }
};
struct Derived: public Base
{
Derived() { std::cout << " Derived::Derived()\n"; }
~Derived() { std::cout << " Derived::~Derived()\n"; }
};
void thr(std::shared_ptr<Base> p)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::shared_ptr<Base> lp = p; // thread-safe, even though the
// shared use_count is incremented
{
static std::mutex io_mutex;
std::lock_guard<std::mutex> lk(io_mutex);
std::cout << "local pointer in a thread:\n"
<< " lp.get() = " << lp.get()
<< ", lp.use_count() = " << lp.use_count() << '\n';
}
}
int main()
{
std::shared_ptr<Base> p = std::make_shared<Derived>();
std::cout << "Created a shared Derived (as a pointer to Base)\n"
<< " p.get() = " << p.get()
<< ", p.use_count() = " << p.use_count() << '\n';
std::thread t1(thr, p), t2(thr, p), t3(thr, p);
p.reset(); // release ownership from main
std::cout << "Shared ownership between 3 threads and released\n"
<< "ownership from main:\n"
<< " p.get() = " << p.get()
<< ", p.use_count() = " << p.use_count() << '\n';
t1.join(); t2.join(); t3.join();
std::cout << "All threads completed, the last one deleted Derived\n";
}
```
Possible output:
```
Base::Base()
Derived::Derived()
Created a shared Derived (as a pointer to Base)
p.get() = 0x2299b30, p.use_count() = 1
Shared ownership between 3 threads and released
ownership from main:
p.get() = 0, p.use_count() = 0
local pointer in a thread:
lp.get() = 0x2299b30, lp.use_count() = 5
local pointer in a thread:
lp.get() = 0x2299b30, lp.use_count() = 3
local pointer in a thread:
lp.get() = 0x2299b30, lp.use_count() = 2
Derived::~Derived()
Base::~Base()
All threads completed, the last one deleted Derived
```
### See also
| | |
| --- | --- |
| [unique\_ptr](unique_ptr "cpp/memory/unique ptr")
(C++11) | smart pointer with unique object ownership semantics (class template) |
| [weak\_ptr](weak_ptr "cpp/memory/weak ptr")
(C++11) | weak reference to an object managed by `std::shared_ptr` (class template) |
| programming_docs |
cpp std::pmr::set_default_resource std::pmr::set\_default\_resource
================================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* set_default_resource(std::pmr::memory_resource* r) noexcept;
```
| | (since C++17) |
If `r` is not null, sets the default memory resource pointer to `r`; otherwise, sets the default memory resource pointer to `[std::pmr::new\_delete\_resource](http://en.cppreference.com/w/cpp/memory/new_delete_resource)()`.
The *default memory resource pointer* is used by certain facilities when an explicit memory resource is not supplied. The initial default memory resource pointer is the return value of `[std::pmr::new\_delete\_resource](new_delete_resource "cpp/memory/new delete resource")`.
This function is thread-safe. Every call to `std::pmr::set_default_resource` *synchronizes with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the subsequent `std::pmr::set_default_resource` and `[std::pmr::get\_default\_resource](get_default_resource "cpp/memory/get default resource")` calls.
### Return value
Returns the previous value of the default memory resource pointer.
### Example
```
#include <array>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <memory_resource>
#include <vector>
class noisy_allocator : public std::pmr::memory_resource {
void* do_allocate(std::size_t bytes, std::size_t alignment) override {
std::cout << "+ Allocating " << bytes << " bytes @ ";
void* p = std::pmr::new_delete_resource()->allocate(bytes, alignment);
std::cout << p << '\n';
return p;
}
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override {
std::cout << "- Deallocating " << bytes << " bytes @ " << p << '\n';
return std::pmr::new_delete_resource()->deallocate(p, bytes, alignment);
}
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
return std::pmr::new_delete_resource()->is_equal(other);
}
};
int main() {
constexpr int push_back_limit{16};
noisy_allocator mem;
std::pmr::set_default_resource(&mem);
{
std::cout << "Entering scope #1 (without buffer on stack)...\n";
std::cout << "Creating vector v...\n";
std::pmr::vector<std::uint16_t> v{ {1, 2, 3, 4} };
std::cout << "v.data() @ " << v.data() << '\n';
std::cout << "Requesting more...\n";
for (int i{0}; i != push_back_limit; ++i) {
v.push_back(i);
std::cout << "v.size(): " << v.size() << '\n';
}
std::cout << "Exiting scope #1...\n";
}
std::cout << '\n';
{
std::cout << "Entering scope #2 (with buffer on stack)...\n";
std::uint8_t buffer[16];
std::cout << "Allocating buffer on stack: " << sizeof buffer << " bytes @ "
<< static_cast<void*>(buffer) << '\n';
std::pmr::monotonic_buffer_resource mem_res{std::data(buffer), std::size(buffer)};
std::cout << "Creating vector v...\n";
std::pmr::vector<std::uint16_t> v{ {1, 2, 3, 4}, &mem_res };
std::cout << "v.data() @ " << v.data() << '\n'; // equals to `buffer` address
std::cout << "Requesting more...\n";
for (int i{0}; i != push_back_limit; ++i) {
v.push_back(i);
std::cout << "v.size(): " << v.size() << '\n';
}
std::cout << "Exiting scope #2...\n";
}
}
```
Possible output:
```
Entering scope #1 (without buffer on stack)...
Creating vector v...
+ Allocating 8 bytes @ 0x1f75c30
v.data() @ 0x1f75c30
Requesting more...
+ Allocating 16 bytes @ 0x1f75c50
- Deallocating 8 bytes @ 0x1f75c30
v.size(): 5
v.size(): 6
v.size(): 7
v.size(): 8
+ Allocating 32 bytes @ 0x1f75c70
- Deallocating 16 bytes @ 0x1f75c50
v.size(): 9
v.size(): 10
v.size(): 11
v.size(): 12
v.size(): 13
v.size(): 14
v.size(): 15
v.size(): 16
+ Allocating 64 bytes @ 0x1f75ca0
- Deallocating 32 bytes @ 0x1f75c70
v.size(): 17
v.size(): 18
v.size(): 19
v.size(): 20
Exiting scope #1...
- Deallocating 64 bytes @ 0x1f75ca0
Entering scope #2 (with buffer on stack)...
Allocating buffer on stack: 16 bytes @ 0x7fffbe9f8240
Creating vector v...
v.data() @ 0x7fffbe9f8240
Requesting more...
+ Allocating 64 bytes @ 0x1f75ca0
v.size(): 5
v.size(): 6
v.size(): 7
v.size(): 8
v.size(): 9
v.size(): 10
v.size(): 11
v.size(): 12
v.size(): 13
v.size(): 14
v.size(): 15
v.size(): 16
+ Allocating 128 bytes @ 0x1f75cf0
v.size(): 17
v.size(): 18
v.size(): 19
v.size(): 20
Exiting scope #2...
- Deallocating 128 bytes @ 0x1f75cf0
- Deallocating 64 bytes @ 0x1f75ca0
```
### See also
| | |
| --- | --- |
| [get\_default\_resource](get_default_resource "cpp/memory/get default resource")
(C++17) | gets the default `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` (function) |
| [new\_delete\_resource](new_delete_resource "cpp/memory/new delete resource")
(C++17) | returns a static program-wide `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` that uses the global `[operator new](new/operator_new "cpp/memory/new/operator new")` and `[operator delete](new/operator_delete "cpp/memory/new/operator delete")` to allocate and deallocate memory (function) |
cpp std::align std::align
==========
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void* align( std::size_t alignment,
std::size_t size,
void*& ptr,
std::size_t& space );
```
| | (since C++11) |
Given a pointer `ptr` to a buffer of size `space`, returns a pointer aligned by the specified `alignment` for `size` number of bytes and decreases `space` argument by the number of bytes used for alignment. The first aligned address is returned.
The function modifies the pointer only if it would be possible to fit the wanted number of bytes aligned by the given alignment into the buffer. If the buffer is too small, the function does nothing and returns `nullptr`.
The behavior is undefined if `alignment` is not a power of two.
### Parameters
| | | |
| --- | --- | --- |
| alignment | - | the desired alignment |
| size | - | the size of the storage to be aligned |
| ptr | - | pointer to contiguous storage (a buffer) of at least `space` bytes |
| space | - | the size of the buffer in which to operate |
### Return value
The adjusted value of `ptr`, or null pointer value if the space provided is too small.
### Example
demonstrates the use of `std::align` to place objects of different type in memory.
```
#include <iostream>
#include <memory>
template <std::size_t N>
struct MyAllocator
{
char data[N];
void* p;
std::size_t sz;
MyAllocator() : p(data), sz(N) {}
template <typename T>
T* aligned_alloc(std::size_t a = alignof(T))
{
if (std::align(a, sizeof(T), p, sz))
{
T* result = reinterpret_cast<T*>(p);
p = (char*)p + sizeof(T);
sz -= sizeof(T);
return result;
}
return nullptr;
}
};
int main()
{
MyAllocator<64> a;
std::cout << "allocated a.data at " << (void*)a.data
<< " (" << sizeof a.data << " bytes)\n";
// allocate a char
if (char* p = a.aligned_alloc<char>()) {
*p = 'a';
std::cout << "allocated a char at " << (void*)p << '\n';
}
// allocate an int
if (int* p = a.aligned_alloc<int>()) {
*p = 1;
std::cout << "allocated an int at " << (void*)p << '\n';
}
// allocate an int, aligned at 32-byte boundary
if (int* p = a.aligned_alloc<int>(32)) {
*p = 2;
std::cout << "allocated an int at " << (void*)p << " (32 byte alignment)\n";
}
}
```
Possible output:
```
allocated a.data at 0x7ffd0b331f80 (64 bytes)
allocated a char at 0x7ffd0b331f80
allocated an int at 0x7ffd0b331f84
allocated an int at 0x7ffd0b331fa0 (32 byte alignment)
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2377](https://cplusplus.github.io/LWG/issue2377) | C++11 | `alignment` required to be a fundamental or supported extended alignment value | only need to be a power of two |
### See also
| | |
| --- | --- |
| [`alignof` operator](../language/alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type |
| [`alignas` specifier](../language/alignas "cpp/language/alignas")(C++11) | specifies that the storage for the variable should be aligned by specific amount |
| [aligned\_storage](../types/aligned_storage "cpp/types/aligned storage")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) |
| [assume\_aligned](assume_aligned "cpp/memory/assume aligned")
(C++20) | informs the compiler that a pointer is aligned (function template) |
cpp std::get_temporary_buffer std::get\_temporary\_buffer
===========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
std::pair<T*, std::ptrdiff_t>
get_temporary_buffer( std::ptrdiff_t count );
```
| | (until C++11) |
|
```
template< class T >
std::pair<T*, std::ptrdiff_t>
get_temporary_buffer( std::ptrdiff_t count ) noexcept;
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
Allocates uninitialized contiguous storage, which should be sufficient to store up to `count` adjacent objects of type `T`. The request is non-binding and the implementation may allocate less or more than necessary to store `count` adjacent objects.
### Parameters
| | | |
| --- | --- | --- |
| count | - | the desired number of objects |
### Return value
A `[std::pair](../utility/pair "cpp/utility/pair")` holding a pointer to the beginning of the allocated storage and the number of objects that fit in the storage that was actually allocated.
If no memory could be allocated, or allocated storage is not enough to store a single element of type `T`, the `first` element of the result is a null pointer and the `second` element is zero.
### Notes
This API was originally designed with the intent of providing a more efficient implementation than the general-purpose operator new, but no such implementation was created and the API was deprecated and removed.
### Example
```
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <iterator>
int main()
{
const std::string s[] = {"string", "1", "test", "..."};
const auto p = std::get_temporary_buffer<std::string>(4);
// requires that p.first is passed to return_temporary_buffer
// (beware of early exit points and exceptions)
std::copy(s, s + p.second,
std::raw_storage_iterator<std::string*, std::string>(p.first));
// has same effect as: std::uninitialized_copy(s, s + p.second, p.first);
// requires that each string in p is individually destroyed
// (beware of early exit points and exceptions)
std::copy(p.first, p.first + p.second,
std::ostream_iterator<std::string>{std::cout, "\n"});
std::for_each(p.first, p.first + p.second, [](std::string& e) {
e.~basic_string<char>();
}); // same as: std::destroy(p.first, p.first + p.second);
std::return_temporary_buffer(p.first);
}
```
Output:
```
string
1
test
...
```
### See also
| | |
| --- | --- |
| [return\_temporary\_buffer](return_temporary_buffer "cpp/memory/return temporary buffer")
(deprecated in C++17)(removed in C++20) | frees uninitialized storage (function template) |
| [allocate\_at\_least](allocate_at_least "cpp/memory/allocate at least")
(C++23) | allocates storage at least as large as the requested size via an allocator (function template) |
cpp std::destroy std::destroy
============
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class ForwardIt >
void destroy( ForwardIt first, ForwardIt last );
```
| (since C++17) (until C++20) |
|
```
template< class ForwardIt >
constexpr void destroy( ForwardIt first, ForwardIt last );
```
| (since C++20) |
|
```
template< class ExecutionPolicy, class ForwardIt >
void destroy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last );
```
| (2) | (since C++17) |
1) Destroys the objects in the range `[first, last)`, as if by
```
for (; first != last; ++first)
std::destroy_at(std::addressof(*first));
```
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of elements to destroy |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. |
### Return value
(none).
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template< class ForwardIt >
constexpr // since C++20
void destroy( ForwardIt first, ForwardIt last )
{
for (; first != last; ++first)
std::destroy_at(std::addressof(*first));
}
```
|
### Example
The following example demonstrates how to use `destroy` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
std::destroy(ptr, ptr + 8);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [destroy\_n](destroy_n "cpp/memory/destroy n")
(C++17) | destroys a number of objects in a range (function template) |
| [destroy\_at](destroy_at "cpp/memory/destroy at")
(C++17) | destroys an object at a given address (function template) |
| [ranges::destroy](ranges/destroy "cpp/memory/ranges/destroy")
(C++20) | destroys a range of objects (niebloid) |
cpp std::return_temporary_buffer std::return\_temporary\_buffer
==============================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
void return_temporary_buffer( T* p );
```
| | (deprecated in C++17) (removed in C++20) |
Deallocates storage previously allocated with `[std::get\_temporary\_buffer](get_temporary_buffer "cpp/memory/get temporary buffer")`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | the pointer previously returned by `[std::get\_temporary\_buffer](get_temporary_buffer "cpp/memory/get temporary buffer")` and not invalidated by an earlier call to `return_temporary_buffer` |
### Return value
(none).
### Exceptions
Throws nothing.
### Example
```
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <iterator>
int main()
{
const std::string s[] = {"string", "1", "test", "..."};
const auto p = std::get_temporary_buffer<std::string>(4);
// requires that p.first is passed to return_temporary_buffer
// (beware of early exit points and exceptions)
std::copy(s, s + p.second,
std::raw_storage_iterator<std::string*, std::string>(p.first));
// has same effect as: std::uninitialized_copy(s, s + p.second, p.first);
// requires that each string in p is individually destroyed
// (beware of early exit points and exceptions)
std::copy(p.first, p.first + p.second,
std::ostream_iterator<std::string>{std::cout, "\n"});
std::for_each(p.first, p.first + p.second, [](std::string& e) {
e.~basic_string<char>();
}); // same as: std::destroy(p.first, p.first + p.second);
std::return_temporary_buffer(p.first);
}
```
Output:
```
string
1
test
...
```
### See also
| | |
| --- | --- |
| [get\_temporary\_buffer](get_temporary_buffer "cpp/memory/get temporary buffer")
(deprecated in C++17)(removed in C++20) | obtains uninitialized storage (function template) |
cpp std::owner_less std::owner\_less
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
struct owner_less; /* undefined */
```
| (since C++11) (until C++17) |
|
```
template< class T = void >
struct owner_less; /* undefined */
```
| (since C++17) |
|
```
template< class T >
struct owner_less<std::shared_ptr<T>>;
```
| (2) | (since C++11) |
|
```
template< class T >
struct owner_less<std::weak_ptr<T>>;
```
| (3) | (since C++11) |
|
```
template<>
struct owner_less<void>;
```
| (4) | (since C++17) |
This function object provides owner-based (as opposed to value-based) mixed-type ordering of both `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` and `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")`. The order is such that two smart pointers compare equivalent only if they are both empty or if they share ownership, even if the values of the raw pointers obtained by `get()` are different (e.g. because they point at different subobjects within the same object).
This class template is the preferred comparison predicate when building associative containers with `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` or `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")` as keys, that is,
`[std::map](http://en.cppreference.com/w/cpp/container/map)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>, U, std::owner\_less<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>>>`
or.
`[std::map](http://en.cppreference.com/w/cpp/container/map)<[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>, U, std::owner\_less<[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>>>`.
The default `operator<` is not defined for weak pointers, and may wrongly consider two shared pointers for the same object non-equivalent (see [`shared_ptr::owner_before`](shared_ptr/owner_before "cpp/memory/shared ptr/owner before")).
### Specializations
| | | | |
| --- | --- | --- | --- |
| The standard library provides a specialization of `std::owner_less` when `T` is not specified. In this case, the parameter types are deduced from the arguments (each of which must still be either a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` or a `[std::weak\_ptr](weak_ptr "cpp/memory/weak ptr")`).
| | |
| --- | --- |
| [owner\_less<void>](owner_less_void "cpp/memory/owner less void") | function object providing mixed-type owner-based ordering of shared and weak pointers, regardless of the type of the pointee (class template specialization) |
| (since C++17) |
| | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Member types
| Member type | Definition |
| --- | --- |
| `result_type`(deprecated in c++17) | 2-3) `bool` |
| `first_argument_type`(deprecated in c++17) | 2) `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>`3) `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` |
| `second_argument_type`(deprecated in c++17) | 2) `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>`3) `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` |
| (until C++20) |
### Member functions
| | |
| --- | --- |
| **operator()** | compares its arguments using owner-based semantics (function) |
std::owner\_less::operator()
-----------------------------
| | | |
| --- | --- | --- |
| member only of `owner_less<shared_ptr<T>>` template specialization | | |
|
```
bool operator()( const std::shared_ptr<T>& lhs,
const std::shared_ptr<T>& rhs ) const noexcept;
```
| | (since C++11) |
| member only of `owner_less<weak_ptr<T>>` template specialization | | |
|
```
bool operator()( const std::weak_ptr<T>& lhs,
const std::weak_ptr<T>& rhs ) const noexcept;
```
| | (since C++11) |
| member of both template specializations | | |
|
```
bool operator()( const std::shared_ptr<T>& lhs,
const std::weak_ptr<T>& rhs ) const noexcept;
```
| | (since C++11) |
|
```
bool operator()( const std::weak_ptr<T>& lhs,
const std::shared_ptr<T>& rhs ) const noexcept;
```
| | (since C++11) |
Compares `lhs` and `rhs` using owner-based semantics. Effectively calls `lhs.owner_before(rhs)`.
The ordering is strict weak ordering relation.
`lhs` and `rhs` are equivalent only if they are both empty or share ownership.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | shared-ownership pointers to compare |
### Return value
`true` if `lhs` is *less than* `rhs` as determined by the owner-based ordering.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2873](https://cplusplus.github.io/LWG/issue2873) | C++11 | the operator()'s might not be declared noexcept | declared noexcept |
### See also
| | |
| --- | --- |
| [owner\_before](shared_ptr/owner_before "cpp/memory/shared ptr/owner before") | provides owner-based ordering of shared pointers (public member function of `std::shared_ptr<T>`) |
| [owner\_before](weak_ptr/owner_before "cpp/memory/weak ptr/owner before") | provides owner-based ordering of weak pointers (public member function of `std::weak_ptr<T>`) |
| programming_docs |
cpp std::assume_aligned std::assume\_aligned
====================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< std::size_t N, class T >
[[nodiscard]] constexpr T* assume_aligned(T* ptr);
```
| | (since C++20) |
Informs the implementation that the object `ptr` points to is aligned to at least `N`. The implementation may use this information to generate more efficient code, but it might only make this assumption if the object is accessed via the return value of `assume_aligned`.
The program is ill-formed if `N` is not a power of 2. The behavior is undefined if `ptr` does not point to an object of type `T` (ignoring cv-qualification at every level), or if the object's alignment is not at least `N`.
### Return value
`ptr`.
### Exceptions
Throws nothing.
### Notes
To ensure that the program benefits from the optimizations enabled by `assume_aligned`, it is important to access the object via its return value:
```
void f(int* p) {
int* p1 = std::assume_aligned<256>(p);
// Use p1, not p, to ensure benefit from the alignment assumption.
// However, the program has undefined behavior if p is not aligned
// regardless of whether p1 is used.
}
```
It is up to the program to ensure that the alignment assumption actually holds. A call to `assume_aligned` does not cause the compiler to verify or enforce this.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_assume_aligned`](../feature_test#Library_features "cpp/feature test") |
### See also
| | |
| --- | --- |
| [`alignof` operator](../language/alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type |
| [`alignas` specifier](../language/alignas "cpp/language/alignas")(C++11) | specifies that the storage for the variable should be aligned by specific amount |
| [aligned\_storage](../types/aligned_storage "cpp/types/aligned storage")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) |
| [align](align "cpp/memory/align")
(C++11) | aligns a pointer in a buffer (function) |
cpp std::destroy_at std::destroy\_at
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
void destroy_at( T* p );
```
| | (since C++17) (until C++20) |
|
```
template< class T >
constexpr void destroy_at( T* p );
```
| | (since C++20) |
If `T` is not an array type, calls the destructor of the object pointed to by `p`, as if by `p->~T()`.
If `T` is an array type, the program is ill-formed (until C++20)recursively destroys elements of `*p` in order, as if by calling `[std::destroy](http://en.cppreference.com/w/cpp/memory/destroy)([std::begin](http://en.cppreference.com/w/cpp/iterator/begin)(\*p), [std::end](http://en.cppreference.com/w/cpp/iterator/end)(\*p))` (since C++20).
### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to the object to be destroyed |
### Return value
(none).
### Possible implementation
| |
| --- |
|
```
template<class T>
constexpr void destroy_at(T* p)
{
if constexpr (std::is_array_v<T>)
for (auto &elem : *p)
(destroy_at)(std::addressof(elem));
else
p->~T();
}
// C++17 version:
// template<class T> void destroy_at(T* p) { p->~T(); }
```
|
### Notes
`destroy_at` deduces the type of object to be destroyed and hence avoids writing it explicitly in the destructor call.
| | |
| --- | --- |
| When `destroy_at` is called in the evaluation of some [constant expression](../language/constant_expression "cpp/language/constant expression") `e`, the argument `p` must point to an object whose lifetime began within the evaluation of `e`. | (since C++20) |
### Example
The following example demonstrates how to use `destroy_at` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
for (int i = 0; i < 8; ++i)
std::destroy_at(ptr + i);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [destroy](destroy "cpp/memory/destroy")
(C++17) | destroys a range of objects (function template) |
| [destroy\_n](destroy_n "cpp/memory/destroy n")
(C++17) | destroys a number of objects in a range (function template) |
| [construct\_at](construct_at "cpp/memory/construct at")
(C++20) | creates an object at a given address (function template) |
| [ranges::destroy\_at](ranges/destroy_at "cpp/memory/ranges/destroy at")
(C++20) | destroys an object at a given address (niebloid) |
cpp std::unique_ptr std::unique\_ptr
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
```
| (1) | (since C++11) |
|
```
template <
class T,
class Deleter
> class unique_ptr<T[], Deleter>;
```
| (2) | (since C++11) |
`std::unique_ptr` is a smart pointer that owns and manages another object through a pointer and disposes of that object when the `unique_ptr` goes out of scope.
The object is disposed of, using the associated deleter when either of the following happens:
* the managing `unique_ptr` object is destroyed
* the managing `unique_ptr` object is assigned another pointer via `[operator=](unique_ptr/operator= "cpp/memory/unique ptr/operator=")` or `[reset()](unique_ptr/reset "cpp/memory/unique ptr/reset")`.
The object is disposed of, using a potentially user-supplied deleter by calling `get_deleter()(ptr)`. The default deleter uses the `delete` operator, which destroys the object and deallocates the memory.
A `unique_ptr` may alternatively own no object, in which case it is called *empty*.
There are two versions of `std::unique_ptr`:
1. Manages a single object (e.g. allocated with `new`)
2. Manages a dynamically-allocated array of objects (e.g. allocated with `new[]`)
The class satisfies the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"), but of neither [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") nor [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable").
| |
| --- |
| Type requirements |
| -`Deleter` must be [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") or lvalue reference to a [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") or lvalue reference to function, callable with an argument of type `unique_ptr<T, Deleter>::pointer` |
### Notes
Only non-const `unique_ptr` can transfer the ownership of the managed object to another `unique_ptr`. If an object's lifetime is managed by a `const std::unique_ptr`, it is limited to the scope in which the pointer was created.
`std::unique_ptr` is commonly used to manage the lifetime of objects, including:
* providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception
* passing ownership of uniquely-owned objects with dynamic lifetime into functions
* acquiring ownership of uniquely-owned objects with dynamic lifetime from functions
* as the element type in move-aware containers, such as `[std::vector](../container/vector "cpp/container/vector")`, which hold pointers to dynamically-allocated objects (e.g. if polymorphic behavior is desired)
`std::unique_ptr` may be constructed for an [incomplete type](../language/incomplete_type "cpp/language/incomplete type") `T`, such as to facilitate the use as a handle in the [pImpl idiom](../language/pimpl "cpp/language/pimpl"). If the default deleter is used, `T` must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and `reset` member function of `std::unique_ptr`. (Conversely, `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` can't be constructed from a raw pointer to incomplete type, but can be destroyed where `T` is incomplete). Note that if `T` is a class template specialization, use of `unique_ptr` as an operand, e.g. `!p` requires `T`'s parameters to be complete due to [ADL](../language/adl "cpp/language/adl").
If `T` is a [derived class](../language/derived_class "cpp/language/derived class") of some base `B`, then `std::unique_ptr<T>` is [implicitly convertible](unique_ptr/unique_ptr "cpp/memory/unique ptr/unique ptr") to `std::unique_ptr<B>`. The default deleter of the resulting `std::unique_ptr<B>` will use [operator delete](new/operator_delete "cpp/memory/new/operator delete") for `B`, leading to [undefined behavior](../language/destructor#Virtual_destructors "cpp/language/destructor") unless the destructor of `B` is [virtual](../language/virtual "cpp/language/virtual"). Note that `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` behaves differently: `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<B>` will use the [operator delete](new/operator_delete "cpp/memory/new/operator delete") for the type `T` and the owned object will be deleted correctly even if the destructor of `B` is not [virtual](../language/virtual "cpp/language/virtual").
Unlike `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")`, `std::unique_ptr` may manage an object through any custom handle type that satisfies [NullablePointer](../named_req/nullablepointer "cpp/named req/NullablePointer"). This allows, for example, managing objects located in shared memory, by supplying a `Deleter` that defines `typedef [boost::offset\_ptr](http://www.boost.org/doc/libs/release/doc/html/boost/interprocess/offset_ptr.html) pointer;` or another [fancy pointer](../named_req/allocator#Fancy_pointers "cpp/named req/Allocator").
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_constexpr_memory`](../feature_test#Library_features "cpp/feature test") |
### Member types
| Member type | Definition |
| --- | --- |
| `pointer` | `[std::remove\_reference](http://en.cppreference.com/w/cpp/types/remove_reference)<Deleter>::type::pointer` if that type exists, otherwise `T*`. Must satisfy [NullablePointer](../named_req/nullablepointer "cpp/named req/NullablePointer") |
| `element_type` | `T`, the type of the object managed by this `unique_ptr` |
| `deleter_type` | `Deleter`, the function object or lvalue reference to function or to function object, to be called from the destructor |
### Member functions
| | |
| --- | --- |
| [(constructor)](unique_ptr/unique_ptr "cpp/memory/unique ptr/unique ptr") | constructs a new `unique_ptr` (public member function) |
| [(destructor)](unique_ptr/~unique_ptr "cpp/memory/unique ptr/~unique ptr") | destructs the managed object if such is present (public member function) |
| [operator=](unique_ptr/operator= "cpp/memory/unique ptr/operator=") | assigns the `unique_ptr` (public member function) |
| Modifiers |
| [release](unique_ptr/release "cpp/memory/unique ptr/release") | returns a pointer to the managed object and releases the ownership (public member function) |
| [reset](unique_ptr/reset "cpp/memory/unique ptr/reset") | replaces the managed object (public member function) |
| [swap](unique_ptr/swap "cpp/memory/unique ptr/swap") | swaps the managed objects (public member function) |
| Observers |
| [get](unique_ptr/get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
| [get\_deleter](unique_ptr/get_deleter "cpp/memory/unique ptr/get deleter") | returns the deleter that is used for destruction of the managed object (public member function) |
| [operator bool](unique_ptr/operator_bool "cpp/memory/unique ptr/operator bool") | checks if there is an associated managed object (public member function) |
| Single-object version, `unique_ptr<T>` |
| [operator\*operator->](unique_ptr/operator* "cpp/memory/unique ptr/operator*") | dereferences pointer to the managed object (public member function) |
| Array version, `unique_ptr<T[]>` |
| [operator[]](unique_ptr/operator_at "cpp/memory/unique ptr/operator at") | provides indexed access to the managed array (public member function) |
### Non-member functions
| | |
| --- | --- |
| [make\_uniquemake\_unique\_for\_overwrite](unique_ptr/make_unique "cpp/memory/unique ptr/make unique")
(C++14)(C++20) | creates a unique pointer that manages a new object (function template) |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](unique_ptr/operator_cmp "cpp/memory/unique ptr/operator cmp")
(removed in C++20)(C++20) | compares to another `unique_ptr` or with `nullptr` (function template) |
| [operator<<](unique_ptr/operator_ltlt "cpp/memory/unique ptr/operator ltlt")
(C++20) | outputs the value of the managed pointer to an output stream (function template) |
| [std::swap(std::unique\_ptr)](unique_ptr/swap2 "cpp/memory/unique ptr/swap2")
(C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
### Helper classes
| | |
| --- | --- |
| [std::hash<std::unique\_ptr>](unique_ptr/hash "cpp/memory/unique ptr/hash")
(C++11) | hash support for `std::unique_ptr` (class template specialization) |
### Example
```
#include <cassert>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
// helper class for runtime polymorphism demo below
struct B
{
virtual ~B() = default;
virtual void bar() { std::cout << "B::bar\n"; }
};
struct D : B
{
D() { std::cout << "D::D\n"; }
~D() { std::cout << "D::~D\n"; }
void bar() override { std::cout << "D::bar\n"; }
};
// a function consuming a unique_ptr can take it by value or by rvalue reference
std::unique_ptr<D> pass_through(std::unique_ptr<D> p)
{
p->bar();
return p;
}
// helper function for the custom deleter demo below
void close_file(std::FILE* fp)
{
std::fclose(fp);
}
// unique_ptr-based linked list demo
struct List
{
struct Node
{
int data;
std::unique_ptr<Node> next;
};
std::unique_ptr<Node> head;
~List()
{
// destroy list nodes sequentially in a loop, the default destructor
// would have invoked its `next`'s destructor recursively, which would
// cause stack overflow for sufficiently large lists.
while (head)
head = std::move(head->next);
}
void push(int data)
{
head = std::unique_ptr<Node>(new Node{data, std::move(head)});
}
};
int main()
{
std::cout << "1) Unique ownership semantics demo\n";
{
// Create a (uniquely owned) resource
std::unique_ptr<D> p = std::make_unique<D>();
// Transfer ownership to `pass_through`,
// which in turn transfers ownership back through the return value
std::unique_ptr<D> q = pass_through(std::move(p));
// `p` is now in a moved-from 'empty' state, equal to `nullptr`
assert(!p);
}
std::cout << "\n" "2) Runtime polymorphism demo\n";
{
// Create a derived resource and point to it via base type
std::unique_ptr<B> p = std::make_unique<D>();
// Dynamic dispatch works as expected
p->bar();
}
std::cout << "\n" "3) Custom deleter demo\n";
std::ofstream("demo.txt") << 'x'; // prepare the file to read
{
using unique_file_t = std::unique_ptr<std::FILE, decltype(&close_file)>;
unique_file_t fp(std::fopen("demo.txt", "r"), &close_file);
if (fp)
std::cout << char(std::fgetc(fp.get())) << '\n';
} // `close_file()` called here (if `fp` is not null)
std::cout << "\n" "4) Custom lambda-expression deleter and exception safety demo\n";
try
{
std::unique_ptr<D, void(*)(D*)> p(new D, [](D* ptr)
{
std::cout << "destroying from a custom deleter...\n";
delete ptr;
});
throw std::runtime_error(""); // `p` would leak here if it were instead a plain pointer
}
catch (const std::exception&) { std::cout << "Caught exception\n"; }
std::cout << "\n" "5) Array form of unique_ptr demo\n";
{
std::unique_ptr<D[]> p(new D[3]);
} // `D::~D()` is called 3 times
std::cout << "\n" "6) Linked list demo\n";
{
List wall;
for (int beer = 0; beer != 1'000'000; ++beer)
wall.push(beer);
std::cout << "1'000'000 bottles of beer on the wall...\n";
} // destroys all the beers
}
```
Possible output:
```
1) Unique ownership semantics demo
D::D
D::bar
D::~D
2) Runtime polymorphism demo
D::D
D::bar
D::~D
3) Custom deleter demo
x
4) Custom lambda-expression deleter and exception safety demo
D::D
destroying from a custom deleter...
D::~D
Caught exception
5) Array form of unique_ptr demo
D::D
D::D
D::D
D::~D
D::~D
D::~D
6) Linked list demo
1'000'000 bottles of beer on the wall...
```
### See also
| | |
| --- | --- |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
| [weak\_ptr](weak_ptr "cpp/memory/weak ptr")
(C++11) | weak reference to an object managed by `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` (class template) |
cpp std::out_ptr_t std::out\_ptr\_t
================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Smart, class Pointer, class... Args >
class out_ptr_t;
```
| | (since C++23) |
`out_ptr_t` is used to adapt types such as smart pointers for foreign functions that output their results via a `Pointer*` (usually `T**` for some object type `T`) or `void**` parameter.
`out_ptr_t` captures additional arguments on construction, provides a storage for the result to which such an aforementioned foreign function writes, and finally resets the adapted `Smart` object with the result and the captured arguments when it is destroyed.
`out_ptr_t` behaves as if it holds following non-static data members:
* a `Smart&` reference, which is bound to the adapted object on construction,
* for every `T` in `Args...`, a member of type `T`, which is an argument captured on construction and used for resetting while destruction, and
* a member subobject that suitable for storing a `Pointer` within it and providing a `void*` object, where the `Pointer` or `void*` object is generally exposed to a foreign function for re-initialization.
Users can control whether each argument for resetting is captured by copy or by reference, by specifying an object type or a reference type in `Args...` respectively.
### Template parameters
| | | |
| --- | --- | --- |
| Smart | - | the type of the object (typically a smart pointer) to adapt |
| Pointer | - | type of the object (typically a raw pointer) to which a foreign function writes its result |
| Args... | - | type of captured arguments used for resetting the adapted object |
| Type requirements |
| -`Pointer` must meet the requirements of [NullablePointer](../named_req/nullablepointer "cpp/named req/NullablePointer"). |
| -The program is ill-formed if `Smart` is a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` specialization and `sizeof...(Args) == 0`. |
### Specializations
Unlike most class templates in the standard library, program-defined specializations of `out_ptr_t` that depend on at least one program-defined type need not meet the requirements for the primary template.
This license allows a program-defined specialization to expose the raw pointer stored within a non-standard smart pointer to foreign functions.
### Member functions
| | |
| --- | --- |
| [(constructor)](out_ptr_t/out_ptr_t "cpp/memory/out ptr t/out ptr t")
(C++23) | constructs an `out_ptr_t` (public member function) |
| operator=
[deleted](C++23) | `out_ptr_t` is not assignable (public member function) |
| [(destructor)](out_ptr_t/~out_ptr_t "cpp/memory/out ptr t/~out ptr t")
(C++23) | resets the adapted smart pointer (public member function) |
| [operator Pointer\*operator void\*\*](out_ptr_t/operator_ptr "cpp/memory/out ptr t/operator ptr")
(C++23) | converts the `out_ptr_t` to the address of the storage for output (public member function) |
### Non-member functions
| | |
| --- | --- |
| [out\_ptr](out_ptr_t/out_ptr "cpp/memory/out ptr t/out ptr")
(C++23) | creates an `out_ptr_t` with an associated smart pointer and resetting arguments (function template) |
### Notes
`out_ptr_t` expects that the foreign functions do not used the value of the pointed-to `Pointer`, and only re-initialize it. The value of the smart pointer before adaption is not used.
The typical usage of `out_ptr_t` is creating its temporary objects by `std::out_ptr`, which resets the adapted smart pointer immediately. E.g. given a setter function and a smart pointer of appropriate type declared with `int foreign_setter(T**);` and `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<T, D> up;` respectively,
```
int foreign_setter(T**);
std::unique_ptr<T, D> up;
if (int ec = foreign_setter(std::out_ptr(up)) {
return ec;
}
```
is roughly equivalent to.
```
int foreign_setter(T**);
std::unique_ptr<T, D> up;
T* raw_p{};
int ec = foreign_setter(&raw_p);
up.reset(raw_p);
if (ec != 0) {
return ec;
}
```
It is not recommended to create an `out_ptr_t` object of a [storage duration](../language/storage_duration "cpp/language/storage duration") other than automatic storage duration, because such code is likely to produce dangling references and result in undefined behavior on destruction.
`out_ptr_t` forbids the usage that would reset a `[std::shared\_ptr](shared_ptr "cpp/memory/shared ptr")` without specifying a deleter, because it would call `[std::shared\_ptr::reset](shared_ptr/reset "cpp/memory/shared ptr/reset")` and replace a custom deleter later.
Captured arguments are typically packed into a `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Args...>`. Implementations may use different mechanism to provide the `Pointer` or `void*` object they need hold.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_out_ptr`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [inout\_ptr\_t](inout_ptr_t "cpp/memory/inout ptr t")
(C++23) | interoperates with foreign pointer setters, obtains the initial pointer value from a smart pointer, and resets it on destruction (class template) |
| [unique\_ptr](unique_ptr "cpp/memory/unique ptr")
(C++11) | smart pointer with unique object ownership semantics (class template) |
| [shared\_ptr](shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
| programming_docs |
cpp std::pmr::pool_options std::pmr::pool\_options
=======================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
struct pool_options;
```
| | (since C++17) |
`std::pmr::pool_options` is a set of constructor options for pool resources including `[std::pmr::synchronized\_pool\_resource](synchronized_pool_resource "cpp/memory/synchronized pool resource")` and `[std::pmr::unsynchronized\_pool\_resource](unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource")`.
### Data members
| Member | Meaning |
| --- | --- |
|
| | | |
| --- | --- | --- |
|
```
std::size_t max_blocks_per_chunk;
```
| | |
| The maximum number of blocks that will be allocated at once from the upstream `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` to replenish the pool. If the value of `max_blocks_per_chunk` is zero or is greater than an implementation-defined limit, that limit is used instead. The implementation may choose to use a smaller value than is specified in this field and may use different values for different pools. |
|
| | | |
| --- | --- | --- |
|
```
std::size_t largest_required_pool_block;
```
| | |
| The largest allocation size that is required to be fulfilled using the pooling mechanism. Attempts to allocate a single block larger than this threshold will be allocated directly from the upstream `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")`. If `largest_required_pool_block` is zero or is greater than an implementation-defined limit, that limit is used instead. The implementation may choose a pass-through threshold larger than specified in this field. |
### See also
| | |
| --- | --- |
| [synchronized\_pool\_resource](synchronized_pool_resource "cpp/memory/synchronized pool resource")
(C++17) | a thread-safe `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` for managing allocations in pools of different block sizes (class) |
| [unsynchronized\_pool\_resource](unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource")
(C++17) | a thread-unsafe `[std::pmr::memory\_resource](memory_resource "cpp/memory/memory resource")` for managing allocations in pools of different block sizes (class) |
cpp std::default_delete std::default\_delete
====================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T > struct default_delete;
```
| (1) | (since C++11) |
|
```
template< class T > struct default_delete<T[]>;
```
| (2) | (since C++11) |
`std::default_delete` is the default destruction policy used by `[std::unique\_ptr](unique_ptr "cpp/memory/unique ptr")` when no deleter is specified. Specializations of `default_delete` are empty classes on typical implementations, and used in the [empty base class optimization](../language/ebo "cpp/language/ebo").
1) The non-specialized `default_delete` uses `delete` to deallocate memory for a single object.
2) A partial specialization for array types that uses `delete[]` is also provided. ### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a `default_delete` object (public member function) |
| **operator()** | deletes the object or array (public member function) |
std::default\_delete::default\_delete
--------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr default_delete() noexcept = default;
```
| (1) | |
| | (2) | |
|
```
template <class U>
default_delete( const default_delete<U>& d ) noexcept;
```
| (since C++11) (until C++23) (member only of primary `default_delete` template) |
|
```
template <class U>
constexpr default_delete( const default_delete<U>& d ) noexcept;
```
| (since C++23) (member only of primary `default_delete` template) |
| | (3) | |
|
```
template<class U>
default_delete( const default_delete<U[]>& d ) noexcept;
```
| (since C++11) (until C++23) (member only of `default_delete<T[]>` specialization) |
|
```
template<class U>
constexpr default_delete( const default_delete<U[]>& d ) noexcept;
```
| (since C++23) (member only of `default_delete<T[]>` specialization) |
1) Constructs a `std::default_delete` object.
2) Constructs a `std::default_delete<T>` object from another `std::default_delete` object. This constructor will only participate in overload resolution if `U*` is implicitly convertible to `T*`.
3) Constructs a `std::default_delete<T[]>` object from another `std::default_delete<U[]>` object. This constructor will only participate in overload resolution if `U(*)[]` is implicitly convertible to `T(*)[]`. ### Parameters
| | | |
| --- | --- | --- |
| d | - | a deleter to copy from |
### Notes
The [converting constructor](../language/converting_constructor "cpp/language/converting constructor") template of `std::default_delete` makes possible the implicit conversion from `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<Derived>` to `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<Base>`.
std::default\_delete::operator()
---------------------------------
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void operator()(T* ptr) const;
```
| (since C++11) (until C++23) (member only of primary `default_delete` template) |
|
```
constexpr void operator()(T* ptr) const;
```
| (since C++23) (member only of primary `default_delete` template) |
| | (2) | |
|
```
template <class U>
void operator()(U* ptr) const;
```
| (since C++11) (until C++23) (member only of `default_delete<T[]>` specialization) |
|
```
template <class U>
constexpr void operator()(U* ptr) const;
```
| (since C++23) (member only of `default_delete<T[]>` specialization) |
1) Calls `delete` on `ptr`
2) Calls `delete[]` on `ptr`. This function will only participate in overload resolution if `U(*)[]` is implicitly convertible to `T(*)[]`. In any case, if U is an incomplete type, the program is ill-formed.
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | an object or array to delete |
### Exceptions
No exception guarantees.
### Invoking over Incomplete Types
At the point in the code the `operator()` is called, the type must be complete. In some implementations a `static_assert` is used to make sure this is the case. The reason for this requirement is that calling [delete](../language/delete "cpp/language/delete") on an incomplete type is undefined behavior in C++ if the complete class type has a nontrivial destructor or a deallocation function, as the compiler has no way of knowing whether such functions exist and must be invoked.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_constexpr_memory`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | `constexpr` constructor and `operator()` |
### Example
```
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
// {
// std::shared_ptr<int> shared_bad(new int[10]);
// } // the destructor calls delete, undefined behavior
{
std::shared_ptr<int> shared_good(new int[10], std::default_delete<int[]>());
} // the destructor calls delete[], ok
{
std::unique_ptr<int> ptr(new int(5));
} // unique_ptr<int> uses default_delete<int>
{
std::unique_ptr<int[]> ptr(new int[10]);
} // unique_ptr<int[]> uses default_delete<int[]>
// default_delete can be used anywhere a delete functor is needed
std::vector<int*> v;
for(int n = 0; n < 100; ++n)
v.push_back(new int(n));
std::for_each(v.begin(), v.end(), std::default_delete<int>());
}
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2118](https://cplusplus.github.io/LWG/issue2118) | C++11 | member functions of `default_delete<T[]>` rejected qualification conversions | accept |
### See also
| | |
| --- | --- |
| [unique\_ptr](unique_ptr "cpp/memory/unique ptr")
(C++11) | smart pointer with unique object ownership semantics (class template) |
cpp std::uninitialized_copy_n std::uninitialized\_copy\_n
===========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class InputIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( InputIt first, Size count, NoThrowForwardIt d_first );
```
| (1) | (since C++11) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( ExecutionPolicy&& policy, ForwardIt first, Size count,
NoThrowForwardIt d_first );
```
| (2) | (since C++17) |
1) Copies `count` elements from a range beginning at `first` to an uninitialized memory area beginning at `d_first` as if by
```
for ( ; n > 0; ++d_first, (void) ++first, --n)
::new (/*VOIDIFY*/(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of the elements to copy |
| count | - | the number of elements to copy |
| d\_first | - | the beginning of the destination range |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -`NoThrowForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `NoThrowForwardIt` may throw exceptions. |
### Return value
Iterator to the element past the last element copied.
### Complexity
Linear in `count`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class InputIt, class Size, class NoThrowForwardIt>
NoThrowForwardIt uninitialized_copy_n(InputIt first, Size count, NoThrowForwardIt d_first)
{
using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
NoThrowForwardIt current = d_first;
try {
for (; count > 0; ++first, (void) ++current, --count) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) T(*first);
}
} catch (...) {
for (; d_first != current; ++d_first) {
d_first->~T();
}
throw;
}
return current;
}
```
|
### Example
```
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
int main()
{
std::vector<std::string> v = {"This", "is", "an", "example"};
std::string* p;
std::size_t sz;
std::tie(p, sz) = std::get_temporary_buffer<std::string>(v.size());
sz = std::min(sz, v.size());
std::uninitialized_copy_n(v.begin(), sz, p);
for (std::string* i = p; i != p+sz; ++i) {
std::cout << *i << ' ';
i->~basic_string<char>();
}
std::return_temporary_buffer(p);
}
```
Output:
```
This is an example
```
### See also
| | |
| --- | --- |
| [uninitialized\_copy](uninitialized_copy "cpp/memory/uninitialized copy") | copies a range of objects to an uninitialized area of memory (function template) |
| [ranges::uninitialized\_copy\_n](ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n")
(C++20) | copies a number of objects to an uninitialized area of memory (niebloid) |
cpp Low level memory management Low level memory management
===========================
The [new-expression](../language/new "cpp/language/new") is the only way to create an object or an array of objects with dynamic storage duration, that is, with lifetime not restricted to the scope in which it is created. A new-expression obtains storage by calling an allocation function. A [delete-expression](../language/delete "cpp/language/delete") destroys a most derived object or an array created by a new-expression and calls the deallocation function. The default allocation and deallocation functions, along with related functions, types, and objects, are declared in the header [`<new>`](../header/new "cpp/header/new").
| Defined in header `[<new>](../header/new "cpp/header/new")` |
| --- |
| Functions |
| [operator newoperator new[]](new/operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [operator deleteoperator delete[]](new/operator_delete "cpp/memory/new/operator delete") | deallocation functions (function) |
| [get\_new\_handler](new/get_new_handler "cpp/memory/new/get new handler")
(C++11) | obtains the current new handler (function) |
| [set\_new\_handler](new/set_new_handler "cpp/memory/new/set new handler") | registers a new handler (function) |
| Classes |
| [bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc") | exception thrown when memory allocation fails (class) |
| [bad\_array\_new\_length](new/bad_array_new_length "cpp/memory/new/bad array new length")
(C++11) | exception thrown on allocation of array with invalid length (class) |
| [align\_val\_t](new/align_val_t "cpp/memory/new/align val t")
(C++17) | type used to pass alignment to alignment-aware allocation and deallocation functions (enum) |
| Types |
| [new\_handler](new/new_handler "cpp/memory/new/new handler") | function pointer type of the new handler (typedef) |
| Objects |
| [nothrow](new/nothrow "cpp/memory/new/nothrow") | an object of type `nothrow_t` used to select an non-throwing *allocation function* (constant) |
| [destroying\_delete](new/destroying_delete "cpp/memory/new/destroying delete")
(C++20) | an object of type destroying\_delete\_t used to select destroying-delete overloads of operator delete (constant) |
| Object access |
| [launder](../utility/launder "cpp/utility/launder")
(C++17) | pointer optimization barrier (function template) |
cpp std::uninitialized_fill_n std::uninitialized\_fill\_n
===========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class ForwardIt, class Size, class T >
void uninitialized_fill_n( ForwardIt first, Size count, const T& value );
```
| (until C++11) |
|
```
template< class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ForwardIt first, Size count, const T& value );
```
| (since C++11) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value );
```
| (2) | (since C++17) |
1) Copies the given value `value` to the first `count` elements in an uninitialized memory area beginning at `first` as if by
```
for (; n--; ++first)
::new (/*VOIDIFY*/(*first))
typename std::iterator_traits<ForwardIt>::value_type(value);
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static_cast<void*>(&e)` | (until C++11) |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (since C++11)(until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of the elements to initialize |
| count | - | number of elements to construct |
| value | - | the value to construct the elements with. |
| Type requirements |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `ForwardIt` may throw exceptions. Applying `&*` to a `ForwardIt` value must yield a pointer to its value type. (until C++11) |
### Return value
| | |
| --- | --- |
| (none). | (until C++11) |
| Iterator to the element past the last element copied. | (since C++11) |
### Complexity
Linear in `count`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template< class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n(ForwardIt first, Size count, const T& value)
{
using V = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; count > 0; ++current, (void) --count) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) V(value);
}
return current;
} catch (...) {
for (; first != current; ++first) {
first->~V();
}
throw;
}
}
```
|
### Example
```
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
int main()
{
std::string* p;
std::size_t sz;
std::tie(p, sz) = std::get_temporary_buffer<std::string>(4);
std::uninitialized_fill_n(p, sz, "Example");
for (std::string* i = p; i != p+sz; ++i) {
std::cout << *i << '\n';
i->~basic_string<char>();
}
std::return_temporary_buffer(p);
}
```
Output:
```
Example
Example
Example
Example
```
### See also
| | |
| --- | --- |
| [uninitialized\_fill](uninitialized_fill "cpp/memory/uninitialized fill") | copies an object to an uninitialized area of memory, defined by a range (function template) |
| [ranges::uninitialized\_fill\_n](ranges/uninitialized_fill_n "cpp/memory/ranges/uninitialized fill n")
(C++20) | copies an object to an uninitialized area of memory, defined by a start and a count (niebloid) |
| programming_docs |
cpp std::uninitialized_move std::uninitialized\_move
========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_move( InputIt first, InputIt last,
NoThrowForwardIt d_first );
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_move( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last,
NoThrowForwardIt d_first );
```
| (2) | (since C++17) |
1) Moves elements from the range `[first, last)` to an uninitialized memory area beginning at `d_first` as if by
```
for (; first != last; ++d_first, (void) ++first)
::new (/*VOIDIFY*/(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(std::move(*first));
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, some objects in `[first, last)` are left in a valid but unspecified state, and the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of the elements to move |
| d\_first | - | the beginning of the destination range |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -`NoThrowForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `NoThrowForwardIt` may throw exceptions. |
### Return value
Iterator to the element past the last element moved.
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class InputIt, class NoThrowForwardIt>
NoThrowForwardIt uninitialized_move(InputIt first, InputIt last, NoThrowForwardIt d_first)
{
using Value = typename std::iterator_traits<NoThrowForwardIt>::value_type;
NoThrowForwardIt current = d_first;
try {
for (; first != last; ++first, (void) ++current) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) Value(std::move(*first));
}
return current;
} catch (...) {
std::destroy(d_first, current);
throw;
}
}
```
|
### Example
```
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
void print(auto rem, auto first, auto last) {
for (std::cout << rem; first != last; ++first)
std::cout << std::quoted(*first) << ' ';
std::cout << '\n';
}
int main() {
std::string in[] { "Home", "Work!" };
print("initially, in: ", std::begin(in), std::end(in));
if (
constexpr auto sz = std::size(in);
void* out = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz)
) {
try {
auto first {static_cast<std::string*>(out)};
auto last {first + sz};
std::uninitialized_move(std::begin(in), std::end(in), first);
print("after move, in: ", std::begin(in), std::end(in));
print("after move, out: ", first, last);
std::destroy(first, last);
}
catch (...) {
std::cout << "Exception!\n";
}
std::free(out);
}
}
```
Possible output:
```
initially, in: "Home" "Work!"
after move, in: "" ""
after move, out: "Home" "Work!"
```
### See also
| | |
| --- | --- |
| [uninitialized\_copy](uninitialized_copy "cpp/memory/uninitialized copy") | copies a range of objects to an uninitialized area of memory (function template) |
| [uninitialized\_move\_n](uninitialized_move_n "cpp/memory/uninitialized move n")
(C++17) | moves a number of objects to an uninitialized area of memory (function template) |
| [ranges::uninitialized\_move](ranges/uninitialized_move "cpp/memory/ranges/uninitialized move")
(C++20) | moves a range of objects to an uninitialized area of memory (niebloid) |
cpp std::uninitialized_construct_using_allocator std::uninitialized\_construct\_using\_allocator
===============================================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc, class... Args >
constexpr T* uninitialized_construct_using_allocator( T* p, const Alloc& alloc, Args&&... args );
```
| | (since C++20) |
Creates an object of the given type `T` by means of [uses-allocator construction](uses_allocator "cpp/memory/uses allocator") at the uninitialized memory location indicated by p.
Equivalent to.
```
return std::apply([&]<class... Xs>(Xs&&...xs) {
return std::construct_at(p, std::forward<Xs>(xs)...);
}, std::uses_allocator_construction_args<T>(alloc, std::forward<Args>(args)...));
```
### Parameters
| | | |
| --- | --- | --- |
| p | - | the memory location where the object will be placed. |
| alloc | - | the allocator to use. |
| args | - | the arguments to pass to T's constructor |
### Return value
Pointer to the newly-created object of type `T`.
### Exceptions
May throw any exception thrown by the constructor of `T`, typically including `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")`.
### Example
### See also
| | |
| --- | --- |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
| [make\_obj\_using\_allocator](make_obj_using_allocator "cpp/memory/make obj using allocator")
(C++20) | creates an object of the given type by means of uses-allocator construction (function template) |
cpp std::pmr::memory_resource std::pmr::memory\_resource
==========================
| Defined in header `[<memory\_resource>](../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
class memory_resource;
```
| | (since C++17) |
The class `std::pmr::memory_resource` is an abstract interface to an unbounded set of classes encapsulating memory resources.
### Member functions
| | |
| --- | --- |
| [(constructor)](memory_resource/memory_resource "cpp/memory/memory resource/memory resource")
(implicitly declared) | constructs a new `memory_resource` (public member function) |
| (destructor)
[virtual] | destructs an `memory_resource` (virtual public member function) |
| operator=
(implicitly declared) | Implicitly declared copy assignment operator (public member function) |
| Public member functions |
| [allocate](memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function) |
| [deallocate](memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function) |
| [is\_equal](memory_resource/is_equal "cpp/memory/memory resource/is equal") | compare for equality with another `memory_resource` (public member function) |
| Private member functions |
| [do\_allocate](memory_resource/do_allocate "cpp/memory/memory resource/do allocate")
[virtual] | allocates memory (virtual private member function) |
| [do\_deallocate](memory_resource/do_deallocate "cpp/memory/memory resource/do deallocate")
[virtual] | deallocates memory (virtual private member function) |
| [do\_is\_equal](memory_resource/do_is_equal "cpp/memory/memory resource/do is equal")
[virtual] | compare for equality with another `memory_resource` (virtual private member function) |
### Non-member-functions
| | |
| --- | --- |
| [operator==operator!=](memory_resource/operator_eq "cpp/memory/memory resource/operator eq")
(removed in C++20) | compare two `memory_resource`s (function) |
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_memory_resource`](../feature_test#Library_features "cpp/feature test") |
cpp std::scoped_allocator_adaptor std::scoped\_allocator\_adaptor
===============================
| Defined in header `[<scoped\_allocator>](../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
template< class OuterAlloc, class... InnerAlloc >
class scoped_allocator_adaptor : public OuterAlloc;
```
| | (since C++11) |
The `std::scoped_allocator_adaptor` class template is an allocator which can be used with multilevel containers (vector of sets of lists of tuples of maps, etc). It is instantiated with one outer allocator type `OuterAlloc` and zero or more inner allocator types `InnerAlloc...`. A container constructed directly with a `scoped_allocator_adaptor` uses `OuterAlloc` to allocate its elements, but if an element is itself a container, it uses the first inner allocator. The elements of that container, if they are themselves containers, use the second inner allocator, etc. If there are more levels to the container than there are inner allocators, the last inner allocator is reused for all further nested containers.
The purpose of this adaptor is to correctly initialize stateful allocators in nested containers, such as when all levels of a nested container must be placed in the same shared memory segment. The adaptor's constructor takes the arguments for all allocators in the list, and each nested container obtains its allocator's state from the adaptor as needed.
For the purpose of `scoped_allocator_adaptor`, if the next inner allocator is `A`, any class `T` for which `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T,A>::value == true` participates in the recursion as if it was a container. Additionally, `[std::pair](../utility/pair "cpp/utility/pair")` is treated as such a container by specific overloads of [`scoped_allocator_adaptor::construct`](scoped_allocator_adaptor/construct "cpp/memory/scoped allocator adaptor/construct").
Typical implementation holds an instance of a `std::scoped_allocator_adaptor<InnerAllocs...>` as a member object.
### Member types
| Type | Definition |
| --- | --- |
| `outer_allocator_type` | `OuterAlloc` |
| `inner_allocator_type` | `scoped_allocator_adaptor<InnerAllocs...>` or, if `sizeof...(InnerAllocs) == 0`, `scoped_allocator_adaptor<OuterAlloc>` |
| `value_type` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::value\_type` |
| `size_type` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::size\_type` |
| `difference_type` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::difference\_type` |
| `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::pointer` |
| `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::const\_pointer` |
| `void_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::void\_pointer` |
| `const_void_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::const\_void\_pointer` |
| `propagate_on_container_copy_assignment` `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::propagate\_on\_container\_copy\_assignment::value` is `true` for at least one allocator `A` among `OuterAlloc` and `InnerAlloc...` |
| `propagate_on_container_move_assignment` `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::propagate\_on\_container\_move\_assignment::value` is `true` for at least one allocator `A` among `OuterAlloc` and `InnerAlloc...` |
| `propagate_on_container_swap` `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::propagate\_on\_container\_swap::value` is `true` for at least one allocator `A` among `OuterAlloc` and `InnerAlloc...` |
| `is_always_equal` `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::is\_always\_equal::value` is `true` for every allocator `A` among `OuterAlloc` and `InnerAlloc...` |
| `rebind`
```
template< class T >
struct rebind {
typedef scoped_allocator_adaptor<
std::allocator_traits<OuterAlloc>::template rebind_alloc<T>,
InnerAllocs...
> other;
};
```
|
### Member functions
| | |
| --- | --- |
| [(constructor)](scoped_allocator_adaptor/scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor/scoped allocator adaptor") | creates a new scoped\_allocator\_adaptor instance (public member function) |
| [(destructor)](scoped_allocator_adaptor/~scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor/~scoped allocator adaptor") | destructs a scoped\_allocator\_adaptor instance (public member function) |
| [operator=](scoped_allocator_adaptor/operator= "cpp/memory/scoped allocator adaptor/operator=") | assigns a `scoped_allocator_adaptor` (public member function) |
| [inner\_allocator](scoped_allocator_adaptor/inner_allocator "cpp/memory/scoped allocator adaptor/inner allocator") | obtains an `inner_allocator` reference (public member function) |
| [outer\_allocator](scoped_allocator_adaptor/outer_allocator "cpp/memory/scoped allocator adaptor/outer allocator") | obtains an `outer_allocator` reference (public member function) |
| [allocate](scoped_allocator_adaptor/allocate "cpp/memory/scoped allocator adaptor/allocate") | allocates uninitialized storage using the outer allocator (public member function) |
| [deallocate](scoped_allocator_adaptor/deallocate "cpp/memory/scoped allocator adaptor/deallocate") | deallocates storage using the outer allocator (public member function) |
| [max\_size](scoped_allocator_adaptor/max_size "cpp/memory/scoped allocator adaptor/max size") | returns the largest allocation size supported by the outer allocator (public member function) |
| [construct](scoped_allocator_adaptor/construct "cpp/memory/scoped allocator adaptor/construct") | constructs an object in allocated storage, passing the inner allocator to its constructor if appropriate (public member function) |
| [destroy](scoped_allocator_adaptor/destroy "cpp/memory/scoped allocator adaptor/destroy") | destructs an object in allocated storage (public member function) |
| [select\_on\_container\_copy\_construction](scoped_allocator_adaptor/select_on_container_copy_construction "cpp/memory/scoped allocator adaptor/select on container copy construction") | copies the state of scoped\_allocator\_adaptor and all its allocators (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](scoped_allocator_adaptor/operator_cmp "cpp/memory/scoped allocator adaptor/operator cmp")
(removed in C++20) | compares two scoped\_allocator\_adaptor instances (function template) |
### [Deduction guides](scoped_allocator_adaptor/deduction_guides "cpp/memory/scoped allocator adaptor/deduction guides")(since C++17)
### Example
```
#include <vector>
#include <scoped_allocator>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/adaptive_pool.hpp>
namespace bi = boost::interprocess;
template<class T> using alloc = bi::adaptive_pool<T,
bi::managed_shared_memory::segment_manager>;
using ipc_row = std::vector<int, alloc<int>>;
using ipc_matrix = std::vector<ipc_row, std::scoped_allocator_adaptor<alloc<ipc_row>>>;
int main ()
{
bi::managed_shared_memory s(bi::create_only, "Demo", 65536);
// create vector of vectors in shared memory
ipc_matrix v(s.get_segment_manager());
// for all these additions, the inner vectors obtain their allocator arguments
// from the outer vector's scoped_allocator_adaptor
v.resize(1); v[0].push_back(1);
v.emplace_back(2);
std::vector<int> local_row = {1,2,3};
v.emplace_back(local_row.begin(), local_row.end());
bi::shared_memory_object::remove("Demo");
}
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2108](https://cplusplus.github.io/LWG/issue2108) | C++11 | there was no way to show if `scoped_allocator_adaptor` is stateless | `is_always_equal` provided |
### See also
| | |
| --- | --- |
| [allocator\_traits](allocator_traits "cpp/memory/allocator traits")
(C++11) | provides information about allocator types (class template) |
| [uses\_allocator](uses_allocator "cpp/memory/uses allocator")
(C++11) | checks if the specified type supports uses-allocator construction (class template) |
| [allocator](allocator "cpp/memory/allocator") | the default allocator (class template) |
cpp std::uninitialized_move_n std::uninitialized\_move\_n
===========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class InputIt, class Size, class NoThrowForwardIt >
std::pair<InputIt, NoThrowForwardIt>
uninitialized_move_n( InputIt first, Size count, NoThrowForwardIt d_first );
```
| (1) | (since C++17) |
|
```
template< class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt >
std::pair<ForwardIt, NoThrowForwardIt>
uninitialized_move_n( ExecutionPolicy&& policy, ForwardIt first, Size count,
NoThrowForwardIt d_first );
```
| (2) | (since C++17) |
1) Moves `count` elements from a range beginning at `first` to an uninitialized memory area beginning at `d_first` as if by
```
for ( ; n > 0; ++d_first, (void) ++first, --n)
::new (/*VOIDIFY*/(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(std::move(*first));
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, some objects in the source range are left in a valid but unspecified state, and the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of the elements to move |
| d\_first | - | the beginning of the destination range |
| count | - | the number of elements to move |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -`NoThrowForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `NoThrowForwardIt` may throw exceptions. |
### Return value
A pair whose first element is an iterator to the element past the last element moved in the source range, and whose second element is an iterator to the element past the last element moved in the destination range.
### Complexity
Linear in `count`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class InputIt, class Size, class NoThrowForwardIt>
std::pair<InputIt, NoThrowForwardIt>
uninitialized_move_n(InputIt first, Size count, NoThrowForwardIt d_first)
{
using Value = typename std::iterator_traits<NoThrowForwardIt>::value_type;
NoThrowForwardIt current = d_first;
try {
for (; count > 0; ++first, (void) ++current, --count) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) Value(std::move(*first));
}
} catch (...) {
std::destroy(d_first, current);
throw;
}
return {first, current};
}
```
|
### Example
```
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
void print(auto rem, auto first, auto last) {
for (std::cout << rem; first != last; ++first)
std::cout << std::quoted(*first) << ' ';
std::cout << '\n';
}
int main() {
std::string in[] { "One", "Definition", "Rule" };
print("initially, in: ", std::begin(in), std::end(in));
if (
constexpr auto sz = std::size(in);
void* out = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz)
) {
try {
auto first {static_cast<std::string*>(out)};
auto last {first + sz};
std::uninitialized_move_n(std::begin(in), sz, first);
print("after move, in: ", std::begin(in), std::end(in));
print("after move, out: ", first, last);
std::destroy(first, last);
}
catch (...) {
std::cout << "Exception!\n";
}
std::free(out);
}
}
```
Possible output:
```
initially, in: "One" "Definition" "Rule"
after move, in: "" "" ""
after move, out: "One" "Definition" "Rule"
```
### See also
| | |
| --- | --- |
| [uninitialized\_move](uninitialized_move "cpp/memory/uninitialized move")
(C++17) | moves a range of objects to an uninitialized area of memory (function template) |
| [uninitialized\_copy\_n](uninitialized_copy_n "cpp/memory/uninitialized copy n")
(C++11) | copies a number of objects to an uninitialized area of memory (function template) |
| [ranges::uninitialized\_move\_n](ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n")
(C++20) | moves a number of objects to an uninitialized area of memory (niebloid) |
| programming_docs |
cpp std::uninitialized_copy std::uninitialized\_copy
========================
| Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt first, InputIt last,
NoThrowForwardIt d_first );
```
| (1) | |
|
```
template< class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last,
NoThrowForwardIt d_first );
```
| (2) | (since C++17) |
1) Copies elements from the range `[first, last)` to an uninitialized memory area beginning at `d_first` as if by
```
for (; first != last; ++d_first, (void) ++first)
::new (/*VOIDIFY*/(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
```
where `/*VOIDIFY*/(e)` is:
| | |
| --- | --- |
| `static_cast<void*>(&e)` | (until C++11) |
| `static\_cast<void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e))` | (since C++11)(until C++20) |
| `const\_cast<void\*>(static\_cast<const volatile void\*>([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(e)))` | (since C++20) |
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of the elements to copy |
| d\_first | - | the beginning of the destination range |
| policy | - | the execution policy to use. See [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
| -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -`NoThrowForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). |
| -No increment, assignment, comparison, or indirection through valid instances of `NoThrowForwardIt` may throw exceptions. Applying `&*` to a `NoThrowForwardIt` value must yield a pointer to its value type. (until C++11) |
### Return value
Iterator to the element past the last element copied.
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The overload with a template parameter named `ExecutionPolicy` reports errors as follows:
* If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
* If the algorithm fails to allocate memory, `[std::bad\_alloc](new/bad_alloc "cpp/memory/new/bad alloc")` is thrown.
### Possible implementation
| |
| --- |
|
```
template<class InputIt, class NoThrowForwardIt>
NoThrowForwardIt uninitialized_copy(InputIt first, InputIt last, NoThrowForwardIt d_first)
{
using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
NoThrowForwardIt current = d_first;
try {
for (; first != last; ++first, (void) ++current) {
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) T(*first);
}
return current;
} catch (...) {
for (; d_first != current; ++d_first) {
d_first->~T();
}
throw;
}
}
```
|
### Example
```
#include <iostream>
#include <memory>
#include <cstdlib>
#include <string>
int main()
{
const char *v[] = {"This", "is", "an", "example"};
auto sz = std::size(v);
if(void *pbuf = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz))
{
try
{
auto first = static_cast<std::string*>(pbuf);
auto last = std::uninitialized_copy(std::begin(v), std::end(v), first);
for (auto it = first; it != last; ++it)
std::cout << *it << '_';
std::cout << '\n';
std::destroy(first, last);
}
catch(...) {}
std::free(pbuf);
}
}
```
Output:
```
This_is_an_example_
```
### See also
| | |
| --- | --- |
| [uninitialized\_copy\_n](uninitialized_copy_n "cpp/memory/uninitialized copy n")
(C++11) | copies a number of objects to an uninitialized area of memory (function template) |
| [ranges::uninitialized\_copy](ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy")
(C++20) | copies a range of objects to an uninitialized area of memory (niebloid) |
cpp std::pmr::monotonic_buffer_resource::~monotonic_buffer_resource std::pmr::monotonic\_buffer\_resource::~monotonic\_buffer\_resource
===================================================================
| | | |
| --- | --- | --- |
|
```
virtual ~monotonic_buffer_resource();
```
| | (since C++17) |
Destroys a `monotonic_buffer_resource`.
Deallocates all memory owned by this resource by calling `this->release()`.
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/monotonic buffer resource/release") | Release all allocated memory (public member function) |
cpp std::pmr::monotonic_buffer_resource::do_deallocate std::pmr::monotonic\_buffer\_resource::do\_deallocate
=====================================================
| | | |
| --- | --- | --- |
|
```
virtual void do_deallocate( void* p, std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
This function has no effect. Memory used by a [`monotonic_buffer_resource`](../monotonic_buffer_resource "cpp/memory/monotonic buffer resource"), as its name indicates, increases monotonically until the resource is destroyed.
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_deallocate](../memory_resource/do_deallocate "cpp/memory/memory resource/do deallocate")
[virtual] | deallocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::monotonic_buffer_resource::release std::pmr::monotonic\_buffer\_resource::release
==============================================
| | | |
| --- | --- | --- |
|
```
void release();
```
| | (since C++17) |
Releases all allocated memory by calling the `deallocate` function on the upstream memory resource as necessary. Resets *current buffer* and *next buffer size* to their initial values at construction.
Memory is released back to the upstream resource even if `deallocate` has not been called for some of the allocated blocks.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3120](https://cplusplus.github.io/LWG/issue3120) | C++17 | `release` might not make initial buffer reusable if provided | required to do so |
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::monotonic_buffer_resource::monotonic_buffer_resource std::pmr::monotonic\_buffer\_resource::monotonic\_buffer\_resource
==================================================================
| | | |
| --- | --- | --- |
|
```
monotonic_buffer_resource();
```
| (1) | (since C++17) |
|
```
explicit monotonic_buffer_resource( std::pmr::memory_resource* upstream );
```
| (2) | (since C++17) |
|
```
explicit monotonic_buffer_resource( std::size_t initial_size );
```
| (3) | (since C++17) |
|
```
monotonic_buffer_resource( std::size_t initial_size,
std::pmr::memory_resource* upstream );
```
| (4) | (since C++17) |
|
```
monotonic_buffer_resource( void* buffer, std::size_t buffer_size );
```
| (5) | (since C++17) |
|
```
monotonic_buffer_resource( void* buffer, std::size_t buffer_size,
std::pmr::memory_resource* upstream );
```
| (6) | (since C++17) |
|
```
monotonic_buffer_resource( const monotonic_buffer_resource& ) = delete;
```
| (7) | (since C++17) |
Constructs a [`monotonic_buffer_resource`](../monotonic_buffer_resource "cpp/memory/monotonic buffer resource"). The constructors not taking an upstream memory resource pointer use the return value of `[std::pmr::get\_default\_resource](../get_default_resource "cpp/memory/get default resource")` as the upstream memory resource.
1-2) Sets the *current buffer* to null and the *next buffer size* to an implementation-defined size.
3-4) Sets the *current buffer* to null and the *next buffer size* to a size no smaller than `initial_size`.
5-6) Sets the *current buffer* to `buffer` and the *next buffer size* to `buffer_size` (but not less than 1). Then increase the *next buffer size* by an implementation-defined growth factor (which does not have to be integral).
7) Copy constructor is deleted. ### Parameters
| | | |
| --- | --- | --- |
| upstream | - | the upstream memory resource to use; must point to a valid memory resource |
| initial\_size | - | the minimum size of the first buffer to allocate; must be greater than zero |
| buffer | - | the initial buffer to use |
| buffer\_size | - | the size of the initial buffer; cannot be greater than the number of bytes in `buffer` |
cpp std::pmr::monotonic_buffer_resource::do_allocate std::pmr::monotonic\_buffer\_resource::do\_allocate
===================================================
| | | |
| --- | --- | --- |
|
```
virtual void* do_allocate( std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
Allocates storage.
If the *current buffer* has sufficient unused space to fit a block with the specified size and alignment, allocates the return block from the current buffer.
Otherwise, this function allocates a new buffer by calling `upstream_resource()->allocate(n, m)`, where `n` is not less than the greater of `bytes` and the *next buffer size* and `m` is not less than `alignment`. It sets the new buffer as the *current buffer*, increases the *next buffer size* by an implementation-defined growth factor (which is not necessarily integral), and then allocates the return block from the newly allocated buffer.
### Return value
A pointer to allocated storage of at least `bytes` bytes in size, aligned to the specified `alignment` if such alignment is supported, and to `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))` otherwise.
### Exceptions
Throws nothing unless calling `allocate()` on the upstream memory resource throws.
### See also
| | |
| --- | --- |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_allocate](../memory_resource/do_allocate "cpp/memory/memory resource/do allocate")
[virtual] | allocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::monotonic_buffer_resource::do_is_equal std::pmr::monotonic\_buffer\_resource::do\_is\_equal
====================================================
| | | |
| --- | --- | --- |
|
```
virtual bool do_is_equal( const std::pmr::memory_resource& other ) const noexcept;
```
| | (since C++17) |
Compare `*this` with `other` for identity - memory allocated using a [`monotonic_buffer_resource`](../monotonic_buffer_resource "cpp/memory/monotonic buffer resource") can only be deallocated using that same resource.
### Return value
`this == &other`.
### Defect report
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3000](https://cplusplus.github.io/LWG/issue3000) | C++17 | unnecessary `dynamic_cast` was performed | removed |
### See also
| | |
| --- | --- |
| [do\_is\_equal](../memory_resource/do_is_equal "cpp/memory/memory resource/do is equal")
[virtual] | compare for equality with another `memory_resource` (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::monotonic_buffer_resource::upstream_resource std::pmr::monotonic\_buffer\_resource::upstream\_resource
=========================================================
| | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* upstream_resource() const;
```
| | (since C++17) |
Returns a pointer to the upstream memory resource. This is the same value as the `upstream` argument passed to the constructor of this object.
### See also
| | |
| --- | --- |
| [(constructor)](monotonic_buffer_resource "cpp/memory/monotonic buffer resource/monotonic buffer resource") | Constructs a `monotonic_buffer_resource` (public member function) |
cpp
no-throw-input-iterator, no-throw-forward-iterator, no-throw-sentinel-for, no-throw-input-range, no-throw-forward-range
*no-throw-input-iterator*, *no-throw-forward-iterator*, *no-throw-sentinel-for*, *no-throw-input-range*, *no-throw-forward-range*
==================================================================================================================================
| | | |
| --- | --- | --- |
|
```
template<class I>
concept no-throw-input-iterator = // exposition only
std::input_iterator<I> &&
std::is_lvalue_reference_v<std::iter_reference_t<I>> &&
std::same_as<std::remove_cvref_t<std::iter_reference_t<I>>, std::iter_value_t<I>>;
```
| (1) | (since C++20) |
|
```
template<class I>
concept no-throw-forward-iterator = // exposition only
no-throw-input-iterator<I> &&
std::forward_iterator<I> &&
no-throw-sentinel-for<I, I>;
```
| (2) | (since C++20) |
|
```
template<class S, class I>
concept no-throw-sentinel-for = std::sentinel_for<S, I>; // exposition only
```
| (3) | (since C++20) |
|
```
template<class R>
concept no-throw-input-range = // exposition only
ranges::range<R> &&
no-throw-input-iterator<ranges::iterator_t<R>> &&
no-throw-sentinel-for<ranges::sentinel_t<R>, ranges::iterator_t<R>>;
```
| (4) | (since C++20) |
|
```
template<class R>
concept no-throw-forward-range = // exposition only
no-throw-input-range<R> &&
no-throw-forward-iterator<ranges::iterator_t<R>>;
```
| (5) | (since C++20) |
These exposition-only concepts specify that no exceptions are thrown from operations required by algorithms on iterators, sentinels, and ranges.
1) The `*no-throw-input-iterator*` concept requires that dereferencing the iterator yields an lvalue, like [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). ### Semantic requirements
Like all standard concepts, every concept listed here is modeled only if all concepts it subsumes are modeled.
1) A type `I` models `*no-throw-input-iterator*` only if no exceptions are thrown from increment, copy construction, move construction, copy assignment, move assignment, or indirection through valid iterators.
3) Types `S` and `I` model `*no-throw-sentinel-for*` only if no exceptions are thrown from copy construction, move construction, copy assignment, move assignment, or comparisons between valid values of type `I` and `S`.
4) A type `R` models `*no-throw-input-range*` only if no exceptions are thrown from calls to `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)` on an object of type `R`. ### Notes
These concepts allow some operations on iterators and sentinels to throw exceptions, e.g. operations on invalid values.
### See also
| | |
| --- | --- |
| [input\_iterator](../../iterator/input_iterator "cpp/iterator/input iterator")
(C++20) | specifies that a type is an input iterator, that is, its referenced values can be read and it can be both pre- and post-incremented (concept) |
| [forward\_iterator](../../iterator/forward_iterator "cpp/iterator/forward iterator")
(C++20) | specifies that an [`input_iterator`](../../iterator/input_iterator "cpp/iterator/input iterator") is a forward iterator, supporting equality comparison and multi-pass (concept) |
| [sentinel\_for](../../iterator/sentinel_for "cpp/iterator/sentinel for")
(C++20) | specifies a type is a sentinel for an [`input_or_output_iterator`](../../iterator/input_or_output_iterator "cpp/iterator/input or output iterator") type (concept) |
| [ranges::input\_range](../../ranges/input_range "cpp/ranges/input range")
(C++20) | specifies a range whose iterator type satisfies [`input_iterator`](../../iterator/input_iterator "cpp/iterator/input iterator") (concept) |
| [ranges::forward\_range](../../ranges/forward_range "cpp/ranges/forward range")
(C++20) | specifies a range whose iterator type satisfies [`forward_iterator`](../../iterator/forward_iterator "cpp/iterator/forward iterator") (concept) |
cpp std::ranges::uninitialized_fill std::ranges::uninitialized\_fill
================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< no-throw-forward-iterator I, no-throw-sentinel-for<I> S, class T >
requires std::constructible_from<std::iter_value_t<I>, const T&>
I uninitialized_fill( I first, S last, const T& x );
```
| (1) | (since C++20) |
|
```
template< no-throw-forward-range R, class T >
requires std::constructible_from<ranges::range_value_t<R>, const T&>
ranges::borrowed_iterator_t<R>
uninitialized_fill( R&& r, const T& x );
```
| (2) | (since C++20) |
1) Constructs \(\scriptsize N\)N copies of the given value `x` in an uninitialized memory area, designated by the range `[first, last)`, where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`.
The function has the effect equivalent to:
```
for (; first != last; ++first) {
::new (
const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first)))
) std::remove_reference_t<std::iter_reference_t<I>>(x);
}
return first;
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first, last | - | iterator-sentinel pair denoting the range of elements to initialize |
| r | - | the range of the elements to initialize |
| value | - | the value to construct the elements with |
### Return value
An iterator equal to `last`.
### Complexity
\(\scriptsize\mathcal{O}(N)\)𝓞(N).
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_fill`, e.g. by using `[ranges::fill](../../algorithm/ranges/fill "cpp/algorithm/ranges/fill")`, if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_fill_fn {
template <no-throw-forward-iterator I, no-throw-sentinel-for<I> S, class T>
requires std::constructible_from<std::iter_value_t<I>, const T&>
I operator()( I first, S last, const T& x ) const {
I rollback {first};
try {
for (; !(first == last); ++first)
ranges::construct_at(std::addressof(*first), x);
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
template <no-throw-forward-range R, class T>
requires std::constructible_from<ranges::range_value_t<R>, const T&>
ranges::borrowed_iterator_t<R>
operator()( R&& r, const T& x ) const {
return (*this)(ranges::begin(r), ranges::end(r), x);
}
};
inline constexpr uninitialized_fill_fn uninitialized_fill{};
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
constexpr int n {4};
alignas(alignof(std::string)) char out[n * sizeof(std::string)];
try
{
auto first {reinterpret_cast<std::string*>(out)};
auto last {first + n};
std::ranges::uninitialized_fill(first, last, "▄▀▄▀▄▀▄▀");
int count {1};
for (auto it {first}; it != last; ++it) {
std::cout << count++ << ' ' << *it << '\n';
}
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
}
```
Output:
```
1 ▄▀▄▀▄▀▄▀
2 ▄▀▄▀▄▀▄▀
3 ▄▀▄▀▄▀▄▀
4 ▄▀▄▀▄▀▄▀
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_fill\_n](uninitialized_fill_n "cpp/memory/ranges/uninitialized fill n")
(C++20) | copies an object to an uninitialized area of memory, defined by a start and a count (niebloid) |
| [uninitialized\_fill](../uninitialized_fill "cpp/memory/uninitialized fill") | copies an object to an uninitialized area of memory, defined by a range (function template) |
| programming_docs |
cpp std::ranges::uninitialized_default_construct std::ranges::uninitialized\_default\_construct
==============================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_default_construct( I first, S last );
```
| (1) | (since C++20) |
|
```
template <no-throw-forward-range R>
requires std::default_initializable<ranges::range_value_t<R>>
ranges::borrowed_iterator_t<R>
uninitialized_default_construct( R&& r );
```
| (2) | (since C++20) |
1) Constructs objects of type `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` in the uninitialized storage designated by the range `[first, last)` by [default-initialization](../../language/default_initialization "cpp/language/default initialization"), as if by
```
for (; first != last; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<I>>;
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first, last | - | iterator-sentinel pair denoting the range of the elements to initialize |
| r | - | the range of the elements to initialize |
### Return value
An iterator equal to `last`.
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may skip the objects construction (without changing the observable effect) if no non-trivial default constructor is called while default-initializing a `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` object, which can be detected by `[std::is\_trivially\_default\_constructible\_v](../../types/is_default_constructible "cpp/types/is default constructible")`.
### Possible implementation
| |
| --- |
|
```
struct uninitialized_default_construct_fn {
template <no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
requires std::default_initializable<std::iter_value_t<I>>
I operator()( I first, S last ) const {
using ValueType = std::remove_reference_t<std::iter_reference_t<I>>;
if constexpr (std::is_trivially_default_constructible_v<ValueType>)
return ranges::next(first, last); // skip initialization
I rollback {first};
try {
for (; !(first == last); ++first)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*first)))) ValueType;
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
template <no-throw-forward-range R>
requires std::default_initializable<ranges::range_value_t<R>>
ranges::borrowed_iterator_t<R>
operator()( R&& r ) const {
return (*this)(ranges::begin(r), ranges::end(r));
}
};
inline constexpr uninitialized_default_construct_fn uninitialized_default_construct{};
```
|
### Example
```
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "▄▀▄▀▄▀▄▀" }; };
constexpr int n {4};
alignas(alignof(S)) char out[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(out)};
auto last {first + n};
std::ranges::uninitialized_default_construct(first, last);
auto count {1};
for (auto it {first}; it != last; ++it) {
std::cout << count++ << ' ' << it->m << '\n';
}
std::ranges::destroy(first, last);
}
catch(...) { std::cout << "Exception!\n"; }
// Notice that for "trivial types" the uninitialized_default_construct
// generally does not zero-fill the given uninitialized memory area.
constexpr char etalon[] { 'A', 'B', 'C', 'D', '\n' };
char v[] { 'A', 'B', 'C', 'D', '\n' };
std::ranges::uninitialized_default_construct(std::begin(v), std::end(v));
if (std::memcmp(v, etalon, sizeof(v)) == 0) {
std::cout << " ";
// Maybe undefined behavior, pending CWG 1997:
// for (const char c : v) { std::cout << c << ' '; }
for (const char c : etalon) { std::cout << c << ' '; }
} else {
std::cout << "Unspecified\n";
}
}
```
Possible output:
```
1 ▄▀▄▀▄▀▄▀
2 ▄▀▄▀▄▀▄▀
3 ▄▀▄▀▄▀▄▀
4 ▄▀▄▀▄▀▄▀
A B C D
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_default\_construct\_n](uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) |
| [ranges::uninitialized\_value\_construct](uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_value\_construct\_n](uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) |
| [uninitialized\_default\_construct](../uninitialized_default_construct "cpp/memory/uninitialized default construct")
(C++17) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (function template) |
cpp std::ranges::uninitialized_value_construct_n std::ranges::uninitialized\_value\_construct\_n
===============================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <no-throw-forward-iterator I>
requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_value_construct_n( I first, std::iter_difference_t<I> n );
```
| | (since C++20) |
Constructs `n` objects of type `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` in the uninitialized memory area starting at `first` by [value-initialization](../../language/value_initialization "cpp/language/value initialization"), as if by.
```
for (; n-- > 0; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<I>>();
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to initialize |
| n | - | the number of elements to construct |
### Return value
The end of the range of objects (i.e., `[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(first, n)`).
### Complexity
Linear in `n`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_value_construct_n`, e.g. by using `[ranges::fill\_n](../../algorithm/ranges/fill_n "cpp/algorithm/ranges/fill n")`, if the value type of the range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType") *and* [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_value_construct_n_fn {
template <no-throw-forward-iterator I>
requires std::default_initializable<std::iter_value_t<I>>
I operator()( I first, std::iter_difference_t<I> n ) const {
using T = std::remove_reference_t<std::iter_reference_t<I>>;
if constexpr (std::is_trivial_v<T> && std::is_copy_assignable_v<T>)
return ranges::fill_n(first, n, T());
I rollback {first};
try {
for (; n-- > 0; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*first)))) T();
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
};
inline constexpr uninitialized_value_construct_n_fn uninitialized_value_construct_n{};
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "█▓▒░ █▓▒░ █▓▒░ " }; };
constexpr int n {4};
alignas(alignof(S)) char out[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(out)};
auto last = std::ranges::uninitialized_value_construct_n(first, n);
auto count {1};
for (auto it {first}; it != last; ++it) {
std::cout << count++ << ' ' << it->m << '\n';
}
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_value_construct_n
// zero-initializes the given uninitialized memory area.
int v[] { 1, 2, 3, 4, 5, 6, 7, 8 };
std::cout << ' ';
for (const int i : v) { std::cout << i << ' '; }
std::cout << "\n ";
std::ranges::uninitialized_value_construct_n(std::begin(v), std::size(v));
for (const int i : v) { std::cout << i << ' '; }
std::cout << '\n';
}
```
Output:
```
1 █▓▒░ █▓▒░ █▓▒░
2 █▓▒░ █▓▒░ █▓▒░
3 █▓▒░ █▓▒░ █▓▒░
4 █▓▒░ █▓▒░ █▓▒░
1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_value\_construct](uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_default\_construct](uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_default\_construct\_n](uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) |
| [uninitialized\_value\_construct\_n](../uninitialized_value_construct_n "cpp/memory/uninitialized value construct n")
(C++17) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
cpp std::ranges::destroy_n std::ranges::destroy\_n
=======================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< no-throw-input-iterator I >
requires std::destructible<std::iter_value_t<I>>
constexpr I destroy_n( I first, std::iter_difference_t<I> n ) noexcept;
```
| | (since C++20) |
Destroys the `n` objects in the range starting at `first`, equivalent to.
```
return std::ranges::destroy(std::counted_iterator(first, n), std::default_sentinel).base();
```
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to destroy |
| n | - | the number of elements to destroy |
### Return value
The end of the range of objects that has been destroyed.
### Complexity
Linear in `n`.
### Possible implementation
| |
| --- |
|
```
struct destroy_n_fn {
template<no-throw-input-iterator I>
requires std::destructible<std::iter_value_t<I>>
constexpr I operator()(I first, std::iter_difference_t<I> n) const noexcept
{
for (; n != 0; (void)++first, --n)
std::ranges::destroy_at(std::addressof(*first));
return first;
}
};
inline constexpr destroy_n_fn destroy_n{};
```
|
### Example
The following example demonstrates how to use `ranges::destroy_n` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
std::ranges::destroy_n(ptr, 8);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [ranges::destroy\_at](destroy_at "cpp/memory/ranges/destroy at")
(C++20) | destroys an object at a given address (niebloid) |
| [ranges::destroy](destroy "cpp/memory/ranges/destroy")
(C++20) | destroys a range of objects (niebloid) |
| [destroy\_n](../destroy_n "cpp/memory/destroy n")
(C++17) | destroys a number of objects in a range (function template) |
cpp std::ranges::uninitialized_default_construct_n std::ranges::uninitialized\_default\_construct\_n
=================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <no-throw-forward-iterator I>
requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_default_construct_n( I first, std::iter_difference_t<I> n );
```
| | (since C++20) |
Constructs `n` objects of type `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` in the uninitialized memory area starting at `first` by [default-initialization](../../language/default_initialization "cpp/language/default initialization"), as if by.
```
for (; n-- > 0; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<I>>;
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of elements to initialize |
| n | - | the number of elements to construct |
### Return value
The end of the range of objects (i.e., `[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(first, n)`).
### Complexity
Linear in `n`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may skip the objects construction (without changing the observable effect) if no non-trivial default constructor is called while default-initializing a `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` object, which can be detected by `[std::is\_trivially\_default\_constructible\_v](../../types/is_default_constructible "cpp/types/is default constructible")`.
### Possible implementation
| |
| --- |
|
```
struct uninitialized_default_construct_n_fn {
template <no-throw-forward-iterator I>
requires std::default_initializable<std::iter_value_t<I>>
I operator()( I first, std::iter_difference_t<I> n ) const {
using ValueType = std::remove_reference_t<std::iter_reference_t<I>>;
if constexpr (std::is_trivially_default_constructible_v<ValueType>)
return ranges::next(first, n); // skip initialization
I rollback {first};
try {
for (; n-- > 0; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*first)))) ValueType;
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
};
inline constexpr uninitialized_default_construct_n_fn uninitialized_default_construct_n{};
```
|
### Example
```
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "█▓▒░ █▓▒░ " }; };
constexpr int n {4};
alignas(alignof(S)) char out[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(out)};
auto last = std::ranges::uninitialized_default_construct_n(first, n);
auto count {1};
for (auto it {first}; it != last; ++it) {
std::cout << count++ << ' ' << it->m << '\n';
}
std::ranges::destroy(first, last);
}
catch(...) { std::cout << "Exception!\n"; }
// Notice that for "trivial types" the uninitialized_default_construct_n
// generally does not zero-fill the given uninitialized memory area.
constexpr int etalon[] { 1, 2, 3, 4, 5, 6 };
int v[] { 1, 2, 3, 4, 5, 6 };
std::ranges::uninitialized_default_construct_n(std::begin(v), std::size(v));
if (std::memcmp(v, etalon, sizeof(v)) == 0) {
// Maybe undefined behavior, pending CWG 1997:
// for (const int i : v) { std::cout << i << ' '; }
for (const int i : etalon) { std::cout << i << ' '; }
} else {
std::cout << "Unspecified!";
}
std::cout << '\n';
}
```
Possible output:
```
1 █▓▒░ █▓▒░
2 █▓▒░ █▓▒░
3 █▓▒░ █▓▒░
4 █▓▒░ █▓▒░
1 2 3 4 5 6
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_default\_construct](uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_value\_construct](uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_value\_construct\_n](uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) |
| [uninitialized\_default\_construct\_n](../uninitialized_default_construct_n "cpp/memory/uninitialized default construct n")
(C++17) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and a count (function template) |
| programming_docs |
cpp std::ranges::construct_at std::ranges::construct\_at
==========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< class T, class... Args >
constexpr T* construct_at( T* p, Args&&... args );
```
| | (since C++20) |
Creates a `T` object initialized with arguments `args...` at given address `p`. `construct_at` participates in overload resolution only if `::new([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<void\*>()) T([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...)` is well-formed in unevaluated context.
Equivalent to.
```
return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
T(std::forward<Args>(args)...);
```
except that `construct_at` may be used in evaluation of [constant expressions](../../language/constant_expression "cpp/language/constant expression").
When `construct_at` is called in the evaluation of some constant expression `e`, the argument `p` must point to either storage obtained by `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>::allocate` or an object whose lifetime began within the evaluation of `e`.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the uninitialized storage on which a `T` object will be constructed |
| args... | - | arguments used for initialization |
### Return value
`p`.
### Possible implementation
| |
| --- |
|
```
struct construct_at_fn {
template<class T, class...Args>
requires
requires (void* vp, Args&&... args) { ::new (vp) T(static_cast<Args&&>(args)...); }
constexpr T* operator()(T* p, Args&&... args) const
{
return std::construct_at(p, static_cast<Args&&>(args)...);
}
};
inline constexpr construct_at_fn construct_at{};
```
|
### Notes
`std::ranges::construct_at` behaves exactly same as `[std::construct\_at](../construct_at "cpp/memory/construct at")`, except that it is invisible to argument-dependent lookup.
### Example
```
#include <iostream>
#include <memory>
struct S {
int x;
float y;
double z;
S(int x, float y, double z) : x{x}, y{y}, z{z} { std::cout << "S::S();\n"; }
~S() { std::cout << "S::~S();\n"; }
void print() const {
std::cout << "S { x=" << x << "; y=" << y << "; z=" << z << "; };\n";
}
};
int main()
{
alignas(S) unsigned char buf[sizeof(S)];
S* ptr = std::ranges::construct_at(reinterpret_cast<S*>(buf), 42, 2.71828f, 3.1415);
ptr->print();
std::ranges::destroy_at(ptr);
}
```
Output:
```
S::S();
S { x=42; y=2.71828; z=3.1415; };
S::~S();
```
### See also
| | |
| --- | --- |
| [ranges::destroy\_at](destroy_at "cpp/memory/ranges/destroy at")
(C++20) | destroys an object at a given address (niebloid) |
| [construct\_at](../construct_at "cpp/memory/construct at")
(C++20) | creates an object at a given address (function template) |
cpp std::ranges::uninitialized_value_construct std::ranges::uninitialized\_value\_construct
============================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_value_construct( I first, S last );
```
| (1) | (since C++20) |
|
```
template <no-throw-forward-range R>
requires std::default_initializable<ranges::range_value_t<R>>
ranges::borrowed_iterator_t<R>
uninitialized_value_construct( R&& r );
```
| (2) | (since C++20) |
1) Constructs objects of type `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` in the uninitialized storage designated by the range `[first, last)` by [value-initialization](../../language/value_initialization "cpp/language/value initialization"), as if by
```
for (; first != last; ++first)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<I>>();
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first, last | - | iterator-sentinel pair denoting the range of elements to value-initialize |
| r | - | the range of the elements to value-initialize |
### Return value
An iterator equal to `last`.
### Complexity
Linear in the distance between `first` and `last`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_value_construct`, e.g. by using `[ranges::fill](../../algorithm/ranges/fill "cpp/algorithm/ranges/fill")`, if the value type of the range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType") *and* [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_value_construct_fn {
template <no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
requires std::default_initializable<std::iter_value_t<I>>
I operator()( I first, S last ) const {
using T = std::remove_reference_t<std::iter_reference_t<I>>;
if constexpr (std::is_trivial_v<T> && std::is_copy_assignable_v<T>)
return ranges::fill(first, last, T());
I rollback {first};
try {
for (; !(first == last); ++first)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*first)))) T();
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
template <no-throw-forward-range R>
requires std::default_initializable<ranges::range_value_t<R>>
ranges::borrowed_iterator_t<R>
operator()( R&& r ) const {
return (*this)(ranges::begin(r), ranges::end(r));
}
};
inline constexpr uninitialized_value_construct_fn uninitialized_value_construct{};
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{ "▄▀▄▀▄▀▄▀" }; };
constexpr int n {4};
alignas(alignof(S)) char out[n * sizeof(S)];
try
{
auto first {reinterpret_cast<S*>(out)};
auto last {first + n};
std::ranges::uninitialized_value_construct(first, last);
auto count {1};
for (auto it {first}; it != last; ++it) {
std::cout << count++ << ' ' << it->m << '\n';
}
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
// Notice that for "trivial types" the uninitialized_value_construct
// zero-fills the given uninitialized memory area.
int v[] { 0, 1, 2, 3 };
std::cout << ' ';
for (const int i : v) { std::cout << ' ' << static_cast<char>(i + 'A'); }
std::cout << "\n ";
std::ranges::uninitialized_value_construct(std::begin(v), std::end(v));
for (const int i : v) { std::cout << ' ' << static_cast<char>(i + 'A'); }
std::cout << '\n';
}
```
Output:
```
1 ▄▀▄▀▄▀▄▀
2 ▄▀▄▀▄▀▄▀
3 ▄▀▄▀▄▀▄▀
4 ▄▀▄▀▄▀▄▀
A B C D
A A A A
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_value\_construct\_n](uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n")
(C++20) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) |
| [ranges::uninitialized\_default\_construct](uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) |
| [ranges::uninitialized\_default\_construct\_n](uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n")
(C++20) | constructs objects by [default-initialization](../../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) |
| [uninitialized\_value\_construct](../uninitialized_value_construct "cpp/memory/uninitialized value construct")
(C++17) | constructs objects by [value-initialization](../../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (function template) |
cpp std::ranges::destroy std::ranges::destroy
====================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< no-throw-input-iterator I, no-throw-sentinel-for<I> S >
requires std::destructible<std::iter_value_t<I>>
constexpr I destroy( I first, S last ) noexcept;
```
| (1) | (since C++20) |
|
```
template< no-throw-input-range R >
requires std::destructible<ranges::range_value_t<R>>
constexpr ranges::borrowed_iterator_t<R> destroy( R&& r ) noexcept;
```
| (2) | (since C++20) |
1) Destroys the objects in the range `[first, last)`, as if by
```
for (; first != last; ++first)
std::ranges::destroy_at(std::addressof(*first));
return first;
```
2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first, last | - | iterator-sentinel pair denoting the range of elements to destroy |
| r | - | the range to destroy |
### Return value
An iterator compares equal to `last`.
### Complexity
Linear in the distance between `first` and `last`.
### Possible implementation
| |
| --- |
|
```
struct destroy_fn {
template<no-throw-input-iterator I, no-throw-sentinel-for<I> S>
requires std::destructible<std::iter_value_t<I>>
constexpr I operator()(I first, S last) const noexcept
{
for (; first != last; ++first)
std::ranges::destroy_at(std::addressof(*first));
return first;
}
template<no-throw-input-range R>
requires std::destructible<std::ranges::range_value_t<R>>
constexpr std::ranges::borrowed_iterator_t<R> operator()(R&& r) const noexcept
{
return operator()(std::ranges::begin(r), std::ranges::end(r));
}
};
inline constexpr destroy_fn destroy{};
```
|
### Example
The following example demonstrates how to use `ranges::destroy` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
std::ranges::destroy(ptr, ptr + 8);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [ranges::destroy\_n](destroy_n "cpp/memory/ranges/destroy n")
(C++20) | destroys a number of objects in a range (niebloid) |
| [ranges::destroy\_at](destroy_at "cpp/memory/ranges/destroy at")
(C++20) | destroys an object at a given address (niebloid) |
| [destroy](../destroy "cpp/memory/destroy")
(C++17) | destroys a range of objects (function template) |
cpp std::ranges::destroy_at std::ranges::destroy\_at
========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::destructible T >
constexpr void destroy_at( T* p ) noexcept;
```
| | (since C++20) |
If `T` is not an array type, calls the destructor of the object pointed to by `p`, as if by `p->~T()`. Otherwise, recursively destroys elements of `*p` in order, as if by calling `[std::destroy](http://en.cppreference.com/w/cpp/memory/destroy)([std::begin](http://en.cppreference.com/w/cpp/iterator/begin)(\*p), [std::end](http://en.cppreference.com/w/cpp/iterator/end)(\*p))`.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to the object to be destroyed |
### Return value
(none).
### Possible implementation
| |
| --- |
|
```
struct destroy_at_fn {
template<std::destructible T>
constexpr void operator()(T *p) const noexcept
{
if constexpr (std::is_array_v<T>)
for (auto &elem : *p)
operator()(std::addressof(elem));
else
p->~T();
}
};
inline constexpr destroy_at_fn destroy_at{};
```
|
### Notes
`destroy_at` deduces the type of object to be destroyed and hence avoids writing it explicitly in the destructor call.
When `destroy_at` is called in the evaluation of some [constant expression](../../language/constant_expression "cpp/language/constant expression") `e`, the argument `p` must point to an object whose lifetime began within the evaluation of `e`.
### Example
The following example demonstrates how to use `ranges::destroy_at` to destroy a contiguous sequence of elements.
```
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
for (int i = 0; i < 8; ++i)
std::ranges::destroy_at(ptr + i);
}
```
Output:
```
0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed
```
### See also
| | |
| --- | --- |
| [ranges::destroy](destroy "cpp/memory/ranges/destroy")
(C++20) | destroys a range of objects (niebloid) |
| [ranges::destroy\_n](destroy_n "cpp/memory/ranges/destroy n")
(C++20) | destroys a number of objects in a range (niebloid) |
| [ranges::construct\_at](construct_at "cpp/memory/ranges/construct at")
(C++20) | creates an object at a given address (niebloid) |
| [destroy\_at](../destroy_at "cpp/memory/destroy at")
(C++17) | destroys an object at a given address (function template) |
cpp std::ranges::uninitialized_copy_n, std::ranges::uninitialized_copy_n_result std::ranges::uninitialized\_copy\_n, std::ranges::uninitialized\_copy\_n\_result
================================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_iterator I, no-throw-input-iterator O, no-throw-sentinel-for<O> S >
requires std::constructible_from<std::iter_value_t<O>, std::iter_reference_t<I>>
uninitialized_copy_n_result<I, O>
uninitialized_copy_n( I ifirst, std::iter_difference_t<I> count,
O ofirst, S olast );
```
| (1) | (since C++20) |
| Helper types | | |
|
```
template<class I, class O>
using uninitialized_copy_n_result = ranges::in_out_result<I, O>;
```
| (2) | (since C++20) |
Let \(\scriptsize N\)N be `[ranges::min](http://en.cppreference.com/w/cpp/algorithm/ranges/min)(count, [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ofirst, olast))`, constructs \(\scriptsize N\)N elements in the output range `[ofirst, olast)`, which is an uninitialized memory area, from the elements in the input range beginning at `ifirst`.
The input range `[ifirst, ifirst + count)` must not overlap with the output range `[ofirst, olast)`.
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
The function has the effect equivalent to:
```
auto ret = ranges::uninitialized_copy(std::counted_iterator(ifirst, count),
std::default_sentinel, ofirst, olast);
return {std::move(ret.in).base(), ret.out};
```
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| ifirst | - | the beginning of the range of elements to copy from |
| count | - | the number of elements to copy |
| ofirst, olast | - | iterator-sentinel pair denoting the destination range |
### Return value
`{ifirst + N, ofirst + N}`.
### Complexity
\(\scriptsize\mathcal{O}(N)\)𝓞(N).
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_copy_n`, by using e.g. `[ranges::copy\_n](../../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n")`, if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_copy_n_fn {
template <std::input_iterator I, no-throw-input-iterator O, no-throw-sentinel-for<O> S>
requires std::constructible_from<std::iter_value_t<O>, std::iter_reference_t<I>>
ranges::uninitialized_copy_n_result<I, O>
operator()( I ifirst, std::iter_difference_t<I> count, O ofirst, S olast ) const {
O current {ofirst};
try {
for (; count > 0 && current != olast; ++ifirst, ++current, --count)
ranges::construct_at(std::addressof(*current), *ifirst);
return {std::move(ifirst), std::move(current)};
} catch (...) { // rollback: destroy constructed elements
for (; ofirst != current; ++ofirst)
ranges::destroy_at(std::addressof(*ofirst));
throw;
}
}
};
inline constexpr uninitialized_copy_n_fn uninitialized_copy_n{};
```
|
### Example
```
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
int main()
{
const char* stars[] { "Procyon", "Spica", "Pollux", "Deneb", "Polaris", };
constexpr int n {4};
alignas(alignof(std::string)) char out[n * sizeof(std::string)];
try
{
auto first {reinterpret_cast<std::string*>(out)};
auto last {first + n};
auto ret {std::ranges::uninitialized_copy_n(std::begin(stars), n, first, last)};
std::cout << "{ ";
for (auto it {first}; it != ret.out; ++it)
std::cout << std::quoted(*it) << ", ";
std::cout << "};\n";
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "uninitialized_copy_n exception\n";
}
}
```
Output:
```
{ "Procyon", "Spica", "Pollux", "Deneb", };
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_copy](uninitialized_copy "cpp/memory/ranges/uninitialized copy")
(C++20) | copies a range of objects to an uninitialized area of memory (niebloid) |
| [uninitialized\_copy\_n](../uninitialized_copy_n "cpp/memory/uninitialized copy n")
(C++11) | copies a number of objects to an uninitialized area of memory (function template) |
| programming_docs |
cpp std::ranges::uninitialized_fill_n std::ranges::uninitialized\_fill\_n
===================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <no-throw-forward-range I, class T>
requires std::constructible_from<std::iter_value_t<I>, const T&>
I uninitialized_fill_n( I first, std::iter_difference_t<I> n, const T& x );
```
| | (since C++20) |
Constructs `n` copies of the given value `x` in an uninitialized memory area, designated by the range `[first, first + n)`, as if by.
```
for (; n--; ++first) {
::new (
const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first)))
) std::remove_reference_t<std::iter_reference_t<I>>(x);
}
```
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| first | - | the beginning of the range of the elements to initialize |
| n | - | number of elements to construct |
| x | - | the value to construct the elements with |
### Return value
An iterator equal to `first + n`.
### Complexity
Linear in `n`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_fill_n`, e.g. by using `[ranges::fill\_n](../../algorithm/ranges/fill_n "cpp/algorithm/ranges/fill n")`, if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_fill_n_fn {
template <no-throw-forward-range I, class T>
requires std::constructible_from<std::iter_value_t<I>, const T&>
I operator()( I first, std::iter_difference_t<I> n, const T& x ) const {
I rollback {first};
try {
for (; n-- > 0; ++first)
ranges::construct_at(std::addressof(*first), x);
return first;
} catch (...) { // rollback: destroy constructed elements
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
};
inline constexpr uninitialized_fill_n_fn uninitialized_fill_n{};
```
|
### Example
```
#include <iostream>
#include <memory>
#include <string>
int main()
{
constexpr int n {3};
alignas(alignof(std::string)) char out[n * sizeof(std::string)];
try
{
auto first {reinterpret_cast<std::string*>(out)};
auto last = std::ranges::uninitialized_fill_n(first, n, "cppreference");
for (auto it {first}; it != last; ++it) {
std::cout << *it << '\n';
}
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "Exception!\n";
}
}
```
Output:
```
cppreference
cppreference
cppreference
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_fill](uninitialized_fill "cpp/memory/ranges/uninitialized fill")
(C++20) | copies an object to an uninitialized area of memory, defined by a range (niebloid) |
| [uninitialized\_fill\_n](../uninitialized_fill_n "cpp/memory/uninitialized fill n") | copies an object to an uninitialized area of memory, defined by a start and a count (function template) |
cpp std::ranges::uninitialized_move, std::ranges::uninitialized_move_result std::ranges::uninitialized\_move, std::ranges::uninitialized\_move\_result
==========================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_iterator I, std::sentinel_for<I> S1,
no-throw-forward-iterator O, no-throw-sentinel-for<O> S2 >
requires std::constructible_from<std::iter_value_t<O>,
std::iter_rvalue_reference_t<I>>
uninitialized_move_result<I, O>
uninitialized_move( I ifirst, S1 ilast, O ofirst, S2 olast );
```
| (1) | (since C++20) |
|
```
template< ranges::input_range IR, no-throw-forward-range OR >
requires std::constructible_from<ranges::range_value_t<OR>,
ranges::range_rvalue_reference_t<IR>>
uninitialized_move_result<ranges::borrowed_iterator_t<IR>,
ranges::borrowed_iterator_t<OR>>
uninitialized_move( IR&& in_range, OR&& out_range );
```
| (2) | (since C++20) |
| Helper types | | |
|
```
template<class I, class O>
using uninitialized_move_result = ranges::in_out_result<I, O>;
```
| (3) | (since C++20) |
1) Moves `N` elements from the input range `[ifirst, ilast)` to the output range `[ofirst, olast)` (that is an uninitialized memory area), where `N` is `min([ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ifirst, ilast), [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ofirst, olast))`.
The effect is equivalent to:
```
for (; ifirst != ilast && ofirst != olast; ++ofirst, ++ifirst)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<O>>(ranges::iter_move(ifirst));
```
If an exception is thrown during the initialization then the objects that already constructed in `[ofirst, olast)` are destroyed in an unspecified order. Also, the objects in `[ifirst, ilast)` that were already moved, are left in a valid but unspecified state.
2) Same as (1), but uses `in_range` as the first range and `out_range` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(in_range)` as `ifirst`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(in_range)` as `ilast`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(out_range)` as `ofirst`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(out_range)` as `olast`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| ifirst, ilast | - | iterator-sentinel pair denoting the input range of elements to move from |
| in\_range | - | the input range of elements to move from |
| ofirst, olast | - | iterator-sentinel pair denoting the output range to initialize |
| out\_range | - | the output range to initialize |
### Return value
`{ifirst + N, ofirst + N}`.
### Complexity
Linear in `N`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_move`, e.g. by using `[ranges::copy\_n](../../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n")`, if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_move_fn {
template <std::input_iterator I, std::sentinel_for<I> S1,
no-throw-forward-iterator O, no-throw-sentinel-for<O> S2>
requires std::constructible_from<std::iter_value_t<O>,
std::iter_rvalue_reference_t<I>>
ranges::uninitialized_move_result<I, O>
operator()( I ifirst, S1 ilast, O ofirst, S2 olast ) const {
O current {ofirst};
try {
for (; !(ifirst == ilast or current == olast); ++ifirst, ++current)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*current)))) std::remove_reference_t<
std::iter_reference_t<O>>(ranges::iter_move(ifirst));
return {std::move(ifirst), std::move(current)};
} catch (...) { // rollback: destroy constructed elements
for (; ofirst != current; ++ofirst)
ranges::destroy_at(std::addressof(*ofirst));
throw;
}
}
template <ranges::input_range IR, no-throw-forward-range OR>
requires std::constructible_from<ranges::range_value_t<OR>,
ranges::range_rvalue_reference_t<IR>>
ranges::uninitialized_move_result<ranges::borrowed_iterator_t<IR>,
ranges::borrowed_iterator_t<OR>>
operator()( IR&& in_range, OR&& out_range ) const {
return (*this)(ranges::begin(in_range), ranges::end(in_range),
ranges::begin(out_range), ranges::end(out_range));
}
};
inline constexpr uninitialized_move_fn uninitialized_move{};
```
|
### Example
```
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
void print(auto rem, auto first, auto last) {
for (std::cout << rem; first != last; ++first)
std::cout << std::quoted(*first) << ' ';
std::cout << '\n';
}
int main() {
std::string in[] { "Home", "World" };
print("initially, in: ", std::begin(in), std::end(in));
if (
constexpr auto sz = std::size(in);
void* out = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz)
) {
try {
auto first {static_cast<std::string*>(out)};
auto last {first + sz};
std::ranges::uninitialized_move(std::begin(in), std::end(in), first, last);
print("after move, in: ", std::begin(in), std::end(in));
print("after move, out: ", first, last);
std::ranges::destroy(first, last);
}
catch (...) {
std::cout << "Exception!\n";
}
std::free(out);
}
}
```
Possible output:
```
initially, in: "Home" "World"
after move, in: "" ""
after move, out: "Home" "World"
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_move\_n](uninitialized_move_n "cpp/memory/ranges/uninitialized move n")
(C++20) | moves a number of objects to an uninitialized area of memory (niebloid) |
| [uninitialized\_move](../uninitialized_move "cpp/memory/uninitialized move")
(C++17) | moves a range of objects to an uninitialized area of memory (function template) |
cpp std::ranges::uninitialized_move_n, std::ranges::uninitialized_move_n_result std::ranges::uninitialized\_move\_n, std::ranges::uninitialized\_move\_n\_result
================================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template <std::input_iterator I, no-throw-forward-iterator O,
no-throw-sentinel-for<O> S>
requires std::constructible_from<std::iter_value_t<O>,
std::iter_rvalue_reference_t<I>>
uninitialized_move_n_result<I, O>
uninitialized_move_n( I ifirst, std::iter_difference_t<I> n, O ofirst, S olast );
```
| (1) | (since C++20) |
| Helper types | | |
|
```
template<class I, class O>
using uninitialized_move_n_result = ranges::in_out_result<I, O>;
```
| (2) | (since C++20) |
Moves `N` elements from the input range beginning at `ifirst` to the uninitialized storage designated by the range `[ofirst, olast)`, where `N` is `min(n, [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ofirst, olast))`.
The effect is equivalent to:
```
for (; n-- > 0 && ofirst != olast; ++ifirst, ++ofirst)
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*first))))
std::remove_reference_t<std::iter_reference_t<O>>(ranges::iter_move(ifirst));
```
If an exception is thrown during the initialization then the objects that already constructed in `[ofirst, olast)` are destroyed in an unspecified order. Also, the objects in the input range beginning at `ifirst`, that were already moved, are left in a valid but unspecified state.
The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| ifirst | - | the beginning of the input range of elements to move from |
| ofirst, olast | - | iterator-sentinel pair denoting the output range of elements to initialize |
| n | - | the number of elements to move |
### Return value
`{ifirst + N, ofirst + N}`.
### Complexity
Linear in `N`.
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of the `ranges::uninitialized_move_n`, e.g. by using `[ranges::copy\_n](../../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n")`, if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_move_n_fn {
template <std::input_iterator I, no-throw-forward-iterator O,
no-throw-sentinel-for<O> S>
requires std::constructible_from<std::iter_value_t<O>,
std::iter_rvalue_reference_t<I>>
ranges::uninitialized_move_n_result<I, O>
operator()( I ifirst, std::iter_difference_t<I> n, O ofirst, S olast ) const {
O current {ofirst};
try {
for (; n-- > 0 && current != olast; ++ifirst, ++current)
::new (const_cast<void*>(static_cast<const volatile void*>
(std::addressof(*current)))) std::remove_reference_t<
std::iter_reference_t<O>>(ranges::iter_move(ifirst));
return {std::move(ifirst), std::move(current)};
} catch (...) { // rollback: destroy constructed elements
for (; ofirst != current; ++ofirst)
ranges::destroy_at(std::addressof(*ofirst));
throw;
}
}
};
inline constexpr uninitialized_move_n_fn uninitialized_move_n{};
```
|
### Example
```
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
void print(auto rem, auto first, auto last) {
for (std::cout << rem; first != last; ++first)
std::cout << std::quoted(*first) << ' ';
std::cout << '\n';
}
int main() {
std::string in[] { "No", "Diagnostic", "Required", };
print("initially, in: ", std::begin(in), std::end(in));
if (
constexpr auto sz = std::size(in);
void* out = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz)
) {
try {
auto first {static_cast<std::string*>(out)};
auto last {first + sz};
std::ranges::uninitialized_move_n(std::begin(in), sz, first, last);
print("after move, in: ", std::begin(in), std::end(in));
print("after move, out: ", first, last);
std::ranges::destroy(first, last);
}
catch (...) {
std::cout << "Exception!\n";
}
std::free(out);
}
}
```
Possible output:
```
initially, in: "No" "Diagnostic" "Required"
after move, in: "" "" ""
after move, out: "No" "Diagnostic" "Required"
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_move](uninitialized_move "cpp/memory/ranges/uninitialized move")
(C++20) | moves a range of objects to an uninitialized area of memory (niebloid) |
| [uninitialized\_move\_n](../uninitialized_move_n "cpp/memory/uninitialized move n")
(C++17) | moves a number of objects to an uninitialized area of memory (function template) |
cpp std::ranges::uninitialized_copy, std::ranges::uninitialized_copy_result std::ranges::uninitialized\_copy, std::ranges::uninitialized\_copy\_result
==========================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_iterator I, std::sentinel_for<I> S1,
no-throw-forward-iterator O, no-throw-sentinel-for<O> S2 >
requires std::constructible_from<std::iter_value_t<O>, std::iter_reference_t<I>>
uninitialized_copy_result<I, O>
uninitialized_copy( I ifirst, S1 ilast, O ofirst, S2 olast );
```
| (1) | (since C++20) |
|
```
template< ranges::input_range IR, no-throw-forward-range OR >
requires std::constructible_from<ranges::range_value_t<OR>,
ranges::range_reference_t<IR>>
uninitialized_copy_result<ranges::borrowed_iterator_t<IR>,
ranges::borrowed_iterator_t<OR>>
uninitialized_copy( IR&& in_range, OR&& out_range );
```
| (2) | (since C++20) |
| Helper types | | |
|
```
template<class I, class O>
using uninitialized_copy_result = ranges::in_out_result<I, O>;
```
| (3) | (since C++20) |
1) Let \(\scriptsize N\)N be `[ranges::min](http://en.cppreference.com/w/cpp/algorithm/ranges/min)([ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ifirst, ilast), [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(ofirst, olast))`, constructs \(\scriptsize N\)N elements in the output range `[ofirst, olast)`, which is an uninitialized memory area, from the elements in the input range `[ifirst, ilast)`.
The input and output ranges must not overlap.
If an exception is thrown during the initialization, the objects already constructed are destroyed in an unspecified order.
The function has the effect equal to:
```
for (; !(ifirst == ilast || ofirst == olast); ++ofirst, ++ifirst) {
::new (const_cast<void*>(static_cast<const volatile void*>(std::addressof(*ofirst))))
std::remove_reference_t<std::iter_reference_t<O>>(*ifirst);
}
```
2) Same as (1), but uses `in_range` as the first range and `out_range` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(in_range)` as `ifirst`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(in_range)` as `ilast`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(out_range)` as `ofirst`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(out_range)` as `olast`. The function-like entities described on this page are *niebloids*, that is:
* Explicit template argument lists cannot be specified when calling any of them.
* None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl").
* When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
### Parameters
| | | |
| --- | --- | --- |
| ifirst, ilast | - | iterator-sentinel pair denoting the range of elements to copy from |
| in\_range | - | the range of elements to copy from |
| ofirst, olast | - | iterator-sentinel pair denoting the destination range |
| out\_range | - | the destination range |
### Return value
`{ifirst + N, ofirst + N}`.
### Complexity
\(\scriptsize\mathcal{O}(N)\)𝓞(N).
### Exceptions
The exception thrown on construction of the elements in the destination range, if any.
### Notes
An implementation may improve the efficiency of `ranges::uninitialized_copy` if the value type of the output range is [TrivialType](../../named_req/trivialtype "cpp/named req/TrivialType").
### Possible implementation
| |
| --- |
|
```
struct uninitialized_copy_fn {
template <std::input_iterator I, std::sentinel_for<I> S1,
no-throw-forward-iterator O, no-throw-sentinel-for<O> S2>
requires std::constructible_from<std::iter_value_t<O>, std::iter_reference_t<I>>
ranges::uninitialized_copy_result<I, O>
operator()( I ifirst, S1 ilast, O ofirst, S2 olast ) const {
O current {ofirst};
try {
for (; !(ifirst == ilast or current == olast); ++ifirst, ++current)
ranges::construct_at(std::addressof(*current), *ifirst);
return {std::move(ifirst), std::move(current)};
} catch (...) { // rollback: destroy constructed elements
for (; ofirst != current; ++ofirst)
ranges::destroy_at(std::addressof(*ofirst));
throw;
}
}
template <ranges::input_range IR, no-throw-forward-range OR>
requires std::constructible_from<ranges::range_value_t<OR>,
ranges::range_reference_t<IR>>
ranges::uninitialized_copy_result<ranges::borrowed_iterator_t<IR>,
ranges::borrowed_iterator_t<OR>>
operator()( IR&& in_range, OR&& out_range ) const {
return (*this)(ranges::begin(in_range), ranges::end(in_range),
ranges::begin(out_range), ranges::end(out_range));
}
};
inline constexpr uninitialized_copy_fn uninitialized_copy{};
```
|
### Example
```
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
int main()
{
const char* v[] { "This", "is", "an", "example", };
if (const auto sz{std::size(v)};
void* pbuf = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz))
{
try
{
auto first {static_cast<std::string*>(pbuf)};
auto last {first + sz};
std::ranges::uninitialized_copy(std::begin(v), std::end(v), first, last);
std::cout << "{ ";
for (auto it {first}; it != last; ++it)
std::cout << std::quoted(*it) << ", ";
std::cout << "};\n";
std::ranges::destroy(first, last);
}
catch(...)
{
std::cout << "uninitialized_copy exception\n";
}
std::free(pbuf);
}
}
```
Output:
```
{ "This", "is", "an", "example", };
```
### See also
| | |
| --- | --- |
| [ranges::uninitialized\_copy\_n](uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n")
(C++20) | copies a number of objects to an uninitialized area of memory (niebloid) |
| [uninitialized\_copy](../uninitialized_copy "cpp/memory/uninitialized copy") | copies a range of objects to an uninitialized area of memory (function template) |
| programming_docs |
cpp std::enable_shared_from_this<T>::~enable_shared_from_this std::enable\_shared\_from\_this<T>::~enable\_shared\_from\_this
===============================================================
| | | |
| --- | --- | --- |
|
```
~enable_shared_from_this();
```
| | |
Destroys `*this`.
### See also
| | |
| --- | --- |
| [shared\_ptr](../shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::enable_shared_from_this<T>::enable_shared_from_this std::enable\_shared\_from\_this<T>::enable\_shared\_from\_this
==============================================================
| | | |
| --- | --- | --- |
|
```
constexpr enable_shared_from_this() noexcept;
```
| (1) | (since C++11) |
|
```
enable_shared_from_this( const enable_shared_from_this<T>&obj ) noexcept;
```
| (2) | (since C++11) |
Constructs a new `enable_shared_from_this` object. The private `std::weak_ptr<T>` member is value-initialized.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | an `enable_shared_from_this` to copy |
### Notes
There is no move constructor: moving from an object derived from `enable_shared_from_this` does not transfer its shared identity.
### Example
```
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() {} // implicitly calls enable_shared_from_this constructor
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
std::shared_ptr<Foo> pf1(new Foo);
auto pf2 = pf1->getFoo(); // shares ownership of object with pf1
}
```
### See also
| | |
| --- | --- |
| [shared\_ptr](../shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::enable_shared_from_this<T>::shared_from_this std::enable\_shared\_from\_this<T>::shared\_from\_this
======================================================
| | | |
| --- | --- | --- |
|
```
std::shared_ptr<T> shared_from_this();
```
| (1) | |
|
```
std::shared_ptr<T const> shared_from_this() const;
```
| (2) | |
Returns a `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` that shares ownership of `*this` with all existing `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)` that refer to `*this`.
Effectively executes `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(weak_this)`, where `weak_this` is the private mutable `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` member of `enable_shared_from_this`.
### Notes
It is permitted to call `shared_from_this` only on a previously shared object, i.e. on an object managed by `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)` (in particular, `shared_from_this` cannot be called during construction of `*this`).
Otherwise the behavior is undefined (until C++17)`[std::bad\_weak\_ptr](../bad_weak_ptr "cpp/memory/bad weak ptr")` is thrown (by the shared\_ptr constructor from a default-constructed `weak_this`) (since C++17).
### Return value
`[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` that shares ownership of `*this` with pre-existing `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)`s.
### Example
```
#include <iostream>
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
Foo *f = new Foo;
std::shared_ptr<Foo> pf1;
{
std::shared_ptr<Foo> pf2(f);
pf1 = pf2->getFoo(); // shares ownership of object with pf2
}
std::cout << "pf2 is gone\n";
}
```
Output:
```
Foo::Foo
pf2 is gone
Foo::~Foo
```
### See also
| | |
| --- | --- |
| [shared\_ptr](../shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::enable_shared_from_this<T>::operator= std::enable\_shared\_from\_this<T>::operator=
=============================================
| | | |
| --- | --- | --- |
|
```
enable_shared_from_this<T>& operator=( const enable_shared_from_this<T> &obj ) noexcept;
```
| | (since C++11) |
Does nothing; returns `*this`.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | an `enable_shared_from_this` to assign to `*this` |
### Return value
`*this`.
### Notes
The private `std::weak_ptr<T>` member is not affected by this assignment operator.
### Example
Note: `enable_shared_from_this::operator=` is defined as `protected` in order to prevent accidental slicing but allow derived classes to have default assignment operators.
```
#include <memory>
#include <iostream>
class SharedInt : public std::enable_shared_from_this<SharedInt>
{
public:
explicit SharedInt(int n) : mNumber(n) {}
SharedInt(const SharedInt&) = default;
SharedInt(SharedInt&&) = default;
~SharedInt() = default;
// Both assignment operators use enable_shared_from_this::operator=
SharedInt& operator=(const SharedInt&) = default;
SharedInt& operator=(SharedInt&&) = default;
int number() const { return mNumber; }
private:
int mNumber;
};
int main() {
std::shared_ptr<SharedInt> a = std::make_shared<SharedInt>(2);
std::shared_ptr<SharedInt> b = std::make_shared<SharedInt>(4);
*a = *b;
std::cout << a->number() << std::endl;
}
```
Output:
```
4
```
### See also
| | |
| --- | --- |
| [shared\_ptr](../shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::enable_shared_from_this<T>::weak_from_this std::enable\_shared\_from\_this<T>::weak\_from\_this
====================================================
| | | |
| --- | --- | --- |
|
```
std::weak_ptr<T> weak_from_this() noexcept;
```
| (1) | (since C++17) |
|
```
std::weak_ptr<T const> weak_from_this() const noexcept;
```
| (2) | (since C++17) |
Returns a `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` that tracks ownership of `*this` by all existing `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` that refer to `*this`.
### Notes
This is a copy of the private mutable `weak_ptr` member that is part of `enable_shared_from_this`.
### Return value
`[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` that shares ownership of `*this` with pre-existing `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")`s.
### Example
### See also
| | |
| --- | --- |
| [shared\_ptr](../shared_ptr "cpp/memory/shared ptr")
(C++11) | smart pointer with shared object ownership semantics (class template) |
cpp std::pmr::unsynchronized_pool_resource::do_deallocate std::pmr::unsynchronized\_pool\_resource::do\_deallocate
========================================================
| | | |
| --- | --- | --- |
|
```
virtual void do_deallocate( void* p, std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
Returns the memory at `p` to the pool. It is unspecified if or under what circumstances this operation will result in a call to `deallocate()` on the upstream memory resource.
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_deallocate](../memory_resource/do_deallocate "cpp/memory/memory resource/do deallocate")
[virtual] | deallocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::unsynchronized_pool_resource::release std::pmr::unsynchronized\_pool\_resource::release
=================================================
| | | |
| --- | --- | --- |
|
```
void release();
```
| | (since C++17) |
Releases all memory owned by this resource by calling the `deallocate` function of the upstream memory resource as needed.
Memory is released back to the upstream resource even if `deallocate` has not been called for some of the allocated blocks.
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::unsynchronized_pool_resource::unsynchronized_pool_resource std::pmr::unsynchronized\_pool\_resource::unsynchronized\_pool\_resource
========================================================================
| | | |
| --- | --- | --- |
|
```
unsynchronized_pool_resource();
```
| (1) | (since C++17) |
|
```
explicit unsynchronized_pool_resource( std::pmr::memory_resource* upstream );
```
| (2) | (since C++17) |
|
```
explicit unsynchronized_pool_resource( const std::pmr::pool_options& opts );
```
| (3) | (since C++17) |
|
```
unsynchronized_pool_resource( const std::pmr::pool_options& opts,
std::pmr::memory_resource* upstream );
```
| (4) | (since C++17) |
|
```
unsynchronized_pool_resource( const unsynchronized_pool_resource& ) = delete;
```
| (5) | (since C++17) |
Constructs a `unsynchronized_pool_resource`.
1-4) Constructs an `unsynchronized_pool_resource` using the specified upstream memory resource and tuned according to the specified options. The resulting object holds a copy of `upstream` but does not own the resource to which `upstream` points.
The overloads not taking `opts` as a parameter uses a default constructed instance of [`pool_options`](../pool_options "cpp/memory/pool options") as the options. The overloads not taking `upstream` as a parameter use the return value of `[std::pmr::get\_default\_resource](http://en.cppreference.com/w/cpp/memory/get_default_resource)()` as the upstream memory resource.
5) Copy constructor is deleted. ### Parameters
| | | |
| --- | --- | --- |
| opts | - | a `[std::pmr::pool\_options](../pool_options "cpp/memory/pool options")` struct containing the constructor options |
| upstream | - | the upstream memory resource to use |
### Exceptions
1-4) Throws only if a call to the `allocate()` function of the upstream resource throws. It is unspecified if or under what conditions such a call takes place.
cpp std::pmr::unsynchronized_pool_resource::do_allocate std::pmr::unsynchronized\_pool\_resource::do\_allocate
======================================================
| | | |
| --- | --- | --- |
|
```
virtual void* do_allocate( std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
Allocates storage.
If the pool selected for a block of size `bytes` is unable to satisfy the request from its internal data structures, calls `allocate()` on the upstream memory resource to obtain memory.
If the size requested is larger than what the largest pool can handle, memory is allocated by calling `allocate()` on the upstream memory resource.
### Return value
A pointer to allocated storage of at least `bytes` bytes in size, aligned to the specified `alignment` if such alignment is supported, and to `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))` otherwise.
### Exceptions
Throws nothing unless calling `allocate()` on the upstream memory resource throws.
### See also
| | |
| --- | --- |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_allocate](../memory_resource/do_allocate "cpp/memory/memory resource/do allocate")
[virtual] | allocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::unsynchronized_pool_resource::~unsynchronized_pool_resource std::pmr::unsynchronized\_pool\_resource::~unsynchronized\_pool\_resource
=========================================================================
| | | |
| --- | --- | --- |
|
```
virtual ~unsynchronized_pool_resource();
```
| | (since C++17) |
Destroys a `unsynchronized_pool_resource`.
Deallocates all memory owned by this resource by calling `this->release()`.
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/unsynchronized pool resource/release") | Release all allocated memory (public member function) |
cpp std::pmr::unsynchronized_pool_resource::do_is_equal std::pmr::unsynchronized\_pool\_resource::do\_is\_equal
=======================================================
| | | |
| --- | --- | --- |
|
```
virtual bool do_is_equal( const std::pmr::memory_resource& other ) const noexcept;
```
| | (since C++17) |
Compare `*this` with `other` for identity - memory allocated using a `unsynchronized_pool_resource` can only be deallocated using that same resource.
### Return value
`this == &other`.
### Defect report
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3000](https://cplusplus.github.io/LWG/issue3000) | C++17 | unnecessary `dynamic_cast` was performed | removed |
### See also
| | |
| --- | --- |
| [do\_is\_equal](../memory_resource/do_is_equal "cpp/memory/memory resource/do is equal")
[virtual] | compare for equality with another `memory_resource` (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::unsynchronized_pool_resource::options std::pmr::unsynchronized\_pool\_resource::options
=================================================
| | | |
| --- | --- | --- |
|
```
std::pmr::pool_options options() const;
```
| | (since C++17) |
Returns the options that controls the pooling behavior of this resource.
The values in the returned struct may differ from those supplied to the constructor in the following ways:
* Values of zero will be replaced with implementation-specified defaults;
* Sizes may be rounded to an unspecified granularity.
### See also
| | |
| --- | --- |
| [(constructor)](unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource/unsynchronized pool resource") | Constructs a `unsynchronized_pool_resource` (public member function) |
cpp std::pmr::unsynchronized_pool_resource::upstream_resource std::pmr::unsynchronized\_pool\_resource::upstream\_resource
============================================================
| | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* upstream_resource() const;
```
| | (since C++17) |
Returns a pointer to the upstream memory resource. This is the same value as the `upstream` argument passed to the constructor of this object.
### See also
| | |
| --- | --- |
| [(constructor)](unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource/unsynchronized pool resource") | Constructs a `unsynchronized_pool_resource` (public member function) |
cpp std::raw_storage_iterator<OutputIt,T>::raw_storage_iterator std::raw\_storage\_iterator<OutputIt,T>::raw\_storage\_iterator
===============================================================
| | | |
| --- | --- | --- |
|
```
explicit raw_storage_iterator( OutputIt it );
```
| | |
Initializes the iterator to point to the same value as `it` points.
### Parameters
| | | |
| --- | --- | --- |
| it | - | location to point to |
cpp std::raw_storage_iterator<OutputIt,T>::base std::raw\_storage\_iterator<OutputIt,T>::base
=============================================
| | | |
| --- | --- | --- |
|
```
OutputIt base() const;
```
| | (since C++17) |
Provides access to the iterator passed in the constructor of this raw\_storage\_iterator.
### Parameters
(none).
### Return value
An iterator pointing at the same object as `*this`.
cpp std::raw_storage_iterator<OutputIt,T>::operator* std::raw\_storage\_iterator<OutputIt,T>::operator\*
===================================================
| | | |
| --- | --- | --- |
|
```
raw_storage_iterator& operator*();
```
| | |
Dereferences the iterator.
### Parameters
(none).
### Return value
`*this`.
cpp std::raw_storage_iterator<OutputIt,T>::operator= std::raw\_storage\_iterator<OutputIt,T>::operator=
==================================================
| | | |
| --- | --- | --- |
|
```
raw_storage_iterator& operator=( const T& el );
```
| (1) | |
|
```
raw_storage_iterator& operator=( T&& el );
```
| (2) | (since C++17) |
1) Constructs a value at the location the iterator points to from `el`.
2) Constructs a value at the location the iterator points to from `std::move(el)`. ### Parameters
| | | |
| --- | --- | --- |
| el | - | the value to copy or move from |
### Return value
`*this`.
cpp std::raw_storage_iterator<OutputIt,T>::operator++, operator++(int) std::raw\_storage\_iterator<OutputIt,T>::operator++, operator++(int)
====================================================================
| | | |
| --- | --- | --- |
|
```
raw_storage_iterator& operator++();
```
| | |
|
```
raw_storage_iterator operator++(int);
```
| | |
Advances the iterator.
1) Pre-increment. Returns the updated iterator.
2) Post-increment. Returns the old value of the iterator. ### Parameters
(none).
### Return value
1) `*this`
2) The old value of the iterator.
cpp std::shared_ptr<T>::reset std::shared\_ptr<T>::reset
==========================
| | | |
| --- | --- | --- |
|
```
void reset() noexcept;
```
| (1) | (since C++11) |
|
```
template< class Y >
void reset( Y* ptr );
```
| (2) | (since C++11) |
|
```
template< class Y, class Deleter >
void reset( Y* ptr, Deleter d );
```
| (3) | (since C++11) |
|
```
template< class Y, class Deleter, class Alloc >
void reset( Y* ptr, Deleter d, Alloc alloc );
```
| (4) | (since C++11) |
Replaces the managed object with an object pointed to by `ptr`. Optional deleter `d` can be supplied, which is later used to destroy the new object when no `shared_ptr` objects own it. By default, [`delete`](../../language/delete "cpp/language/delete") expression is used as deleter. Proper [`delete`](../../language/delete "cpp/language/delete") expression corresponding to the supplied type is always selected, this is the reason why the function is implemented as template using a separate parameter `Y`.
If `*this` already owns an object and it is the last `shared_ptr` owning it, the object is destroyed through the owned deleter.
If the object pointed to by `ptr` is already owned, the function generally results in undefined behavior.
1) Releases the ownership of the managed object, if any. After the call, `*this` manages no object. Equivalent to `shared_ptr().swap(*this);`
2-4) Replaces the managed object with an object pointed to by `ptr`. `Y` must be a complete type and implicitly convertible to `T`. Additionally:
2) Uses the delete expression as the deleter. A valid delete expression must be available, i.e. `delete ptr` must be well formed, have well-defined behavior and not throw any exceptions. Equivalent to `shared_ptr<T>(ptr).swap(*this);`.
3) Uses the specified deleter `d` as the deleter. `Deleter` must be callable for the type `T`, i.e. `d(ptr)` must be well formed, have well-defined behavior and not throw any exceptions. `Deleter` must be [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"), and its copy constructor and destructor must not throw exceptions. Equivalent to `shared_ptr<T>(ptr, d).swap(*this);`.
4) Same as (3), but additionally uses a copy of `alloc` for allocation of data for internal use. `Alloc` must be an [Allocator](../../named_req/allocator "cpp/named req/Allocator"). The copy constructor and destructor must not throw exceptions. Equivalent to `shared_ptr<T>(ptr, d, alloc).swap(*this);`. ### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to an object to acquire ownership of |
| d | - | deleter to store for deletion of the object |
| alloc | - | allocator to use for internal allocations |
### Return value
(none).
### Exceptions
2) `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if required additional memory could not be obtained. May throw implementation-defined exception for other errors. `delete ptr` is called if an exception occurs.
3-4) `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if required additional memory could not be obtained. May throw implementation-defined exception for other errors. `d(ptr)` is called if an exception occurs. ### Example
```
#include <memory>
#include <iostream>
struct Foo {
Foo(int n = 0) noexcept : bar(n) {
std::cout << "Foo::Foo(), bar = " << bar << " @ " << this << '\n';
}
~Foo() {
std::cout << "Foo::~Foo(), bar = " << bar << " @ " << this << "\n";
}
int getBar() const noexcept { return bar; }
private:
int bar;
};
int main()
{
std::cout << "1) unique ownership\n";
{
std::shared_ptr<Foo> sptr = std::make_shared<Foo>(100);
std::cout << "Foo::bar = " << sptr->getBar() << ", use_count() = "
<< sptr.use_count() << '\n';
// Reset the shared_ptr without handing it a fresh instance of Foo.
// The old instance will be destroyed after this call.
std::cout << "call sptr.reset()...\n";
sptr.reset(); // calls Foo's destructor here
std::cout << "After reset(): use_count() = " << sptr.use_count()
<< ", sptr = " << sptr << '\n';
} // No call to Foo's destructor, it was done earlier in reset().
std::cout << "\n2) unique ownership\n";
{
std::shared_ptr<Foo> sptr = std::make_shared<Foo>(200);
std::cout << "Foo::bar = " << sptr->getBar() << ", use_count() = "
<< sptr.use_count() << '\n';
// Reset the shared_ptr, hand it a fresh instance of Foo.
// The old instance will be destroyed after this call.
std::cout << "call sptr.reset()...\n";
sptr.reset(new Foo{222});
std::cout << "After reset(): use_count() = " << sptr.use_count()
<< ", sptr = " << sptr << "\nLeaving the scope...\n";
} // Calls Foo's destructor.
std::cout << "\n3) multiple ownership\n";
{
std::shared_ptr<Foo> sptr1 = std::make_shared<Foo>(300);
std::shared_ptr<Foo> sptr2 = sptr1;
std::shared_ptr<Foo> sptr3 = sptr2;
std::cout << "Foo::bar = " << sptr1->getBar() << ", use_count() = "
<< sptr1.use_count() << '\n';
// Reset the shared_ptr sptr1, hand it a fresh instance of Foo.
// The old instance will stay shared between sptr2 and sptr3.
std::cout << "call sptr1.reset()...\n";
sptr1.reset(new Foo{333});
std::cout << "After reset():\n"
<< "sptr1.use_count() = " << sptr1.use_count()
<< ", sptr1 @ " << sptr1 << '\n'
<< "sptr2.use_count() = " << sptr2.use_count()
<< ", sptr2 @ " << sptr2 << '\n'
<< "sptr3.use_count() = " << sptr3.use_count()
<< ", sptr3 @ " << sptr3 << '\n'
<< "Leaving the scope...\n";
} // Calls two destructors of: 1) Foo owned by sptr1,
// 2) Foo shared between sptr2/sptr3.
}
```
Possible output:
```
1) unique ownership
Foo::Foo(), bar = 100 @ 0x23c5040
Foo::bar = 100, use_count() = 1
call sptr.reset()...
Foo::~Foo(), bar = 100 @ 0x23c5040
After reset(): use_count() = 0, sptr = 0
2) unique ownership
Foo::Foo(), bar = 200 @ 0x23c5040
Foo::bar = 200, use_count() = 1
call sptr.reset()...
Foo::Foo(), bar = 222 @ 0x23c5050
Foo::~Foo(), bar = 200 @ 0x23c5040
After reset(): use_count() = 1, sptr = 0x23c5050
Leaving the scope...
Foo::~Foo(), bar = 222 @ 0x23c5050
3) multiple ownership
Foo::Foo(), bar = 300 @ 0x23c5080
Foo::bar = 300, use_count() = 3
call sptr1.reset()...
Foo::Foo(), bar = 333 @ 0x23c5050
After reset():
sptr1.use_count() = 1, sptr1 @ 0x23c5050
sptr2.use_count() = 2, sptr2 @ 0x23c5080
sptr3.use_count() = 2, sptr3 @ 0x23c5080
Leaving the scope...
Foo::~Foo(), bar = 300 @ 0x23c5080
Foo::~Foo(), bar = 333 @ 0x23c5050
```
### See also
| | |
| --- | --- |
| [(constructor)](shared_ptr "cpp/memory/shared ptr/shared ptr") | constructs new `shared_ptr` (public member function) |
| programming_docs |
cpp deduction guides for std::shared_ptr
deduction guides for `std::shared_ptr`
======================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template <class T>
shared_ptr(std::weak_ptr<T>) -> shared_ptr<T>;
```
| (1) | (since C++17) |
|
```
template <class T, class D>
shared_ptr(std::unique_ptr<T, D>) -> shared_ptr<T>;
```
| (2) | (since C++17) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` to account for the edge cases missed by the implicit deduction guides.
Note that there is no class template argument deduction from pointer types because it is impossible to distinguish pointers obtained from array and non-array forms of `new`.
### Example
```
#include <memory>
int main()
{
auto p = std::make_shared<int>(42);
std::weak_ptr w{p}; // explicit deduction guide is used in this case
std::shared_ptr p2{w}; // explicit deduction guide is used in this case
}
```
cpp std::static_pointer_cast, std::dynamic_pointer_cast, std::const_pointer_cast, std::reinterpret_pointer_cast std::static\_pointer\_cast, std::dynamic\_pointer\_cast, std::const\_pointer\_cast, std::reinterpret\_pointer\_cast
===================================================================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept;
```
| (1) | (since C++11) |
|
```
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r ) noexcept;
```
| (2) | (since C++20) |
|
```
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept;
```
| (3) | (since C++11) |
|
```
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( std::shared_ptr<U>&& r ) noexcept;
```
| (4) | (since C++20) |
|
```
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r ) noexcept;
```
| (5) | (since C++11) |
|
```
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( std::shared_ptr<U>&& r ) noexcept;
```
| (6) | (since C++20) |
|
```
template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( const std::shared_ptr<U>& r ) noexcept;
```
| (7) | (since C++17) |
|
```
template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( std::shared_ptr<U>&& r ) noexcept;
```
| (8) | (since C++20) |
Creates a new instance of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` whose stored pointer is obtained from `r`'s stored pointer using a cast expression.
If `r` is empty, so is the new `shared_ptr` (but its stored pointer is not necessarily null). Otherwise, the new `shared_ptr` will share ownership with the initial value of `r`, except that it is empty if the `dynamic_cast` performed by `dynamic_pointer_cast` returns a null pointer.
Let `Y` be `typename [std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type`, then the resulting `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")`'s stored pointer will be obtained by evaluating, respectively:
1-2) `static_cast<Y*>(r.get())`.
3-4) `dynamic_cast<Y*>(r.get())` (If the result of the `dynamic_cast` is a null pointer value, the returned `shared_ptr` will be empty.)
5-6) `const_cast<Y*>(r.get())`.
7-8) `reinterpret_cast<Y*>(r.get())`
The behavior of these functions is undefined unless the corresponding cast from `U*` to `T*` is well formed:
1-2) The behavior is undefined unless `static_cast<T*>((U*)nullptr)` is well formed.
3-4) The behavior is undefined unless `dynamic_cast<T*>((U*)nullptr)` is well formed.
5-6) The behavior is undefined unless `const_cast<T*>((U*)nullptr)` is well formed.
7-8) The behavior is undefined unless `reinterpret_cast<T*>((U*)nullptr)` is well formed.
| | |
| --- | --- |
| After calling the rvalue overloads (2,4,6,8), `r` is empty and `r.get() == nullptr`, except that `r` is not modified for `dynamic_pointer_cast` (4) if the `dynamic_cast` fails. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| r | - | The pointer to convert |
### Notes
The expressions `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(static\_cast<T\*>(r.get()))`, `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(dynamic\_cast<T\*>(r.get()))` and `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(const\_cast<T\*>(r.get()))` might seem to have the same effect, but they all will likely result in undefined behavior, attempting to delete the same object twice!
### Possible implementation
| First version |
| --- |
|
```
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
auto p = static_cast<typename std::shared_ptr<T>::element_type*>(r.get());
return std::shared_ptr<T>{r, p};
}
```
|
| Second version |
|
```
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
if (auto p = dynamic_cast<typename std::shared_ptr<T>::element_type*>(r.get())) {
return std::shared_ptr<T>{r, p};
} else {
return std::shared_ptr<T>{};
}
}
```
|
| Third version |
|
```
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
auto p = const_cast<typename std::shared_ptr<T>::element_type*>(r.get());
return std::shared_ptr<T>{r, p};
}
```
|
| Fourth version |
|
```
template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
auto p = reinterpret_cast<typename std::shared_ptr<T>::element_type*>(r.get());
return std::shared_ptr<T>{r, p};
}
```
|
### Example
```
#include <iostream>
#include <memory>
struct Base
{
int a;
virtual void f() const { std::cout << "I am base!\n";}
virtual ~Base(){}
};
struct Derived : Base
{
void f() const override
{ std::cout << "I am derived!\n"; }
~Derived(){}
};
int main(){
auto basePtr = std::make_shared<Base>();
std::cout << "Base pointer says: ";
basePtr->f();
auto derivedPtr = std::make_shared<Derived>();
std::cout << "Derived pointer says: ";
derivedPtr->f();
// static_pointer_cast to go up class hierarchy
basePtr = std::static_pointer_cast<Base>(derivedPtr);
std::cout << "Base pointer to derived says: ";
basePtr->f();
// dynamic_pointer_cast to go down/across class hierarchy
auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr);
if(downcastedPtr)
{
std::cout << "Downcasted pointer says: ";
downcastedPtr->f();
}
// All pointers to derived share ownership
std::cout << "Pointers to underlying derived: "
<< derivedPtr.use_count()
<< "\n";
}
```
Output:
```
Base pointer says: I am base!
Derived pointer says: I am derived!
Base pointer to derived says: I am derived!
Downcasted pointer says: I am derived!
Pointers to underlying derived: 3
```
### See also
| | |
| --- | --- |
| [(constructor)](shared_ptr "cpp/memory/shared ptr/shared ptr") | constructs new `shared_ptr` (public member function) |
cpp std::shared_ptr<T>::operator<< std::shared\_ptr<T>::operator<<
===============================
| | | |
| --- | --- | --- |
|
```
template< class T, class U, class V >
std::basic_ostream<U, V>& operator<<( std::basic_ostream<U, V>& os, const std::shared_ptr<T>& ptr );
```
| | |
Inserts the value of the pointer stored in `ptr` into the output stream `os`.
Equivalent to `os << ptr.get()`.
### Parameters
| | | |
| --- | --- | --- |
| os | - | a `[std::basic\_ostream](../../io/basic_ostream "cpp/io/basic ostream")` to insert `ptr` into |
| ptr | - | the data to be inserted into `os` |
### Return value
`os`.
### Example
```
#include <iostream>
#include <memory>
class Foo {};
int main()
{
auto sp = std::make_shared<Foo>();
std::cout << sp << '\n';
std::cout << sp.get() << '\n';
}
```
Possible output:
```
0x6d9028
0x6d9028
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
cpp std::shared_ptr<T>::~shared_ptr std::shared\_ptr<T>::~shared\_ptr
=================================
| | | |
| --- | --- | --- |
|
```
~shared_ptr();
```
| | |
If `*this` owns an object and it is the last `shared_ptr` owning it, the object is destroyed through the owned deleter.
After the destruction, the smart pointers that shared ownership with `*this`, if any, will report a `[use\_count()](use_count "cpp/memory/shared ptr/use count")` that is one less than its previous value.
### Notes
Unlike `[std::unique\_ptr](../unique_ptr "cpp/memory/unique ptr")`, the deleter of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` is invoked even if the managed pointer is null.
### Example
```
#include <memory>
#include <iostream>
struct S {
S() { std::cout << "S::S()\n"; }
~S() { std::cout << "S::~S()\n"; }
struct Deleter {
void operator()(S* s) const {
std::cout << "S::Deleter()\n";
delete s;
}
};
};
int main()
{
auto sp = std::shared_ptr<S>{ new S, S::Deleter{} };
auto use_count = [&sp](char c) {
std::cout << c << ") use_count(): " << sp.use_count() << '\n';
};
use_count('A');
{
auto sp2 = sp;
use_count('B');
{
auto sp3 = sp;
use_count('C');
}
use_count('D');
}
use_count('E');
// sp.reset();
// use_count('F'); // would print "F) use_count(): 0"
}
```
Output:
```
S::S()
A) use_count(): 1
B) use_count(): 2
C) use_count(): 3
D) use_count(): 2
E) use_count(): 1
S::Deleter()
S::~S()
```
### See also
| | |
| --- | --- |
| [(destructor)](../weak_ptr/~weak_ptr "cpp/memory/weak ptr/~weak ptr") | destroys a `weak_ptr` (public member function of `std::weak_ptr<T>`) |
cpp std::get_deleter std::get\_deleter
=================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Deleter, class T >
Deleter* get_deleter( const std::shared_ptr<T>& p ) noexcept;
```
| | (since C++11) |
Access to the `p`'s deleter. If the shared pointer `p` owns a deleter of type cv-unqualified `Deleter` (e.g. if it was created with one of the constructors that take a deleter as a parameter), then returns a pointer to the deleter. Otherwise, returns a null pointer.
### Parameters
| | | |
| --- | --- | --- |
| p | - | a shared pointer whose deleter needs to be accessed |
### Return value
A pointer to the owned deleter or [`nullptr`](../../language/nullptr "cpp/language/nullptr"). The returned pointer is valid at least as long as there remains at least one `[shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` instance that owns it.
### Notes
The returned pointer may outlive the last `[shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` if, for example, `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")`s remain and the implementation doesn't destroy the deleter until the entire control block is destroyed.
### Example
demonstrates that `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` deleter is independent of the `[shared\_ptr](../shared_ptr "cpp/memory/shared ptr")`'s type.
```
#include <iostream>
#include <memory>
struct Foo { int i; };
void foo_deleter(Foo * p)
{
std::cout << "foo_deleter called!\n";
delete p;
}
int main()
{
std::shared_ptr<int> aptr;
{
// create a shared_ptr that owns a Foo and a deleter
auto foo_p = new Foo;
std::shared_ptr<Foo> r(foo_p, foo_deleter);
aptr = std::shared_ptr<int>(r, &r->i); // aliasing ctor
// aptr is now pointing to an int, but managing the whole Foo
} // r gets destroyed (deleter not called)
// obtain pointer to the deleter:
if(auto del_p = std::get_deleter<void(*)(Foo*)>(aptr))
{
std::cout << "shared_ptr<int> owns a deleter\n";
if(*del_p == foo_deleter)
std::cout << "...and it equals &foo_deleter\n";
} else
std::cout << "The deleter of shared_ptr<int> is null!\n";
} // deleter called here
```
Output:
```
shared_ptr<int> owns a deleter
...and it equals &foo_deleter
foo_deleter called!
```
### See also
| | |
| --- | --- |
| [(constructor)](shared_ptr "cpp/memory/shared ptr/shared ptr") | `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` constructors (public member function) |
| [get\_deleter](../unique_ptr/get_deleter "cpp/memory/unique ptr/get deleter") | returns the deleter that is used for destruction of the managed object (public member function of `std::unique_ptr<T,Deleter>`) |
cpp std::shared_ptr<T>::operator[] std::shared\_ptr<T>::operator[]
===============================
| | | |
| --- | --- | --- |
|
```
element_type& operator[]( std::ptrdiff_t idx ) const;
```
| | (since C++17) |
Index into the array pointed to by the stored pointer.
The behavior is undefined if the stored pointer is null or if `idx` is negative.
If `T` (the template parameter of `shared_ptr`) is an array type `U[N]`, `idx` must be less than `N`, otherwise the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| idx | - | the array index |
### Return value
A reference to the `idx`-th element of the array, i.e., `get()[idx]`
### Exceptions
Throws nothing.
### Remarks
When `T` is not an array type, it is unspecified whether this function is declared. If the function is declared, it is unspecified what its return type is, except that the declaration (although not necessarily the definition) of the function is guaranteed to be legal.
### Example
```
#include <cstddef>
#include <memory>
#include <iostream>
int main() {
const std::size_t arr_size = 10;
std::shared_ptr<int[]> pis(new int[10]{0,1,2,3,4,5,6,7,8,9});
for (std::size_t i = 0; i < arr_size; i++){
std::cout << pis[i] << ' ';
}
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
cpp std::hash(std::shared_ptr)
std::hash(std::shared\_ptr)
===========================
| | | |
| --- | --- | --- |
|
```
template<class T> struct hash<shared_ptr<T>>;
```
| | (since C++11) |
The template specialization of `[std::hash](../../utility/hash "cpp/utility/hash")` for `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` allows users to obtain hashes of objects of type `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>`.
For a given `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T> p`, this specialization ensures that.
| | |
| --- | --- |
| `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>>()(p) == [std::hash](http://en.cppreference.com/w/cpp/utility/hash)<T\*>()(p.get())`. | (until C++17) |
| `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>>()(p) == [std::hash](http://en.cppreference.com/w/cpp/utility/hash)<typename [std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type\*>()(p.get())`. | (since C++17) |
### Example
### See also
| | |
| --- | --- |
| [hash](../../utility/hash "cpp/utility/hash")
(C++11) | hash function object (class template) |
cpp std::shared_ptr<T>::swap std::shared\_ptr<T>::swap
=========================
| | | |
| --- | --- | --- |
|
```
void swap( shared_ptr& r ) noexcept;
```
| | (since C++11) |
Exchanges the stored pointer values and the ownerships of `*this` and `r`. Reference counts, if any, are not adjusted.
### Parameters
| | | |
| --- | --- | --- |
| r | - | smart pointer to exchange the contents with |
### Return value
(none).
### Example
```
#include <iostream>
#include <memory>
#include <string>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::shared_ptr<Foo> p1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> p2 = std::make_shared<Foo>(200);
auto print = [&]() {
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
p1.swap(p2);
print();
p1.reset();
print();
p1.swap(p2);
print();
}
```
Output:
```
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
~Foo...
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
```
cpp std::shared_ptr<T>::operator bool std::shared\_ptr<T>::operator bool
==================================
| | | |
| --- | --- | --- |
|
```
explicit operator bool() const noexcept;
```
| | |
Checks if `*this` stores a non-null pointer, i.e. whether `get() != nullptr`.
### Parameters
(none).
### Return value
`true` if `*this` stores a pointer, `false` otherwise.
### Notes
An empty shared\_ptr (where `use_count() == 0`) may store a non-null pointer accessible by `[get()](get "cpp/memory/shared ptr/get")`, e.g. if it were created using the aliasing constructor.
### Example
```
#include <iostream>
#include <memory>
void report(std::shared_ptr<int> ptr)
{
if (ptr) {
std::cout << "*ptr=" << *ptr << "\n";
} else {
std::cout << "ptr is not a valid pointer.\n";
}
}
int main()
{
std::shared_ptr<int> ptr;
report(ptr);
ptr = std::make_shared<int>(7);
report(ptr);
}
```
Output:
```
ptr is not a valid pointer.
*ptr=7
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
cpp std::shared_ptr<T>::operator*, std::shared_ptr<T>::operator-> std::shared\_ptr<T>::operator\*, std::shared\_ptr<T>::operator->
================================================================
| | | |
| --- | --- | --- |
|
```
T& operator*() const noexcept;
```
| (1) | (since C++11) |
|
```
T* operator->() const noexcept;
```
| (2) | (since C++11) |
Dereferences the stored pointer. The behavior is undefined if the stored pointer is null.
### Parameters
(none).
### Return value
1) The result of dereferencing the stored pointer, i.e., `*get()`
2) The stored pointer, i.e., `get()`
### Remarks
When `T` is a (possibly cv-qualified) `void`, it is unspecified whether function (1) is declared.
| | |
| --- | --- |
| When `T` is an array type, it is unspecified whether these member functions are declared, and if they are, what their return type is, except that the declaration (not necessarily the definition) of these functions is well-formed. | (since C++17) |
If either function is declared despite being unspecified, it is unspecified what its return type is, except that the declaration (although not necessarily the definition) of the function is guaranteed to be legal. This makes it possible to instantiate `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<void>`.
### Example
```
#include <iostream>
#include <memory>
struct Foo
{
Foo(int in) : a(in) {}
void print() const
{
std::cout << "a = " << a << '\n';
}
int a;
};
int main()
{
auto ptr = std::make_shared<Foo>(10);
ptr->print();
(*ptr).print();
}
```
Output:
```
a = 10
a = 10
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
| programming_docs |
cpp std::shared_ptr<T>::shared_ptr std::shared\_ptr<T>::shared\_ptr
================================
| | | |
| --- | --- | --- |
|
```
constexpr shared_ptr() noexcept;
```
| (1) | |
|
```
constexpr shared_ptr( std::nullptr_t ) noexcept;
```
| (2) | |
|
```
template< class Y >
explicit shared_ptr( Y* ptr );
```
| (3) | |
|
```
template< class Y, class Deleter >
shared_ptr( Y* ptr, Deleter d );
```
| (4) | |
|
```
template< class Deleter >
shared_ptr( std::nullptr_t ptr, Deleter d );
```
| (5) | |
|
```
template< class Y, class Deleter, class Alloc >
shared_ptr( Y* ptr, Deleter d, Alloc alloc );
```
| (6) | |
|
```
template< class Deleter, class Alloc >
shared_ptr( std::nullptr_t ptr, Deleter d, Alloc alloc );
```
| (7) | |
|
```
template< class Y >
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;
```
| (8) | |
|
```
template< class Y >
shared_ptr( shared_ptr<Y>&& r, element_type* ptr ) noexcept;
```
| (8) | (since C++20) |
|
```
shared_ptr( const shared_ptr& r ) noexcept;
```
| (9) | |
|
```
template< class Y >
shared_ptr( const shared_ptr<Y>& r ) noexcept;
```
| (9) | |
|
```
shared_ptr( shared_ptr&& r ) noexcept;
```
| (10) | |
|
```
template< class Y >
shared_ptr( shared_ptr<Y>&& r ) noexcept;
```
| (10) | |
|
```
template< class Y >
explicit shared_ptr( const std::weak_ptr<Y>& r );
```
| (11) | |
|
```
template< class Y >
shared_ptr( std::auto_ptr<Y>&& r );
```
| (12) | (removed in C++17) |
|
```
template< class Y, class Deleter >
shared_ptr( std::unique_ptr<Y, Deleter>&& r );
```
| (13) | |
Constructs new `shared_ptr` from a variety of pointer types that refer to an object to manage.
| | |
| --- | --- |
| For the purposes of the description below, a pointer type `Y*` is said to be *compatible with* a pointer type `T*` if either `Y*` is convertible to `T*` or `Y` is the array type `U[N]` and `T` is `U cv []` (where cv is some set of cv-qualifiers). | (since C++17) |
1-2) Constructs a `shared_ptr` with no managed object, i.e. empty `shared_ptr`
3-7) Constructs a `shared_ptr` with `ptr` as the pointer to the managed object.
| | |
| --- | --- |
| For (3-4,6), `Y*` must be convertible to `T*`. | (until C++17) |
| If `T` is an array type `U[N]`, (3-4,6) do not participate in overload resolution if `Y(*)[N]` is not convertible to `T*`. If `T` is an array type `U[]`, (3-4,6) do not participate in overload resolution if `Y(*)[]` is not convertible to `T*`. Otherwise, (3-4,6) do not participate in overload resolution if `Y*` is not convertible to `T*`. | (since C++17) |
Additionally:
3) Uses the [delete-expression](../../language/delete "cpp/language/delete") `delete ptr` if `T` is not an array type; `delete[] ptr` if `T` is an array type (since C++17) as the deleter. `Y` must be a complete type. The delete expression must be well-formed, have well-defined behavior and not throw any exceptions. This constructor additionally does not participate in overload resolution if the delete expression is not well-formed. (since C++17)
4-5) Uses the specified deleter `d` as the deleter. The expression `d(ptr)` must be well formed, have well-defined behavior and not throw any exceptions. The construction of `d` and of the stored deleter from `d` must not throw exceptions.
| | |
| --- | --- |
| `Deleter` must be [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | (until C++17) |
| These constructors additionally do not participate in overload resolution if the expression `d(ptr)` is not well-formed, or if `[std::is\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<D>::value` is `false`. | (since C++17) |
6-7) Same as (4-5), but additionally uses a copy of `alloc` for allocation of data for internal use. `Alloc` must be an [Allocator](../../named_req/allocator "cpp/named req/Allocator").
8) The *aliasing constructor*: constructs a `shared_ptr` which shares ownership information with the initial value of `r`, but holds an unrelated and unmanaged pointer `ptr`. If this `shared_ptr` is the last of the group to go out of scope, it will call the stored deleter for the object originally managed by `r`. However, calling `get()` on this `shared_ptr` will always return a copy of `ptr`. It is the responsibility of the programmer to make sure that this `ptr` remains valid as long as this shared\_ptr exists, such as in the typical use cases where `ptr` is a member of the object managed by `r` or is an alias (e.g., downcast) of `r.get()` For the second overload taking an rvalue, `r` is empty and `r.get() == nullptr` after the call. (since C++20)
9) Constructs a `shared_ptr` which shares ownership of the object managed by `r`. If `r` manages no object, `*this` manages no object either. The template overload doesn't participate in overload resolution if `Y*` is not implicitly convertible to (until C++17)*compatible with* (since C++17) `T*`.
10) Move-constructs a `shared_ptr` from `r`. After the construction, `*this` contains a copy of the previous state of `r`, `r` is empty and its stored pointer is null. The template overload doesn't participate in overload resolution if `Y*` is not implicitly convertible to (until C++17)*compatible with* (since C++17) `T*`.
11) Constructs a `shared_ptr` which shares ownership of the object managed by `r`. `Y*` must be implicitly convertible to `T*`. (until C++17)This overload participates in overload resolution only if `Y*` is compatible with `T*`. (since C++17) Note that `r.lock()` may be used for the same purpose: the difference is that this constructor throws an exception if the argument is empty, while `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>::lock()` constructs an empty `std::shared_ptr` in that case.
12) Constructs a `shared_ptr` that stores and owns the object formerly owned by `r`. `Y*` must be convertible to `T*`. After construction, `r` is empty.
13) Constructs a `shared_ptr` which manages the object currently managed by `r`. The deleter associated with `r` is stored for future deletion of the managed object. `r` manages no object after the call.
| | |
| --- | --- |
| This overload doesn't participate in overload resolution if `std::unique_ptr<Y, Deleter>::pointer` is not *compatible with* `T*`. If `r.get()` is a null pointer, this overload is equivalent to the default constructor (1). | (since C++17) |
If `Deleter` is a reference type, it is equivalent to `shared_ptr(r.release(), [std::ref](http://en.cppreference.com/w/cpp/utility/functional/ref)(r.get\_deleter())`. Otherwise, it is equivalent to `shared_ptr(r.release(), std::move(r.get_deleter()))` When `T` is not an array type, the overloads (3), (4), and (6) enable `shared_from_this` with `ptr`, and the overload (13) enables `shared_from_this` with the pointer returned by `r.release()`.
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | a pointer to an object to manage |
| d | - | a deleter to use to destroy the object |
| alloc | - | an allocator to use for allocations of data for internal use |
| r | - | another smart pointer to share the ownership to or acquire the ownership from |
### Exceptions
3) `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if required additional memory could not be obtained. May throw implementation-defined exception for other errors. If an exception occurs, this calls `delete ptr` if `T` is not an array type, and calls `delete[] ptr` otherwise (since C++17).
4-7) `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if required additional memory could not be obtained. May throw implementation-defined exception for other errors. `d(ptr)` is called if an exception occurs.
11) `[std::bad\_weak\_ptr](../bad_weak_ptr "cpp/memory/bad weak ptr")` if `r.expired() == true`. The constructor has no effect in this case.
12) `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if required additional memory could not be obtained. May throw implementation-defined exception for other errors. This constructor has no effect if an exception occurs.
13) If an exception is thrown, the constructor has no effects. ### Notes
A constructor *enables `shared_from_this`* with a pointer `ptr` of type `U*` means that it determines if `U` has an unambiguous and accessible (since C++17) base class that is a specialization of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`, and if so, the constructor evaluates the statement:
```
if (ptr != nullptr && ptr->weak_this.expired())
ptr->weak_this = std::shared_ptr<std::remove_cv_t<U>>(*this,
const_cast<std::remove_cv_t<U>*>(ptr));
```
Where `*weak\_this*` is the hidden mutable `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` member of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`. The assignment to the `*weak\_this*` member is not atomic and conflicts with any potentially concurrent access to the same object. This ensures that future calls to [`shared_from_this()`](../enable_shared_from_this/shared_from_this "cpp/memory/enable shared from this/shared from this") would share ownership with the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` created by this raw pointer constructor.
The test `ptr->weak_this.expired()` in the exposition code above makes sure that `*weak\_this*` is not reassigned if it already indicates an owner. This test is required as of C++17.
The raw pointer overloads assume ownership of the pointed-to object. Therefore, constructing a `shared_ptr` using the raw pointer overload for an object that is already managed by a `shared_ptr`, such as by `shared_ptr(ptr.get())` is likely to lead to undefined behavior, even if the object is of a type derived from `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`.
Because the default constructor is `constexpr`, static shared\_ptrs are initialized as part of [static non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization"), before any dynamic non-local initialization begins. This makes it safe to use a shared\_ptr in a constructor of any static object.
In C++11 and C++14 it is valid to construct a `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>` from a `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<T[]>`:
```
std::unique_ptr<int[]> arr(new int[1]);
std::shared_ptr<int> ptr(std::move(arr));
```
Since the `shared_ptr` obtains its deleter (a `[std::default\_delete](http://en.cppreference.com/w/cpp/memory/default_delete)<T[]>` object) from the `[std::unique\_ptr](../unique_ptr "cpp/memory/unique ptr")`, the array will be correctly deallocated.
This is no longer allowed in C++17. Instead the array form `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T[]>` should be used.
### Example
```
#include <memory>
#include <iostream>
struct Foo {
int id{0};
Foo(int i = 0) : id{i} { std::cout << "Foo::Foo(" << i << ")\n"; }
~Foo() { std::cout << "Foo::~Foo(), id=" << id << '\n'; }
};
struct D {
void operator()(Foo* p) const {
std::cout << "Call delete from function object. Foo::id=" << p->id << '\n';
delete p;
}
};
int main()
{
{
std::cout << "1) constructor with no managed object\n";
std::shared_ptr<Foo> sh1;
}
{
std::cout << "2) constructor with object\n";
std::shared_ptr<Foo> sh2(new Foo{10});
std::cout << "sh2.use_count(): " << sh2.use_count() << '\n';
std::shared_ptr<Foo> sh3(sh2);
std::cout << "sh2.use_count(): " << sh2.use_count() << '\n';
std::cout << "sh3.use_count(): " << sh3.use_count() << '\n';
}
{
std::cout << "3) constructor with object and deleter\n";
std::shared_ptr<Foo> sh4(new Foo{11}, D());
std::shared_ptr<Foo> sh5(new Foo{12}, [](auto p) {
std::cout << "Call delete from lambda... p->id=" << p->id << "\n";
delete p;
});
}
}
```
Output:
```
1) constructor with no managed object
2) constructor with object
Foo::Foo(10)
sh2.use_count(): 1
sh2.use_count(): 2
sh3.use_count(): 2
Foo::~Foo(), id=10
3) constructor with object and deleter
Foo::Foo(11)
Foo::Foo(12)
Call delete from lambda... p->id=12
Foo::~Foo(), id=12
Call delete from function object. Foo::id=11
Foo::~Foo(), id=11
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3548](https://cplusplus.github.io/LWG/issue3548) | C++11 | the constructor from `unique_ptr` copy-constructed the deleter | move-constructs instead |
### See also
| | |
| --- | --- |
| [make\_sharedmake\_shared\_for\_overwrite](make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
| [allocate\_sharedallocate\_shared\_for\_overwrite](allocate_shared "cpp/memory/shared ptr/allocate shared")
(C++20) | creates a shared pointer that manages a new object allocated using an allocator (function template) |
| [enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")
(C++11) | allows an object to create a `shared_ptr` referring to itself (class template) |
cpp std::make_shared, std::make_shared_for_overwrite std::make\_shared, std::make\_shared\_for\_overwrite
====================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
```
| (1) | (since C++11) (T is not array) |
|
```
template< class T >
shared_ptr<T> make_shared( std::size_t N );
```
| (2) | (since C++20) (T is U[]) |
|
```
template< class T >
shared_ptr<T> make_shared();
```
| (3) | (since C++20) (T is U[N]) |
|
```
template< class T >
shared_ptr<T> make_shared( std::size_t N, const std::remove_extent_t<T>& u );
```
| (4) | (since C++20) (T is U[]) |
|
```
template< class T >
shared_ptr<T> make_shared( const std::remove_extent_t<T>& u );
```
| (5) | (since C++20) (T is U[N]) |
|
```
template< class T >
shared_ptr<T> make_shared_for_overwrite();
```
| (6) | (since C++20) (T is not U[]) |
|
```
template< class T >
shared_ptr<T> make_shared_for_overwrite( std::size_t N );
```
| (7) | (since C++20) (T is U[]) |
1) Constructs an object of type `T` and wraps it in a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` using `args` as the parameter list for the constructor of `T`. The object is constructed as if by the expression `::new (pv) T([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `pv` is an internal `void*` pointer to storage suitable to hold an object of type `T`. The storage is typically larger than `sizeof(T)` in order to use one allocation for both the control block of the shared pointer and the `T` object. The `std::shared_ptr` constructor called by this function enables `shared_from_this` with a pointer to the newly constructed object of type `T`.
| | |
| --- | --- |
| This overload participates in overload resolution only if T is not an array type. | (since C++20) |
2,3) Same as (1), but the object constructed is a possibly-multidimensional array whose non-array elements of type `std::remove_all_extents_t<T>` are value-initialized as if by placement-new expression `::new(pv) [std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>()`. The overload (2) creates an array of size `N` along the first dimension. The array elements are initialized in ascending order of their addresses, and when their lifetime ends are destroyed in the reverse order of their original construction.
4,5) Same as (2,3), but every element is initialized from the default value `u`. If `U` is not an array type, then this is performed as if by the same placement-new expression as in (1); otherwise, this is performed as if by initializing every non-array element of the (possibly multidimensional) array with the corresponding element from `u` with the same placement-new expression as in (1). The overload (4) creates an array of size `N` along the first dimension. The array elements are initialized in ascending order of their addresses, and when their lifetime ends are destroyed in the reverse order of their original construction.
6) Same as (1) if `T` is not an array type and (3) if `T` is `U[N]`, except that the created object is [default-initialized](../../language/default_initialization "cpp/language/default initialization").
7) Same as (2), except that the individual array elements are [default-initialized](../../language/default_initialization "cpp/language/default initialization"). In each case, the object (or individual elements if `T` is an array type) (since C++20) will be destroyed by `p->~X()`, where `p` is a pointer to the object and `X` is its type.
### Parameters
| | | |
| --- | --- | --- |
| args | - | list of arguments with which an instance of `T` will be constructed. |
| N | - | array size to use |
| u | - | the initial value to initialize every element of the array |
### Return value
`[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` of an instance of type `T`.
### Exceptions
May throw `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` or any exception thrown by the constructor of `T`. If an exception is thrown, the functions have no effect. If an exception is thrown during the construction of the array, already-initialized elements are destroyed in reverse order. (since C++20).
### Notes
This function may be used as an alternative to `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(new T(args...))`. The trade-offs are:
* `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(new T(args...))` performs at least two allocations (one for the object `T` and one for the control block of the shared pointer), while `std::make_shared<T>` typically performs only one allocation (the standard recommends, but does not require this; all known implementations do this)
* If any `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` references the control block created by `std::make_shared` after the lifetime of all shared owners ended, the memory occupied by `T` persists until all weak owners get destroyed as well, which may be undesirable if `sizeof(T)` is large.
* `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(new T(args...))` may call a non-public constructor of `T` if executed in context where it is accessible, while `std::make_shared` requires public access to the selected constructor.
* Unlike the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` constructors, `std::make_shared` does not allow a custom deleter.
* `std::make_shared` uses `::new`, so if any special behavior has been set up using a class-specific [`operator new`](../new/operator_new "cpp/memory/new/operator new"), it will differ from `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>(new T(args...))`.
| | |
| --- | --- |
| * `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` supports array types (as of C++17), but `std::make_shared` does not. This functionality is supported by [`boost::make_shared`](http://www.boost.org/doc/libs/1_66_0/libs/smart_ptr/doc/html/smart_ptr.html#make_shared)
| (until C++20) |
| | |
| --- | --- |
| * code such as `f([std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<int>(new int(42)), g())` can cause a memory leak if `g` gets called after `new int(42)` and throws an exception, while `f(std::make_shared<int>(42), g())` is safe, since two function calls are [never interleaved](../../language/eval_order "cpp/language/eval order").
| (until C++17) |
A constructor *enables `shared_from_this`* with a pointer `ptr` of type `U*` means that it determines if `U` has an unambiguous and accessible (since C++17) base class that is a specialization of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`, and if so, the constructor evaluates the statement:
```
if (ptr != nullptr && ptr->weak_this.expired())
ptr->weak_this = std::shared_ptr<std::remove_cv_t<U>>(*this,
const_cast<std::remove_cv_t<U>*>(ptr));
```
Where `*weak\_this*` is the hidden mutable `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` member of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`. The assignment to the `*weak\_this*` member is not atomic and conflicts with any potentially concurrent access to the same object. This ensures that future calls to [`shared_from_this()`](../enable_shared_from_this/shared_from_this "cpp/memory/enable shared from this/shared from this") would share ownership with the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` created by this raw pointer constructor.
The test `ptr->weak_this.expired()` in the exposition code above makes sure that `*weak\_this*` is not reassigned if it already indicates an owner. This test is required as of C++17.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_shared_ptr_arrays`](../../feature_test#Library_features "cpp/feature test") | `201707L` | (C++20) | for overloads (2-5) |
| [`__cpp_lib_smart_ptr_for_overwrite`](../../feature_test#Library_features "cpp/feature test") | `202002L` | (C++20) | for overloads (6,7) |
### Example
```
#include <memory>
#include <vector>
#include <iostream>
#include <type_traits>
struct C
{
// constructors needed (until C++20)
C(int i) : i(i) {}
C(int i, float f) : i(i), f(f) {}
int i;
float f{};
};
int main()
{
// using `auto` for the type of `sp1`
auto sp1 = std::make_shared<C>(1); // overload (1)
static_assert(std::is_same_v<decltype(sp1), std::shared_ptr<C>>);
std::cout << "sp1->{ i:" << sp1->i << ", f:" << sp1->f << " }\n";
// being explicit with the type of `sp2`
std::shared_ptr<C> sp2 = std::make_shared<C>(2, 3.0f); // overload (1)
static_assert(std::is_same_v<decltype(sp2), std::shared_ptr<C>>);
static_assert(std::is_same_v<decltype(sp1), decltype(sp2)>);
std::cout << "sp2->{ i:" << sp2->i << ", f:" << sp2->f << " }\n";
// shared_ptr to a value-initialized float[64]; overload (2):
std::shared_ptr<float[]> sp3 = std::make_shared<float[]>(64);
// shared_ptr to a value-initialized long[5][3][4]; overload (2):
std::shared_ptr<long[][3][4]> sp4 = std::make_shared<long[][3][4]>(5);
// shared_ptr to a value-initialized short[128]; overload (3):
std::shared_ptr<short[128]> sp5 = std::make_shared<short[128]>();
// shared_ptr to a value-initialized int[7][6][5]; overload (3):
std::shared_ptr<int[7][6][5]> sp6 = std::make_shared<int[7][6][5]>();
// shared_ptr to a double[256], where each element is 2.0; overload (4):
std::shared_ptr<double[]> sp7 = std::make_shared<double[]>(256, 2.0);
// shared_ptr to a double[7][2], where each double[2] element is {3.0, 4.0}; overload (4):
std::shared_ptr<double[][2]> sp8 = std::make_shared<double[][2]>(7, {3.0, 4.0});
// shared_ptr to a vector<int>[4], where each vector has contents {5, 6}; overload (4):
std::shared_ptr<std::vector<int>[]> sp9 = std::make_shared<std::vector<int>[]>(4, {5, 6});
// shared_ptr to a float[512], where each element is 1.0; overload (5):
std::shared_ptr<float[512]> spA = std::make_shared<float[512]>(1.0);
// shared_ptr to a double[6][2], where each double[2] element is {1.0, 2.0}; overload (5):
std::shared_ptr<double[6][2]> spB = std::make_shared<double[6][2]>({1.0, 2.0});
// shared_ptr to a vector<int>[4], where each vector has contents {5, 6}; overload (5):
std::shared_ptr<std::vector<int>[4]> spC = std::make_shared<std::vector<int>[4]>({5, 6});
}
```
Output:
```
sp1->{ i:1, f:0 }
sp2->{ i:2, f:3 }
```
### See also
| | |
| --- | --- |
| [(constructor)](shared_ptr "cpp/memory/shared ptr/shared ptr") | constructs new `shared_ptr` (public member function) |
| [allocate\_sharedallocate\_shared\_for\_overwrite](allocate_shared "cpp/memory/shared ptr/allocate shared")
(C++20) | creates a shared pointer that manages a new object allocated using an allocator (function template) |
| [make\_uniquemake\_unique\_for\_overwrite](../unique_ptr/make_unique "cpp/memory/unique ptr/make unique")
(C++14)(C++20) | creates a unique pointer that manages a new object (function template) |
| [operator newoperator new[]](../new/operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| programming_docs |
cpp std::swap(std::shared_ptr)
std::swap(std::shared\_ptr)
===========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
void swap( std::shared_ptr<T>& lhs, std::shared_ptr<T>& rhs ) noexcept;
```
| | (since C++11) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | smart pointers whose contents to swap |
### Return value
(none).
### Complexity
Constant.
### Example
```
#include <iostream>
#include <memory>
#include <string>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::shared_ptr<Foo> p1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> p2 = std::make_shared<Foo>(200);
auto print = [&]() {
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
std::swap(p1, p2);
print();
p1.reset();
print();
std::swap(p1, p2);
print();
}
```
Output:
```
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
~Foo...
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap](swap "cpp/memory/shared ptr/swap") | swaps the contents (public member function) |
cpp std::shared_ptr<T>::operator= std::shared\_ptr<T>::operator=
==============================
| | | |
| --- | --- | --- |
|
```
shared_ptr& operator=( const shared_ptr& r ) noexcept;
```
| (1) | |
|
```
template< class Y >
shared_ptr& operator=( const shared_ptr<Y>& r ) noexcept;
```
| (1) | |
|
```
shared_ptr& operator=( shared_ptr&& r ) noexcept;
```
| (2) | |
|
```
template< class Y >
shared_ptr& operator=( shared_ptr<Y>&& r ) noexcept;
```
| (2) | |
|
```
template< class Y >
shared_ptr& operator=( std::auto_ptr<Y>&& r );
```
| (3) | (deprecated in C++11) (removed in C++17) |
|
```
template< class Y, class Deleter >
shared_ptr& operator=( std::unique_ptr<Y,Deleter>&& r );
```
| (4) | |
Replaces the managed object with the one managed by `r`.
If `*this` already owns an object and it is the last `shared_ptr` owning it, and `r` is not the same as `*this`, the object is destroyed through the owned deleter.
1) Shares ownership of the object managed by `r`. If `r` manages no object, `*this` manages no object too. Equivalent to `shared_ptr<T>(r).swap(*this)`.
2) Move-assigns a `shared_ptr` from `r`. After the assignment, `*this` contains a copy of the previous state of `r`, and `r` is empty. Equivalent to `shared_ptr<T>(std::move(r)).swap(*this)`.
3) Transfers the ownership of the object managed by `r` to `*this`. If `r` manages no object, `*this` manages no object too. After the assignment, `*this` contains the pointer previously held by `r`, and `use_count()==1`; also `r` is empty. Equivalent to `shared_ptr<T>(r).swap(*this)`.
4) Transfers the ownership of the object managed by `r` to `*this`. The deleter associated to `r` is stored for future deletion of the managed object. `r` manages no object after the call. Equivalent to `shared_ptr<T>(std::move(r)).swap(*this)`. ### Parameters
| | | |
| --- | --- | --- |
| r | - | another smart pointer to share the ownership to or acquire the ownership from |
### Return value
`*this`.
### Notes
The implementation may meet the requirements without creating a temporary `shared_ptr` object.
### Exceptions
3-4) May throw implementation-defined exceptions. ### Example
### See also
| | |
| --- | --- |
| [reset](reset "cpp/memory/shared ptr/reset") | replaces the managed object (public member function) |
cpp std::allocate_shared, std::allocate_shared_for_overwrite std::allocate\_shared, std::allocate\_shared\_for\_overwrite
============================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc, class... Args >
shared_ptr<T> allocate_shared( const Alloc& alloc, Args&&... args );
```
| (1) | (since C++11) (T is non-array) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared( const Alloc& alloc, std::size_t N );
```
| (2) | (since C++20) (T is U[]) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared( const Alloc& alloc );
```
| (3) | (since C++20) (T is U[N]) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared( const Alloc& alloc, std::size_t N,
const std::remove_extent_t<T>& u );
```
| (4) | (since C++20) (T is U[]) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared( const Alloc& alloc,
const std::remove_extent_t<T>& u );
```
| (5) | (since C++20) (T is U[N]) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared_for_overwrite( const Alloc& alloc );
```
| (6) | (since C++20) (T is not U[]) |
|
```
template< class T, class Alloc >
shared_ptr<T> allocate_shared_for_overwrite( const Alloc& alloc, std::size_t N );
```
| (7) | (since C++20) (T is U[]) |
1) Constructs an object of type `T` and wraps it in a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` using `args` as the parameter list for the constructor of `T`. The object is constructed as if by the expression `::new (pv) T(v)` (until C++20)`[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A2>::construct(a, pv, v)` (since C++20), where `pv` is an internal `void*` pointer to storage suitable to hold an object of type `T` and `a` is a copy of the allocator rebound to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>`. The storage is typically larger than `sizeof(T)` in order to use one allocation for both the control block of the shared pointer and the `T` object. The `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` constructor called by this function enables `shared_from_this` with a pointer to the newly constructed object of type `T`. All memory allocation is done using a copy of `alloc`, which must satisfy the [Allocator](../../named_req/allocator "cpp/named req/Allocator") requirements. This overload participates in overload resolution only if T is not an array type
2,3) Same as (1), but the object constructed is a possibly-multidimensional array whose every non-array element is initialized as if by the expression `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A2>::construct(a2, pv)` where `a2` of type `A2` is the copy of the allocator rebound to manage objects of type `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>>`. The overload (2) creates an array of size `N` along its first dimension. The array elements are initialized in ascending order of their addresses, and when their lifetime ends are destroyed in the reverse order of their original construction.
4,5) Same as (2,3), but the elements of the array are initialized from the default value `u`. If `[std::remove\_extent\_t](http://en.cppreference.com/w/cpp/types/remove_extent)<T>` is not itself an array type, then this is performed as if by the same allocator expression as in (1), except that the allocator is rebound to the `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>>`. Otherwise, this is performed as if by initializing every non-array element of the (possibly multidimensional) array with the corresponding element from `u` using the same allocator expression as in (1), except that the allocator is rebound to the type `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_all\_extents\_t](http://en.cppreference.com/w/cpp/types/remove_all_extents)<T>>`. The overload (4) creates an array of size `N` along the first dimension. The array elements are initialized in ascending order of their addresses, and when their lifetime ends are destroyed in the reverse order of their original construction.
6) Same as (1) if `T` is not an array type and (3) if `T` is `U[N]`, except that the created object is [default-initialized](../../language/default_initialization "cpp/language/default initialization").
7) Same as (2), except that the individual array elements are [default-initialized](../../language/default_initialization "cpp/language/default initialization"). For `allocate_shared`, the object (or the individual array elements for (2-5)) (since C++20) are destroyed via the expression `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A2>::destroy(a, p)`, where `p` is a pointer to the object and `a` is a copy of the allocator passed to `allocate_shared`, rebound to the type of the object being destroyed.
| | |
| --- | --- |
| For `allocate_shared_for_overwrite`, the object (or individual elements if `T` is an array type) will be destroyed by `p->~X()`, where `p` is a pointer to the object and `X` is its type. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| alloc | - | The [Allocator](../../named_req/allocator "cpp/named req/Allocator") to use. |
| args... | - | list of arguments with which an instance of `T` will be constructed. |
| N | - | array size to use |
| u | - | the initial value to initialize every element of the array |
### Return value
`[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` of an instance of type `T`.
### Exceptions
Can throw the exceptions thrown from `Alloc::allocate()` or from the constructor of `T`. If an exception is thrown, (1) has no effect. If an exception is thrown during the construction of the array, already-initialized elements are destroyed in reverse order (since C++20).
### Notes
Like `[std::make\_shared](make_shared "cpp/memory/shared ptr/make shared")`, this function typically performs only one allocation, and places both the `T` object and the control block in the allocated memory block (the standard recommends but does not require this, all known implementations do this). A copy of `alloc` is stored as part of the control block so that it can be used to deallocate it once both shared and weak reference counts reach zero.
Unlike the `std::shared_ptr` [`constructors`](shared_ptr "cpp/memory/shared ptr/shared ptr"), `std::allocate_shared` does not accept a separate custom deleter: the supplied allocator is used for destruction of the control block and the `T` object, and for deallocation of their shared memory block.
| | |
| --- | --- |
| `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` supports array types (as of C++17), but `std::allocate_shared` does not. This functionality is supported by [`boost::allocate_shared`](http://www.boost.org/doc/libs/1_66_0/libs/smart_ptr/doc/html/smart_ptr.html#make_shared). | (until C++20) |
A constructor *enables `shared_from_this`* with a pointer `ptr` of type `U*` means that it determines if `U` has an unambiguous and accessible (since C++17) base class that is a specialization of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`, and if so, the constructor evaluates the statement:
```
if (ptr != nullptr && ptr->weak_this.expired())
ptr->weak_this = std::shared_ptr<std::remove_cv_t<U>>(*this,
const_cast<std::remove_cv_t<U>*>(ptr));
```
Where `*weak\_this*` is the hidden mutable `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` member of `[std::enable\_shared\_from\_this](../enable_shared_from_this "cpp/memory/enable shared from this")`. The assignment to the `*weak\_this*` member is not atomic and conflicts with any potentially concurrent access to the same object. This ensures that future calls to [`shared_from_this()`](../enable_shared_from_this/shared_from_this "cpp/memory/enable shared from this/shared from this") would share ownership with the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` created by this raw pointer constructor.
The test `ptr->weak_this.expired()` in the exposition code above makes sure that `*weak\_this*` is not reassigned if it already indicates an owner. This test is required as of C++17.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment |
| --- | --- |
| [`__cpp_lib_smart_ptr_for_overwrite`](../../feature_test#Library_features "cpp/feature test") | for overloads (6,7) |
### See also
| | |
| --- | --- |
| [(constructor)](shared_ptr "cpp/memory/shared ptr/shared ptr") | constructs new `shared_ptr` (public member function) |
| [make\_sharedmake\_shared\_for\_overwrite](make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
cpp std::atomic_...<std::shared_ptr>
std::atomic\_...<std::shared\_ptr>
==================================
| | | |
| --- | --- | --- |
|
```
template< class T >
bool atomic_is_lock_free( const std::shared_ptr<T>* p );
```
| (1) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
std::shared_ptr<T> atomic_load( const std::shared_ptr<T>* p );
```
| (2) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
std::shared_ptr<T> atomic_load_explicit( const std::shared_ptr<T>* p,
std::memory_order mo );
```
| (3) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
void atomic_store( std::shared_ptr<T>* p,
std::shared_ptr<T> r );
```
| (4) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
void atomic_store_explicit( std::shared_ptr<T>* p,
std::shared_ptr<T> r,
std::memory_order mo);
```
| (5) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
std::shared_ptr<T> atomic_exchange( std::shared_ptr<T>* p,
std::shared_ptr<T> r);
```
| (6) | (since C++11) (deprecated in C++20) |
|
```
template<class T>
std::shared_ptr<T> atomic_exchange_explicit( std::shared_ptr<T>* p,
std::shared_ptr<T> r,
std::memory_order mo);
```
| (7) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
bool atomic_compare_exchange_weak( std::shared_ptr<T>* p,
std::shared_ptr<T>* expected,
std::shared_ptr<T> desired);
```
| (8) | (since C++11) (deprecated in C++20) |
|
```
template<class T>
bool atomic_compare_exchange_strong( std::shared_ptr<T>* p,
std::shared_ptr<T>* expected,
std::shared_ptr<T> desired);
```
| (9) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
bool atomic_compare_exchange_strong_explicit( std::shared_ptr<T>* p,
std::shared_ptr<T>* expected,
std::shared_ptr<T> desired,
std::memory_order success,
std::memory_order failure);
```
| (10) | (since C++11) (deprecated in C++20) |
|
```
template< class T >
bool atomic_compare_exchange_weak_explicit( std::shared_ptr<T>* p,
std::shared_ptr<T>* expected,
std::shared_ptr<T> desired,
std::memory_order success,
std::memory_order failure);
```
| (11) | (since C++11) (deprecated in C++20) |
If multiple threads of execution access the same `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` object without synchronization and any of those accesses uses a non-const member function of `shared_ptr` then a data race will occur unless all such access is performed through these functions, which are overloads of the corresponding atomic access functions (`[std::atomic\_load](../../atomic/atomic_load "cpp/atomic/atomic load")`, `[std::atomic\_store](../../atomic/atomic_store "cpp/atomic/atomic store")`, etc.).
Note that the control block of a shared\_ptr is thread-safe: different `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` objects can be accessed using mutable operations, such as operator= or reset, simultaneously by multiple threads, even when these instances are copies, and share the same control block internally.
1) Determines whether atomic access to the shared pointer pointed-to by `p` is lock-free.
2) Equivalent to `atomic_load_explicit(p, [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`
3) Returns the shared pointer pointed-to by `p`. As with the non-specialized `[std::atomic\_load\_explicit](../../atomic/atomic_load "cpp/atomic/atomic load")`, `mo` cannot be `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`
4) Equivalent to `atomic_store_explicit(p, r, memory_order_seq_cst)`
5) Stores the shared pointer `r` in the shared pointer pointed-to by `p` atomically, effectively executing `p->swap(r)`. As with the non-specialized `[std::atomic\_store\_explicit](../../atomic/atomic_store "cpp/atomic/atomic store")`, `mo` cannot be `[std::memory\_order\_acquire](../../atomic/memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`.
6) Equivalent to `atomic_exchange_explicit(p, r, memory_order_seq_cst)`
7) Stores the shared pointer `r` in the shared pointer pointed to by `p` and returns the value formerly pointed-to by `p`, atomically. Effectively executes `p->swap(r)` and returns a copy of `r` after the swap.
8) Equivalent to `atomic_compare_exchange_weak_explicit(p, expected, desired, [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order), [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`
9) Equivalent to `atomic_compare_exchange_strong_explicit(p, expected, desired, [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order), [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`
10) Compares the shared pointers pointed-to by `p` and `expected`. If they are equivalent (store the same pointer value, and either share ownership of the same object or are both empty), assigns `desired` into `*p` using the memory ordering constraints specified by `success` and returns `true`. If they are not equivalent, assigns `*p` into `*expected` using the memory ordering constraints specified by `failure` and returns `false`.
11) Same as 10), but may fail spuriously. All these functions invoke undefined behavior if `p` is a null pointer.
### Parameters
| | | |
| --- | --- | --- |
| p, expected | - | a pointer to a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` |
| r, desired | - | a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` |
| mo, success, failure | - | memory ordering selectors of type `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")` |
### Exceptions
These functions do not throw exceptions.
### Return value
1) `true` if atomic access is implemented using lock-free instructions
2,3) A copy of the pointed-to shared pointer.
4,5) (none)
6,7) A copy of the formerly pointed-to shared pointer
8,9,10,11) `true` if the shared pointers were equivalent and the exchange was performed, `false` otherwise. ### Notes
These functions are typically implemented using mutexes, stored in a global hash table where the pointer value is used as the key.
To avoid data races, once a shared pointer is passed to any of these functions, it cannot be accessed non-atomically. In particular, you cannot dereference such a shared\_ptr without first atomically loading it into another shared\_ptr object, and then dereferencing through the second object.
The [Concurrency TS](https://en.cppreference.com/w/cpp/experimental/concurrency "cpp/experimental/concurrency") offers atomic smart pointer classes `atomic_shared_ptr` and `atomic_weak_ptr` as a replacement for the use of these functions.
| | |
| --- | --- |
| These functions were deprecated in favor of the specializations of the `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` template: `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)>` and `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)>`. | (since C++20) |
### Example
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2980](https://cplusplus.github.io/LWG/issue2980) | C++11 | empty `shared_ptr`s are never equivalent | equivalent if they store the same pointer value |
### See also
| | |
| --- | --- |
| [atomic\_is\_lock\_free](../../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free")
(C++11) | checks if the atomic type's operations are lock-free (function template) |
| [atomic\_storeatomic\_store\_explicit](../../atomic/atomic_store "cpp/atomic/atomic store")
(C++11)(C++11) | atomically replaces the value of the atomic object with a non-atomic argument (function template) |
| [atomic\_loadatomic\_load\_explicit](../../atomic/atomic_load "cpp/atomic/atomic load")
(C++11)(C++11) | atomically obtains the value stored in an atomic object (function template) |
| [atomic\_exchangeatomic\_exchange\_explicit](../../atomic/atomic_exchange "cpp/atomic/atomic exchange")
(C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) |
| [atomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicitatomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicit](../../atomic/atomic_compare_exchange "cpp/atomic/atomic compare exchange")
(C++11)(C++11)(C++11)(C++11) | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template) |
| programming_docs |
cpp std::shared_ptr<T>::use_count std::shared\_ptr<T>::use\_count
===============================
| | | |
| --- | --- | --- |
|
```
long use_count() const noexcept;
```
| | |
Returns the number of different `shared_ptr` instances (`this` included) managing the current object. If there is no managed object, `0` is returned.
In multithreaded environment, the value returned by `use_count` is approximate (typical implementations use a [memory\_order\_relaxed](../../atomic/memory_order "cpp/atomic/memory order") load).
### Parameters
(none).
### Return value
the number of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` instances managing the current object or `0` if there is no managed object.
### Notes
Common use cases include.
* comparison with `0`. If `use_count` returns zero, the shared pointer is *empty* and manages no objects (whether or not its stored pointer is [`nullptr`](../../language/nullptr "cpp/language/nullptr")).
* comparison with `1`. If `use_count` returns 1, there are no other owners. The deprecated (since C++17) member function `[unique()](unique "cpp/memory/shared ptr/unique")` is provided for this use case. (until C++20) In multithreaded environment, this does not imply that the object is safe to modify because accesses to the managed object by former shared owners may not have completed, and because new shared owners may be introduced concurrently, such as by `[std::weak\_ptr::lock](../weak_ptr/lock "cpp/memory/weak ptr/lock")`.
### Example
```
#include <memory>
#include <iostream>
void fun(std::shared_ptr<int> sp)
{
std::cout << "in fun(): sp.use_count() == " << sp.use_count()
<< " (object @ " << sp << ")\n";
}
int main()
{
auto sp1 = std::make_shared<int>(5);
std::cout << "in main(): sp1.use_count() == " << sp1.use_count()
<< " (object @ " << sp1 << ")\n";
fun(sp1);
}
```
Possible output:
```
in main(): sp1.use_count() == 1 (object @ 0x20eec30)
in fun(): sp.use_count() == 2 (object @ 0x20eec30)
```
### See also
| | |
| --- | --- |
| [unique](unique "cpp/memory/shared ptr/unique")
(until C++20) | checks whether the managed object is managed only by the current `shared_ptr` instance (public member function) |
cpp operator==, !=, <, <=, >, >=, <=> (std::shared_ptr)
operator==, !=, <, <=, >, >=, <=> (std::shared\_ptr)
====================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| Compare two `shared_ptr` objects | | |
|
```
template < class T, class U >
bool operator==( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (1) | (since C++11) |
|
```
template< class T, class U >
bool operator!=( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (2) | (since C++11) (until C++20) |
|
```
template< class T, class U >
bool operator<( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (3) | (since C++11) (until C++20) |
|
```
template< class T, class U >
bool operator>( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (4) | (since C++11) (until C++20) |
|
```
template< class T, class U >
bool operator<=( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (5) | (since C++11) (until C++20) |
|
```
template< class T, class U >
bool operator>=( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (6) | (since C++11) (until C++20) |
|
```
template< class T, class U >
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs,
const std::shared_ptr<U>& rhs ) noexcept;
```
| (7) | (since C++20) |
| Compare a `shared_ptr` with a null pointer | | |
|
```
template< class T >
bool operator==( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (8) | (since C++11) |
|
```
template< class T >
bool operator==( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (9) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator!=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (10) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator!=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (11) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator<( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (12) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator<( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (13) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator>( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (14) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator>( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (15) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator<=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (16) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator<=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (17) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator>=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
```
| (18) | (since C++11) (until C++20) |
|
```
template< class T >
bool operator>=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
```
| (19) | (since C++11) (until C++20) |
|
```
template< class T >
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs,
std::nullptr_t ) noexcept;
```
| (20) | (since C++20) |
Compares two `shared_ptr<T>` objects or compares `shared_ptr<T>` with a null pointer.
Note that the comparison operators for `shared_ptr` simply compare pointer values; the actual objects pointed to are *not* compared. Having `operator<` defined for `shared_ptr` allows `shared_ptr`s to be used as keys in associative containers, like `[std::map](../../container/map "cpp/container/map")` and `[std::set](../../container/set "cpp/container/set")`.
| | |
| --- | --- |
| The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs | - | the left-hand `shared_ptr` to compare |
| rhs | - | the right-hand `shared_ptr` to compare |
### Return value
1) `lhs.get() == rhs.get()`
2) `!(lhs == rhs)`
3) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<V>()(lhs.get(), rhs.get())`, where V is the [composite pointer type](../../language/operator_comparison#Pointer_comparison_operators "cpp/language/operator comparison") of `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type\*` and `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<U>::element\_type\*`
4) `rhs < lhs`
5) `!(rhs < lhs)`
6) `!(lhs < rhs)`
7) `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way){}(x.get(), y.get())`
8) `!lhs`
9) `!rhs`
10) `(bool)lhs`
11) `(bool)rhs`
12) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type\*>()(lhs.get(), nullptr)`
13) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type\*>()(nullptr, rhs.get())`
14) `nullptr < lhs`
15) `rhs < nullptr`
16) `!(nullptr < lhs)`
17) `!(rhs < nullptr)`
18) `!(lhs < nullptr)`
19) `!(nullptr < rhs)`
20) `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way){}(x.get(), static\_cast<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>::element\_type\*>(nullptr))`
### Notes
In all cases, it is the stored pointer (the one returned by `[get()](get "cpp/memory/shared ptr/get")`) that is compared, rather than the managed pointer (the one passed to the deleter when `[use\_count](use_count "cpp/memory/shared ptr/use count")` goes to zero). The two pointers may differ in a `[shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` created using the aliasing constructor.
### Example
```
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> p1(new int(42));
std::shared_ptr<int> p2(new int(42));
std::cout << std::boolalpha
<< "(p1 == p1) : " << (p1 == p1) << '\n'
<< "(p1 <=> p1) == 0 : " << ((p1 <=> p1) == 0) << '\n' // Since C++20
// p1 and p2 point to different memory locations, so p1 != p2
<< "(p1 == p2) : " << (p1 == p2) << '\n'
<< "(p1 < p2) : " << (p1 < p2) << '\n'
<< "(p1 <=> p2) < 0 : " << ((p1 <=> p2) < 0) << '\n' // Since C++20
<< "(p1 <=> p2) == 0 : " << ((p1 <=> p2) == 0) << '\n'; // Since C++20
}
```
Possible output:
```
(p1 == p1) : true
(p1 <=> p1) == 0 : true
(p1 == p2) : false
(p1 < p2) : true
(p1 <=> p2) < 0 : true
(p1 <=> p2) == 0 : false
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3427](https://cplusplus.github.io/LWG/issue3427) | C++20 | `operator<=>(shared_ptr, nullptr_t)` was ill-formed | definition fixed |
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/shared ptr/get") | returns the stored pointer (public member function) |
cpp std::shared_ptr<T>::get std::shared\_ptr<T>::get
========================
| | | |
| --- | --- | --- |
|
```
T* get() const noexcept;
```
| | (until C++17) |
|
```
element_type* get() const noexcept;
```
| | (since C++17) |
Returns the stored pointer.
### Parameters
(none).
### Return value
The stored pointer.
### Notes
A `shared_ptr` may share ownership of an object while storing a pointer to another object. `get()` returns the stored pointer, not the managed pointer.
### Example
```
#include <iostream>
#include <memory>
#include <string_view>
int main()
{
auto output = [](std::string_view msg, int const* pInt) {
std::cout << msg << *pInt << " in " << pInt << "\n";
};
int* pInt = new int(42);
std::shared_ptr<int> pShared = std::make_shared<int>(42);
output("Naked pointer ", pInt);
// output("Shared pointer ", pShared); // compiler error
output("Shared pointer with get() ", pShared.get());
delete pInt;
std::cout << "\nThe shared_ptr's aliasing constructor demo.\n";
struct Base1 { int i1{}; };
struct Base2 { int i2{}; };
struct Derived : Base1, Base2 { int i3{}; };
std::shared_ptr<Derived> p(new Derived());
std::shared_ptr<Base2> q(p, static_cast<Base2*>(p.get()));
std::cout << "q shares ownership with p, but points to Base2 subobject:\n"
<< "p.get(): " << p.get() << '\n'
<< "q.get(): " << q.get() << '\n'
<< "&(p->i1): " << &(p->i1) << '\n'
<< "&(p->i2): " << &(p->i2) << '\n'
<< "&(p->i3): " << &(p->i3) << '\n'
<< "&(q->i2): " << &(q->i2) << '\n';
}
```
Possible output:
```
Naked pointer 42 in 0xacac20
Shared pointer with get() 42 in 0xacac50
The shared_ptr's aliasing constructor demo.
q shares ownership with p, but points to Base2 subobject:
p.get(): 0xacac20
q.get(): 0xacac24
&(p->i1): 0xacac20
&(p->i2): 0xacac24
&(p->i3): 0xacac28
&(q->i2): 0xacac24
```
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/memory/shared ptr/operator*") | dereferences the stored pointer (public member function) |
cpp std::shared_ptr<T>::unique std::shared\_ptr<T>::unique
===========================
| | | |
| --- | --- | --- |
|
```
bool unique() const noexcept;
```
| | (deprecated in C++17) (removed in C++20) |
Checks if `*this` is the only `shared_ptr` instance managing the current object, i.e. whether `use_count() == 1`.
### Parameters
(none).
### Return value
`true` if `*this` is the only `shared_ptr` instance managing the current object, `false` otherwise.
### Notes
This function was deprecated in C++17 and removed in C++20 because `[use\_count](use_count "cpp/memory/shared ptr/use count")` is only an approximation in multithreaded environment (see [Notes](use_count#Notes "cpp/memory/shared ptr/use count") in `[use\_count](use_count "cpp/memory/shared ptr/use count")`).
### Example
```
#include <memory>
#include <iostream>
int main()
{
auto sp1 = std::make_shared<int>(5);
std::cout << std::boolalpha;
std::cout << "sp1.unique() == " << sp1.unique() << '\n';
std::shared_ptr<int> sp2 = sp1;
std::cout << "sp1.unique() == " << sp1.unique() << '\n';
}
```
Output:
```
sp1.unique() == true
sp1.unique() == false
```
### See also
| | |
| --- | --- |
| [use\_count](use_count "cpp/memory/shared ptr/use count") | returns the number of `shared_ptr` objects referring to the same managed object (public member function) |
cpp std::shared_ptr<T>::owner_before std::shared\_ptr<T>::owner\_before
==================================
| | | |
| --- | --- | --- |
|
```
template< class Y >
bool owner_before( const shared_ptr<Y>& other ) const noexcept;
```
| | |
|
```
template< class Y >
bool owner_before( const std::weak_ptr<Y>& other ) const noexcept;
```
| | |
Checks whether this `shared_ptr` precedes `other` in implementation defined owner-based (as opposed to value-based) order. The order is such that two smart pointers compare equivalent only if they are both empty or if they both own the same object, even if the values of the pointers obtained by `[get()](get "cpp/memory/shared ptr/get")` are different (e.g. because they point at different subobjects within the same object).
This ordering is used to make shared and weak pointers usable as keys in associative containers, typically through `[std::owner\_less](../owner_less "cpp/memory/owner less")`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` or `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` to be compared |
### Return value
`true` if `*this` precedes `other`, `false` otherwise. Common implementations compare the addresses of the control blocks.
### Example
```
#include <iostream>
#include <memory>
struct Foo {
int n1;
int n2;
Foo(int a, int b) : n1(a), n2(b) {}
};
int main()
{
auto p1 = std::make_shared<Foo>(1, 2);
std::shared_ptr<int> p2(p1, &p1->n1);
std::shared_ptr<int> p3(p1, &p1->n2);
std::cout << std::boolalpha
<< "p2 < p3 " << (p2 < p3) << '\n'
<< "p3 < p2 " << (p3 < p2) << '\n'
<< "p2.owner_before(p3) " << p2.owner_before(p3) << '\n'
<< "p3.owner_before(p2) " << p3.owner_before(p2) << '\n';
std::weak_ptr<int> w2(p2);
std::weak_ptr<int> w3(p3);
std::cout
// << "w2 < w3 " << (w2 < w3) << '\n' // won't compile
// << "w3 < w2 " << (w3 < w2) << '\n' // won't compile
<< "w2.owner_before(w3) " << w2.owner_before(w3) << '\n'
<< "w3.owner_before(w2) " << w3.owner_before(w2) << '\n';
}
```
Output:
```
p2 < p3 true
p3 < p2 false
p2.owner_before(p3) false
p3.owner_before(p2) false
w2.owner_before(w3) false
w3.owner_before(w2) false
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2873](https://cplusplus.github.io/LWG/issue2873) | C++11 | `owner_before` might not be declared noexcept | declared noexcept |
### See also
| | |
| --- | --- |
| [owner\_less](../owner_less "cpp/memory/owner less")
(C++11) | provides mixed-type owner-based ordering of shared and weak pointers (class template) |
cpp std::inout_ptr std::inout\_ptr
===============
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Pointer = void, class Smart, class... Args >
auto inout_ptr( Smart& s, Args&&... args );
```
| | (since C++23) |
Returns an `inout_ptr_t` with deduced template arguments that captures arguments for resetting by reference.
The program is ill-formed if construction of the return value (see below) is ill-formed.
### Parameters
| | | |
| --- | --- | --- |
| s | - | the object (typically a smart pointer) to adapt |
| args... | - | the arguments for resetting to capture |
### Return value
`std::inout\_ptr\_t<Smart, P, Args&&>(s, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `P` is.
* `Pointer`, if `Pointer` is not same as `void`,
* otherwise, `Smart::pointer`, if it is valid and denotes a type,
* otherwise, `Smart::element_type*`, if `Smart::element_type` is valid and denotes a type,
* otherwise, `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type\*`.
### Notes
Users may specify the template argument for the template parameter `Pointer`, in order to interoperate with foreign functions that take a `Pointer*`.
As all arguments for resetting are captured by reference, the returned `inout_ptr_t` should be a temporary object destroyed at the end of the full-expression containing the call to the foreign function, in order to avoid dangling references.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_out_ptr`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [out\_ptr](../out_ptr_t/out_ptr "cpp/memory/out ptr t/out ptr")
(C++23) | creates an `out_ptr_t` with an associated smart pointer and resetting arguments (function template) |
| [make\_uniquemake\_unique\_for\_overwrite](../unique_ptr/make_unique "cpp/memory/unique ptr/make unique")
(C++14)(C++20) | creates a unique pointer that manages a new object (function template) |
| [make\_sharedmake\_shared\_for\_overwrite](../shared_ptr/make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
cpp std::inout_ptr_t<Smart,Pointer,Args...>::inout_ptr_t std::inout\_ptr\_t<Smart,Pointer,Args...>::inout\_ptr\_t
========================================================
| | | |
| --- | --- | --- |
|
```
explicit inoout_ptr_t( Smart &sp, Args... args );
```
| (1) | (since C++23) |
|
```
inout_ptr_t( const inout_ptr_t& ) = delete;
```
| (2) | (since C++23) |
1) Creates an `inout_ptr_t`. Adapts `sp` as if binds it to the `Smart&` member, captures every argument `t` in `args...` as if initializes the corresponding member of type `T` in `Args...` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`, then initializes the stored `Pointer` with `sp` if `Smart` is a pointer type, otherwise, initializes it with `sp.get()`. `sp.release()` may be called if `Smart` is not a pointer type, in which case it will not be called again within the destructor.
2) Copy constructor is explicitly deleted. `inout_ptr_t` is neither copyable nor movable. ### Parameters
| | | |
| --- | --- | --- |
| sp | - | the object (typically a smart pointer) to adapt |
| args... | - | the arguments used for resetting to capture |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Notes
If `Smart` is not a pointer type and `sp.release()` is not called by the constructor, it may be called by the destructor before resetting `sp`.
Every argument in `args...` is moved into the created `inout_ptr_t` if it is of an object type, or transferred into the created `inout_ptr_t` as-is if it is of a reference type.
The constructor of `inout_ptr_t` is allowed to throw exceptions. For example, when `sp` is an intrusive pointer with a control block, the allocation for the new control block may be performed within the constructor rather than the destructor.
### Example
| programming_docs |
cpp std::inout_ptr_t<Smart,Pointer,Args...>::~inout_ptr_t std::inout\_ptr\_t<Smart,Pointer,Args...>::~inout\_ptr\_t
=========================================================
| | | |
| --- | --- | --- |
|
```
~inout_ptr_t();
```
| | (since C++23) |
Resets the adapted `Smart` object by the value of modified `Pointer` object (or the `void*` object if `operator void**()` has been called) and the captured arguments. `release()` may be called on the adapted `Smart` object if it is not called by the constructor.
Let.
* `s` denotes the adapted `Smart` object,
* `args...` denotes the captured arguments,
* `p` denotes the value of stored `Pointer`, or `static_cast<Pointer>(*operator void**())` if `operator void**` has been called,
* `SP` be
+ `Smart::pointer`, if it is valid and denotes a type, otherwise,
+ `Smart::element_type*`, if `Smart::element_type` is valid and denotes a type, otherwise,
+ `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type\*`, if `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type` is valid and denotes a type, otherwise,
+ `Pointer`,
* `/*do-release*/` denotes `s.release()` if the [constructor](inout_ptr_t "cpp/memory/inout ptr t/inout ptr t") does not call `release()`, empty otherwise.
If `Smart` is a pointer type, the destructor performs `if (p) s = static_cast<Smart>(p);`, and the program is ill-formed if `sizeof...(Args) > 0`,
otherwise, if `s.reset(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)` is well-formed, the destructor performs `if (p) { /\*do-release\*/; s.reset(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...); }`,
otherwise, if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<Smart, SP, Args...>` is `true`, the destructor performs `if (p) { /\*do-release\*/; s = Smart(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...); }`,
otherwise, the program is ill-formed.
### Notes
The implementation may allocate the storage for the data structure needed for `Smart` (e.g. a control block) on construction, in order to leave non-throwing works to the destructor.
Arguments captured by value are destroyed after resetting.
cpp std::inout_ptr_t<Smart,Pointer,Args...>::operator Pointer*, std::inout_ptr_t<Smart,Pointer,Args...>::operator void** std::inout\_ptr\_t<Smart,Pointer,Args...>::operator Pointer\*, std::inout\_ptr\_t<Smart,Pointer,Args...>::operator void\*\*
===========================================================================================================================
| | | |
| --- | --- | --- |
|
```
operator Pointer*() const noexcept;
```
| (1) | (since C++23) |
|
```
operator void**() const noexcept;
```
| (2) | (since C++23) |
Exposes the address of a `Pointer` or `void*` object to a foreign function which will generally release the ownership represented by its value and then re-initialize it.
1) Converts `*this` to the address of stored `Pointer` object.
2) Converts `*this` to the address of a `void*` object. This conversion function participates in overload resolution only if `Pointer` is not same as `void*`, and the program is ill-formed if `Pointer` is not a pointer type.
The initial value of the `void*` object is equal the value of the stored `Pointer` object converted to `void*`, and any modification to it affects the `Pointer` value used in the [destructor](~inout_ptr_t "cpp/memory/inout ptr t/~inout ptr t"). Accessing the `void*` object outside the lifetime of `*this` has undefined behavior. Once one of these two conversion functions has been called on an `inout_ptr_t` object, the other shall not be called on it, otherwise, the behavior is undefined.
### Parameters
(none).
### Return value
1) The address of stored `Pointer` object.
2) The address of the `void*` object that satisfies aforementioned requirements. ### Notes
If the object pointed by the return value has not been rewritten, it is equal to the value held by adapted `Smart` object before construction.
On common implementations, the object representation of every `Pointer` that is a pointer type is compatible with that of `void*`, and therefore these implementations typically store the `void*` object within the storage for the `Pointer` object, no additional storage needed:
* If the implementation enables type-based alias analysis (which relies on the [strict aliasing rule](../../language/reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast")), a properly aligned `[std::byte](http://en.cppreference.com/w/cpp/types/byte)[sizeof(void\*)]` member subobject may be used, and both conversion functions return the address of objects [implicitly created](../../language/object#Object_creation "cpp/language/object") within the array.
* Otherwise, a `Pointer` member subobject may be used for both conversion functions, and (2) may directly returns its address [`reinterpret_cast`](../../language/reinterpret_cast "cpp/language/reinterpret cast") to `void**`.
If `Pointer` is a pointer type whose object representation is incompatible with that of `void*`, an additional `bool` flag may be needed for recording whether (1) (or (2)) has been called.
### Example
cpp std::auto_ptr<T>::reset std::auto\_ptr<T>::reset
========================
| | | |
| --- | --- | --- |
|
```
void reset( T* p = 0 ) throw();
```
| | (deprecated in C++11) (removed in C++17) |
Replaces the held pointer by `p`. If the currently held pointer is not null pointer, `delete get()` is called.
### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to an object to manage |
### Return value
(none).
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/auto ptr/release") | releases ownership of the managed object (public member function) |
cpp std::auto_ptr<T>::operator auto_ptr<Y> std::auto\_ptr<T>::operator auto\_ptr<Y>
========================================
| | | |
| --- | --- | --- |
|
```
template< class Y >
operator auto_ptr_ref<Y>() throw();
```
| (1) | (deprecated in C++11) (removed in C++17) |
|
```
template< class Y >
operator auto_ptr<Y>() throw();
```
| (2) | (deprecated in C++11) (removed in C++17) |
Converts `*this` to an `auto_ptr` for a different type `Y`.
1) Returns an implementation-defined type that holds a reference to `*this`. `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` is [convertible](auto_ptr "cpp/memory/auto ptr/auto ptr") and [assignable](operator= "cpp/memory/auto ptr/operator=") from this template. The implementation is allowed to provide the template with a different name or implement equivalent functionality in other ways.
2) Constructs a new `auto_ptr` with a pointer obtained by calling `[release()](release "cpp/memory/auto ptr/release")`. ### Parameters
(none).
### Return value
1) An implementation-defined type that holds a reference to `*this`
2) A `auto_ptr` with a pointer obtained by calling `[release()](release "cpp/memory/auto ptr/release")`. ### Notes
The constructor and the copy assignment operator from `auto_ptr_ref` is provided to allow copy-constructing and assigning `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` from nameless temporaries. Since its copy constructor and copy assignment operator take the argument as non-const reference, they cannot bind rvalue arguments directly. However, a **user-defined conversion** can be executed (which releases the original auto\_ptr), followed by a call to the constructor or copy-assignment operator that take `auto_ptr_ref` by value. This is an early implementation of [move semantics](../../utility/move "cpp/utility/move").
cpp std::auto_ptr<T>::auto_ptr std::auto\_ptr<T>::auto\_ptr
============================
| | | |
| --- | --- | --- |
|
```
explicit auto_ptr( X* p = 0 ) throw();
```
| (1) | (deprecated in C++11) (removed in C++17) |
|
```
auto_ptr( auto_ptr& r ) throw();
```
| (2) | (deprecated in C++11) (removed in C++17) |
|
```
template< class Y >
auto_ptr( auto_ptr<Y>& r ) throw();
```
| (3) | (deprecated in C++11) (removed in C++17) |
|
```
auto_ptr( auto_ptr_ref<X> m ) throw();
```
| (4) | (deprecated in C++11) (removed in C++17) |
Constructs the `auto_ptr` from a pointer that refers to the object to manage.
1) Constructs the `auto_ptr` with pointer `p`.
2) Constructs the `auto_ptr` with the pointer held in `r`. `r.release()` is called to acquire the ownership of the object.
3) Same as (2). `Y*` must be implicitly convertible to `T*`.
4) Constructs the `auto_ptr` with the pointer held in the `auto_ptr` instance referred to by `m`. `p.release()` is called for the `auto_ptr p` that `m` holds to acquire the ownership of the object.
`auto_ptr_ref` is an implementation-defined type that holds a reference to `auto_ptr`. `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` is implicitly [convertible to](operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr") and [assignable from](operator= "cpp/memory/auto ptr/operator=") this type. The implementation is allowed to provide the template with a different name or implement equivalent functionality in other ways. ### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to an object to manage |
| r | - | another `auto_ptr` to transfer the ownership of the object from |
| m | - | an implementation-defined type that holds a reference to `auto_ptr` |
### Notes
The constructor and the copy assignment operator from `auto_ptr_ref` is provided to allow copy-constructing and assigning `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` from nameless temporaries. Since its copy constructor and copy assignment operator take the argument as non-const reference, they cannot bind rvalue arguments directly. However, a [user-defined conversion](operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr") can be executed (which releases the original auto\_ptr), followed by a call to the constructor or copy-assignment operator that take `auto_ptr_ref` by value. This is an early implementation of [move semantics](../../utility/move "cpp/utility/move").
cpp std::auto_ptr<T>::operator*, std::auto_ptr<T>::operator-> std::auto\_ptr<T>::operator\*, std::auto\_ptr<T>::operator->
============================================================
| | | |
| --- | --- | --- |
|
```
T& operator*() const throw();
```
| (1) | (deprecated in C++11) (removed in C++17) |
|
```
T* operator->() const throw();
```
| (2) | (deprecated in C++11) (removed in C++17) |
Dereferences a pointer to the managed object. The first version requires `get() != 0`.
### Parameters
(none).
### Return value
1) `*get()`.
2) `get()`. ### See also
| | |
| --- | --- |
| [get](get "cpp/memory/auto ptr/get") | returns a pointer to the managed object (public member function) |
cpp std::auto_ptr<T>::release std::auto\_ptr<T>::release
==========================
| | | |
| --- | --- | --- |
|
```
T* release() throw();
```
| | (deprecated in C++11) (removed in C++17) |
Releases the held pointer. After the call `*this` holds the null pointer.
### Parameters
(none).
### Return value
`get()`.
### See also
| | |
| --- | --- |
| [reset](reset "cpp/memory/auto ptr/reset") | replaces the managed object (public member function) |
cpp std::auto_ptr<T>::operator= std::auto\_ptr<T>::operator=
============================
| | | |
| --- | --- | --- |
|
```
auto_ptr& operator=( auto_ptr& r ) throw();
```
| (1) | (deprecated in C++11) (removed in C++17) |
|
```
template< class Y >
auto_ptr& operator=( auto_ptr<Y>& r ) throw();
```
| (2) | (deprecated in C++11) (removed in C++17) |
|
```
auto_ptr& operator=( auto_ptr_ref m ) throw();
```
| (3) | (deprecated in C++11) (removed in C++17) |
Replaces the managed object with the one managed by `r`.
1) Effectively calls `reset(r.release())`.
2) Effectively calls `reset(r.release())`. `Y*` must be implicitly convertible to `T*`.
3) Effectively calls `reset(m.release())`. `auto_ptr_ref` is an implementation-defined type that holds a reference to `auto_ptr`. `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` is implicitly [convertible to](operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr") and [from](auto_ptr "cpp/memory/auto ptr/auto ptr") this type. The implementation is allowed to provide the template with a different name or implement equivalent functionality in other ways. ### Parameters
| | | |
| --- | --- | --- |
| r | - | another `auto_ptr` to transfer the ownership of the object from |
| m | - | an implementation-defined type that holds a reference to `auto_ptr` |
### Return value
`*this`.
### Notes
The constructor and the copy assignment operator from `auto_ptr_ref` is provided to allow copy-constructing and assigning `[std::auto\_ptr](../auto_ptr "cpp/memory/auto ptr")` from nameless temporaries. Since its copy constructor and copy assignment operator take the argument as non-const reference, they cannot bind rvalue arguments directly. However, a [user-defined conversion](operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr") can be executed (which releases the original auto\_ptr), followed by a call to the constructor or copy-assignment operator that take `auto_ptr_ref` by value. This is an early implementation of [move semantics](../../utility/move "cpp/utility/move").
cpp std::auto_ptr<T>::~auto_ptr std::auto\_ptr<T>::~auto\_ptr
=============================
| | | |
| --- | --- | --- |
|
```
~auto_ptr() throw();
```
| | (deprecated in C++11) (removed in C++17) |
Destroys the managed object. Calls `delete get()`.
cpp std::auto_ptr<T>::get std::auto\_ptr<T>::get
======================
| | | |
| --- | --- | --- |
|
```
T* get() const throw();
```
| | (deprecated in C++11) (removed in C++17) |
Returns the pointer that is held by `*this`.
### Parameters
(none).
### Return value
The pointer held by `*this`.
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/memory/auto ptr/operator*") | accesses the managed object (public member function) |
cpp std::pmr::synchronized_pool_resource::synchronized_pool_resource std::pmr::synchronized\_pool\_resource::synchronized\_pool\_resource
====================================================================
| | | |
| --- | --- | --- |
|
```
synchronized_pool_resource();
```
| (1) | (since C++17) |
|
```
explicit synchronized_pool_resource( std::pmr::memory_resource* upstream );
```
| (2) | (since C++17) |
|
```
explicit synchronized_pool_resource( const std::pmr::pool_options& opts );
```
| (3) | (since C++17) |
|
```
synchronized_pool_resource( const std::pmr::pool_options& opts,
std::pmr::memory_resource* upstream );
```
| (4) | (since C++17) |
|
```
synchronized_pool_resource( const synchronized_pool_resource& ) = delete;
```
| (5) | (since C++17) |
Constructs a `synchronized_pool_resource`.
1-4) Constructs a `synchronized_pool_resource` using the specified upstream memory resource and tuned according to the specified options. The resulting object holds a copy of `upstream` but does not own the resource to which `upstream` points.
The overloads not taking `opts` as a parameter uses a default constructed instance of [`pool_options`](../pool_options "cpp/memory/pool options") as the options. The overloads not taking `upstream` as a parameter uses the return value of `[std::pmr::get\_default\_resource](../get_default_resource "cpp/memory/get default resource")` as the upstream memory resource.
5) Copy constructor is deleted. ### Parameters
| | | |
| --- | --- | --- |
| opts | - | a `[std::pmr::pool\_options](../pool_options "cpp/memory/pool options")` struct containing the constructor options |
| upstream | - | the upstream memory resource to use |
### Exceptions
1-4) Throws only if a call to the `allocate()` function of the upstream resource throws. It is unspecified if or under what conditions such a call takes place.
cpp std::pmr::synchronized_pool_resource::do_deallocate std::pmr::synchronized\_pool\_resource::do\_deallocate
======================================================
| | | |
| --- | --- | --- |
|
```
virtual void do_deallocate( void* p, std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
Returns the memory at `p` to the pool. It is unspecified if or under what circumstances this operation will result in a call to `deallocate()` on the upstream memory resource.
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_deallocate](../memory_resource/do_deallocate "cpp/memory/memory resource/do deallocate")
[virtual] | deallocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::synchronized_pool_resource::release std::pmr::synchronized\_pool\_resource::release
===============================================
| | | |
| --- | --- | --- |
|
```
void release();
```
| | (since C++17) |
Releases all memory owned by this resource by calling the `deallocate` function of the upstream memory resource as needed.
Memory is released back to the upstream resource even if `deallocate` has not been called for some of the allocated blocks.
### See also
| | |
| --- | --- |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::synchronized_pool_resource::do_allocate std::pmr::synchronized\_pool\_resource::do\_allocate
====================================================
| | | |
| --- | --- | --- |
|
```
virtual void* do_allocate( std::size_t bytes, std::size_t alignment );
```
| | (since C++17) |
Allocates storage.
If the pool selected for a block of size `bytes` is unable to satisfy the request from its internal data structures, calls `allocate()` on the upstream memory resource to obtain memory.
If the size requested is larger than what the largest pool can handle, memory is allocated by calling `allocate()` on the upstream memory resource.
### Return value
A pointer to allocated storage of at least `bytes` bytes in size, aligned to the specified `alignment` if such alignment is supported, and to `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))` otherwise.
### Exceptions
Throws nothing unless calling `allocate()` on the upstream memory resource throws.
### See also
| | |
| --- | --- |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
| [do\_allocate](../memory_resource/do_allocate "cpp/memory/memory resource/do allocate")
[virtual] | allocates memory (virtual private member function of `std::pmr::memory_resource`) |
cpp std::pmr::synchronized_pool_resource::do_is_equal std::pmr::synchronized\_pool\_resource::do\_is\_equal
=====================================================
| | | |
| --- | --- | --- |
|
```
virtual bool do_is_equal( const std::pmr::memory_resource& other ) const noexcept;
```
| | (since C++17) |
Compare `*this` with `other` for identity - memory allocated using a `synchronized_pool_resource` can only be deallocated using that same resource.
### Return value
`this == &other`.
### Defect report
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3000](https://cplusplus.github.io/LWG/issue3000) | C++17 | unnecessary `dynamic_cast` was performed | removed |
### See also
| | |
| --- | --- |
| [do\_is\_equal](../memory_resource/do_is_equal "cpp/memory/memory resource/do is equal")
[virtual] | compare for equality with another `memory_resource` (virtual private member function of `std::pmr::memory_resource`) |
| programming_docs |
cpp std::pmr::synchronized_pool_resource::options std::pmr::synchronized\_pool\_resource::options
===============================================
| | | |
| --- | --- | --- |
|
```
std::pmr::pool_options options() const;
```
| | (since C++17) |
Returns the options that controls the pooling behavior of this resource.
The values in the returned struct may differ from those supplied to the constructor in the following ways:
* Values of zero will be replaced with implementation-specified defaults;
* Sizes may be rounded to an unspecified granularity.
### See also
| | |
| --- | --- |
| [(constructor)](synchronized_pool_resource "cpp/memory/synchronized pool resource/synchronized pool resource") | Constructs a `synchronized_pool_resource` (public member function) |
cpp std::pmr::synchronized_pool_resource::upstream_resource std::pmr::synchronized\_pool\_resource::upstream\_resource
==========================================================
| | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* upstream_resource() const;
```
| | (since C++17) |
Returns a pointer to the upstream memory resource. This is the same value as the `upstream` argument passed to the constructor of this object.
### See also
| | |
| --- | --- |
| [(constructor)](synchronized_pool_resource "cpp/memory/synchronized pool resource/synchronized pool resource") | Constructs a `synchronized_pool_resource` (public member function) |
cpp std::pmr::synchronized_pool_resource::~synchronized_pool_resource std::pmr::synchronized\_pool\_resource::~synchronized\_pool\_resource
=====================================================================
| | | |
| --- | --- | --- |
|
```
virtual ~synchronized_pool_resource();
```
| | (since C++17) |
Destroys a `synchronized_pool_resource`.
Deallocates all memory owned by this resource by calling `this->release()`.
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/synchronized pool resource/release") | Release all allocated memory (public member function) |
cpp std::out_ptr std::out\_ptr
=============
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class Pointer = void, class Smart, class... Args >
auto out_ptr( Smart& s, Args&&... args );
```
| | (since C++23) |
Returns an `out_ptr_t` with deduced template arguments that captures arguments for resetting by reference.
The program is ill-formed if construction of the return value (see below) is ill-formed.
### Parameters
| | | |
| --- | --- | --- |
| s | - | the object (typically a smart pointer) to adapt |
| args... | - | the arguments for resetting to capture |
### Return value
`std::out\_ptr\_t<Smart, P, Args&&>(s, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, where `P` is.
* `Pointer`, if `Pointer` is not same as `void`,
* otherwise, `Smart::pointer`, if it is valid and denotes a type,
* otherwise, `Smart::element_type*`, if `Smart::element_type` is valid and denotes a type,
* otherwise, `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type\*`.
### Notes
Users may specify the template argument for the template parameter `Pointer`, in order to interoperate with foreign functions that take a `Pointer*`.
As all arguments for resetting are captured by reference, the returned `out_ptr_t` should be a temporary object destroyed at the end of the full-expression containing the call to the foreign function, in order to avoid dangling references.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_out_ptr`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### Example
### See also
| | |
| --- | --- |
| [inout\_ptr](../inout_ptr_t/inout_ptr "cpp/memory/inout ptr t/inout ptr")
(C++23) | creates an `inout_ptr_t` with an associated smart pointer and resetting arguments (function template) |
| [make\_uniquemake\_unique\_for\_overwrite](../unique_ptr/make_unique "cpp/memory/unique ptr/make unique")
(C++14)(C++20) | creates a unique pointer that manages a new object (function template) |
| [make\_sharedmake\_shared\_for\_overwrite](../shared_ptr/make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
cpp std::out_ptr_t<Smart,Pointer,Args...>::~out_ptr_t std::out\_ptr\_t<Smart,Pointer,Args...>::~out\_ptr\_t
=====================================================
| | | |
| --- | --- | --- |
|
```
~out_ptr_t();
```
| | (since C++23) |
Resets the adapted `Smart` object by the value of modified `Pointer` object (or the `void*` object if `operator void**()` has been called) and the captured arguments.
Let.
* `s` denotes the adapted `Smart` object,
* `args...` denotes the captured arguments,
* `p` denotes the value of stored `Pointer`, or `static_cast<Pointer>(*operator void**())` if `operator void**` has been called,
* `SP` be
+ `Smart::pointer`, if it is valid and denotes a type, otherwise,
+ `Smart::element_type*`, if `Smart::element_type` is valid and denotes a type, otherwise,
+ `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type\*`, if `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<Smart>::element\_type` is valid and denotes a type, otherwise,
+ `Pointer`.
If `s.reset(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)` is well-formed, the destructor performs `if (p) s.reset(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);`,
otherwise, if `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<Smart, SP, Args...>` is `true`, the destructor performs `if (p) s = Smart(static\_cast<SP>(p), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...);`,
otherwise, the program is ill-formed.
### Notes
If `Smart` is a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` specialization, the implementation may allocate the storage for the new control block on construction, in order to leave non-throwing works to the destructor.
Arguments captured by value are destroyed after resetting.
cpp std::out_ptr_t<Smart,Pointer,Args...>::out_ptr_t std::out\_ptr\_t<Smart,Pointer,Args...>::out\_ptr\_t
====================================================
| | | |
| --- | --- | --- |
|
```
explicit out_ptr_t( Smart &sp, Args... args );
```
| (1) | (since C++23) |
|
```
out_ptr_t( const out_ptr_t& ) = delete;
```
| (2) | (since C++23) |
1) Creates an `out_ptr_t`. Adapts `sp` as if binds it to the `Smart&` member, captures every argument `t` in `args...` as if initializes the corresponding member of type `T` in `Args...` with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`, then value-initializes the stored `Pointer`.
2) Copy constructor is explicitly deleted. `out_ptr_t` is neither copyable nor movable. ### Parameters
| | | |
| --- | --- | --- |
| sp | - | the object (typically a smart pointer) to adapt |
| args... | - | the arguments used for resetting to capture |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Notes
After construction, the `Pointer` or `void*` object pointed by the return value of either conversion function is equal to `nullptr`.
Every argument in `args...` is moved into the created `out_ptr_t` if it is of an object type, or transferred into the created `out_ptr_t` as-is if it is of a reference type.
The constructor of `out_ptr_t` is allowed to throw exceptions. For example, when `sp` is a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")`, the allocation for the new control block may be performed within the constructor rather than the destructor.
### Example
cpp std::out_ptr_t<Smart,Pointer,Args...>::operator Pointer*, std::out_ptr_t<Smart,Pointer,Args...>::operator void** std::out\_ptr\_t<Smart,Pointer,Args...>::operator Pointer\*, std::out\_ptr\_t<Smart,Pointer,Args...>::operator void\*\*
=======================================================================================================================
| | | |
| --- | --- | --- |
|
```
operator Pointer*() const noexcept;
```
| (1) | (since C++23) |
|
```
operator void**() const noexcept;
```
| (2) | (since C++23) |
Exposes the address of a `Pointer` or `void*` object to a foreign function which will generally re-initialize it.
1) Converts `*this` to the address of stored `Pointer` object.
2) Converts `*this` to the address of a `void*` object. This conversion function participates in overload resolution only if `Pointer` is not same as `void*`, and the program is ill-formed if `Pointer` is not a pointer type.
The initial value of the `void*` object is equal the value of the stored `Pointer` object converted to `void*`, and any modification to it affects the `Pointer` value used in the [destructor](~out_ptr_t "cpp/memory/out ptr t/~out ptr t"). Accessing the `void*` object outside the lifetime of `*this` has undefined behavior. Once one of these two conversion functions has been called on an `out_ptr_t` object, the other shall not be called on it, otherwise, the behavior is undefined.
### Parameters
(none).
### Return value
1) The address of stored `Pointer` object.
2) The address of the `void*` object that satisfies aforementioned requirements. ### Notes
If the object pointed by the return value has not been rewritten, it is equal to `nullptr`.
On common implementations, the object representation of every `Pointer` that is a pointer type is compatible with that of `void*`, and therefore these implementations typically store the `void*` object within the storage for the `Pointer` object, no additional storage needed:
* If the implementation enables type-based alias analysis (which relies on the [strict aliasing rule](../../language/reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast")), a properly aligned `[std::byte](http://en.cppreference.com/w/cpp/types/byte)[sizeof(void\*)]` member subobject may be used, and both conversion functions return the address of objects [implicitly created](../../language/object#Object_creation "cpp/language/object") within the array.
* Otherwise, a `Pointer` member subobject may be used for both conversion functions, and (2) may directly returns its address [`reinterpret_cast`](../../language/reinterpret_cast "cpp/language/reinterpret cast") to `void**`.
If `Pointer` is a pointer type whose object representation is incompatible with that of `void*`, an additional `bool` flag may be needed for recording whether (1) (or (2)) has been called.
### Example
cpp std::unique_ptr<T,Deleter>::reset std::unique\_ptr<T,Deleter>::reset
==================================
| | | |
| --- | --- | --- |
| members of the primary template, unique\_ptr<T> | | |
|
```
void reset( pointer ptr = pointer() ) noexcept;
```
| (1) | (constexpr since C++23) |
| members of the specialization unique\_ptr<T[]> | | |
|
```
template< class U >
void reset( U ptr ) noexcept;
```
| (2) | (constexpr since C++23) |
|
```
void reset( std::nullptr_t = nullptr ) noexcept;
```
| (3) | (constexpr since C++23) |
Replaces the managed object.
1) Given `current_ptr`, the pointer that was managed by `*this`, performs the following actions, in this order: 1. Saves a copy of the current pointer `old_ptr = current_ptr`
2. Overwrites the current pointer with the argument `current_ptr = ptr`
3. If the old pointer was non-empty, deletes the previously managed object `if(old_ptr) get_deleter()(old_ptr)`.
2) Behaves the same as the reset member of the primary template, except that it will only participate in overload resolution if either 1. `U` is the same type as `pointer`, or
2. `pointer` is the same type as `element_type*` and `U` is a pointer type `V*` such that `V(*)[]` is convertible to `element_type(*)[]`.
3) Equivalent to `reset(pointer())`
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to a new object to manage |
### Return value
(none).
### Notes
To replace the managed object while supplying a new deleter as well, move assignment operator may be used.
A test for self-reset, i.e. whether `ptr` points to an object already managed by `*this`, is not performed, except where provided as a compiler extension or as a debugging assert. Note that code such as `p.reset(p.release())` does not involve self-reset, only code like `p.reset(p.get())` does.
### Example
```
#include <iostream>
#include <memory>
struct Foo { // object to manage
Foo() { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
};
struct D { // deleter
void operator() (Foo* p) {
std::cout << "Calling delete for Foo object... \n";
delete p;
}
};
int main()
{
std::cout << "Creating new Foo...\n";
std::unique_ptr<Foo, D> up(new Foo(), D()); // up owns the Foo pointer (deleter D)
std::cout << "Replace owned Foo with a new Foo...\n";
up.reset(new Foo()); // calls deleter for the old one
std::cout << "Release and delete the owned Foo...\n";
up.reset(nullptr);
}
```
Output:
```
Creating new Foo...
Foo...
Replace owned Foo with a new Foo...
Foo...
Calling delete for Foo object...
~Foo...
Release and delete the owned Foo...
Calling delete for Foo object...
~Foo...
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2118](https://cplusplus.github.io/LWG/issue2118) | C++11 | `unique_ptr<T[]>::reset` rejected qualification conversions | accepts |
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/unique ptr/release") | returns a pointer to the managed object and releases the ownership (public member function) |
cpp std::unique_ptr<T,Deleter>::~unique_ptr std::unique\_ptr<T,Deleter>::~unique\_ptr
=========================================
| | | |
| --- | --- | --- |
|
```
~unique_ptr();
```
| | (since C++11) (constexpr since C++23) |
If `[get()](get "cpp/memory/unique ptr/get")` `==` `nullptr` there are no effects. Otherwise, the owned object is destroyed via `[get\_deleter()](get_deleter "cpp/memory/unique ptr/get deleter")``(``[get()](get "cpp/memory/unique ptr/get")``)`.
Requires that `get_deleter()(get())` does not throw exceptions.
### Notes
Although `std::unique_ptr<T>` with the default deleter may be constructed with [incomplete type](../../language/incomplete_type "cpp/language/incomplete type") `T`, the type `T` must be complete at the point of code where the destructor is called.
### Example
The following program demonstrates usage of a custom deleter.
```
#include <iostream>
#include <memory>
int main ()
{
auto deleter = [](int* ptr){
std::cout << "[deleter called]\n";
delete ptr;
};
std::unique_ptr<int,decltype(deleter)> uniq(new int, deleter);
std::cout << (uniq ? "not empty\n" : "empty\n");
uniq.reset();
std::cout << (uniq ? "not empty\n" : "empty\n");
}
```
Output:
```
not empty
[deleter called]
empty
```
cpp std::unique_ptr<T,Deleter>::operator<< std::unique\_ptr<T,Deleter>::operator<<
=======================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits, class Y, class D >
std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os,
const std::unique_ptr<Y, D>& p );
```
| | (since C++20) |
Inserts the value of the pointer managed by `p` into the output stream `os`.
Equivalent to `os << p.get()`.
This overload participates in overload resolution only if `os << p.get()` is a valid expression.
### Parameters
| | | |
| --- | --- | --- |
| os | - | a `[std::basic\_ostream](../../io/basic_ostream "cpp/io/basic ostream")` to insert `p` into |
| p | - | the pointer to be inserted into `os` |
### Return value
`os`.
### Notes
If `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<Y, D>::pointer` is a pointer to a character type (e.g., when `Y` is `char` or `char[]` or `CharT`), this may end up calling the [overloads of `operator<<` for null-terminated character strings](../../io/basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") (causing undefined behavior if the pointer does not in fact point to such a string), rather than [the overload for printing the value of the pointer itself](../../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt").
### Example
```
#include <iostream>
#include <memory>
class Foo {};
int main()
{
auto p = std::make_unique<Foo>();
std::cout << p << '\n';
std::cout << p.get() << '\n';
}
```
Possible output:
```
0x6d9028
0x6d9028
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
cpp std::unique_ptr<T,Deleter>::get_deleter std::unique\_ptr<T,Deleter>::get\_deleter
=========================================
| | | |
| --- | --- | --- |
|
```
Deleter& get_deleter() noexcept;
```
| | (since C++11) (constexpr since C++23) |
|
```
const Deleter& get_deleter() const noexcept;
```
| | (since C++11) (constexpr since C++23) |
Returns the deleter object which would be used for destruction of the managed object.
### Parameters
(none).
### Return value
The stored deleter object.
### Example
```
#include <iostream>
#include <memory>
struct Foo
{
Foo() { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
};
struct D
{
void bar() { std::cout << "Call deleter D::bar()...\n"; }
void operator()(Foo* p) const
{
std::cout << "Call delete for Foo object...\n";
delete p;
}
};
int main()
{
std::unique_ptr<Foo, D> up(new Foo(), D());
D& del = up.get_deleter();
del.bar();
}
```
Output:
```
Foo...
Call deleter D::bar()...
Call delete for Foo object...
~Foo...
```
### See also
| | |
| --- | --- |
| [get\_deleter](../shared_ptr/get_deleter "cpp/memory/shared ptr/get deleter") | returns the deleter of specified type, if owned (function template) |
cpp std::unique_ptr<T,Deleter>::operator[] std::unique\_ptr<T,Deleter>::operator[]
=======================================
| | | |
| --- | --- | --- |
|
```
T& operator[]( std::size_t i ) const;
```
| | (since C++11) (constexpr since C++23) |
`operator[]` provides access to elements of an array managed by a `unique_ptr`.
The parameter `i` shall be less than the number of elements in the array; otherwise, the behavior is undefined.
This member function is only provided for specializations for array types.
### Parameters
| | | |
| --- | --- | --- |
| i | - | the index of the element to be returned |
### Return value
Returns the element at index `i`, i.e. [`get()[i]`](get "cpp/memory/unique ptr/get").
### Example
```
#include <iostream>
#include <memory>
int main()
{
const int size = 10;
std::unique_ptr<int[]> fact(new int[size]);
for (int i = 0; i < size; ++i) {
fact[i] = (i == 0) ? 1 : i * fact[i-1];
}
for (int i = 0; i < size; ++i) {
std::cout << i << "! = " << fact[i] << '\n';
}
}
```
Output:
```
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
| programming_docs |
cpp std::unique_ptr<T,Deleter>::swap std::unique\_ptr<T,Deleter>::swap
=================================
| | | |
| --- | --- | --- |
|
```
void swap( unique_ptr& other ) noexcept;
```
| | (since C++11) |
Swaps the managed objects and associated deleters of `*this` and another `unique_ptr` object `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another `unique_ptr` object to swap the managed object and the deleter with |
### Return value
(none).
### Example
```
#include <iostream>
#include <memory>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
int val;
};
int main()
{
std::unique_ptr<Foo> up1(new Foo(1));
std::unique_ptr<Foo> up2(new Foo(2));
up1.swap(up2);
std::cout << "up1->val:" << up1->val << '\n';
std::cout << "up2->val:" << up2->val << '\n';
}
```
Output:
```
Foo...
Foo...
up1->val:2
up2->val:1
~Foo...
~Foo...
```
cpp std::unique_ptr<T,Deleter>::operator bool std::unique\_ptr<T,Deleter>::operator bool
==========================================
| | | |
| --- | --- | --- |
|
```
explicit operator bool() const noexcept;
```
| | (since C++11) (constexpr since C++23) |
Checks whether `*this` owns an object, i.e. whether `[get()](get "cpp/memory/unique ptr/get")` `!=` `nullptr`.
### Parameters
(none).
### Return value
`true` if `*this` owns an object, `false` otherwise.
### Example
```
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> ptr(new int(42));
if (ptr) std::cout << "before reset, ptr is: " << *ptr << '\n';
ptr.reset();
ptr ? (std::cout << "after reset, ptr is: " << *ptr)
: (std::cout << "after reset ptr is empty") << '\n';
}
```
Output:
```
before reset, ptr is: 42
after reset ptr is empty
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
cpp std::unique_ptr<T,Deleter>::operator*, std::unique_ptr<T,Deleter>::operator-> std::unique\_ptr<T,Deleter>::operator\*, std::unique\_ptr<T,Deleter>::operator->
================================================================================
| | | |
| --- | --- | --- |
|
```
typename std::add_lvalue_reference<T>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()));
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
pointer operator->() const noexcept;
```
| (2) | (since C++11) (constexpr since C++23) |
`operator*` and `operator->` provide access to the object owned by `*this`.
The behavior is undefined if `get() == nullptr`.
These member functions are only provided for `unique_ptr` for the single objects i.e. the primary template.
### Parameters
(none).
### Return value
1) Returns the object owned by `*this`, equivalent to `*get()`.
2) Returns a pointer to the object owned by `*this`, i.e. `get()`. ### Exceptions
1) May throw if `pointer` has a throwing `operator*`. ### Example
```
#include <iostream>
#include <memory>
struct Foo {
void bar() { std::cout << "Foo::bar\n"; }
};
void f(const Foo&)
{
std::cout << "f(const Foo&)\n";
}
int main()
{
std::unique_ptr<Foo> ptr(new Foo);
ptr->bar();
f(*ptr);
}
```
Output:
```
Foo::bar
f(const Foo&)
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2762](https://cplusplus.github.io/LWG/issue2762) | C++11 | `operator*` might be potentially-throwing even if`*get()` was noexcept | a conditional exception specification added |
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
cpp std::unique_ptr<T,Deleter>::release std::unique\_ptr<T,Deleter>::release
====================================
| | | |
| --- | --- | --- |
|
```
pointer release() noexcept;
```
| | (since C++11) (constexpr since C++23) |
Releases the ownership of the managed object, if any.
`[get()](get "cpp/memory/unique ptr/get")` returns `nullptr` after the call.
The caller is responsible for deleting the object.
### Parameters
(none).
### Return value
Pointer to the managed object or `nullptr` if there was no managed object, i.e. the value which would be returned by `[get()](get "cpp/memory/unique ptr/get")` before the call.
### Example
```
#include <memory>
#include <iostream>
#include <cassert>
struct Foo {
Foo() { std::cout << "Foo\n"; }
~Foo() { std::cout << "~Foo\n"; }
};
int main()
{
std::cout << "Creating new Foo...\n";
std::unique_ptr<Foo> up(new Foo());
std::cout << "About to release Foo...\n";
Foo* fp = up.release();
assert (up.get() == nullptr);
assert (up == nullptr);
std::cout << "Foo is no longer owned by unique_ptr...\n";
delete fp;
}
```
Output:
```
Creating new Foo...
Foo
About to release Foo...
Foo is no longer owned by unique_ptr...
~Foo
```
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
| [reset](reset "cpp/memory/unique ptr/reset") | replaces the managed object (public member function) |
cpp std::swap(std::unique_ptr)
std::swap(std::unique\_ptr)
===========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class D >
void swap( std::unique_ptr<T, D>& lhs, std::unique_ptr<T, D>& rhs ) noexcept;
```
| | (since C++11) (constexpr since C++23) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`.
| | |
| --- | --- |
| This function does not participate in overload resolution unless `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<D>` is `true`. | (since C++17) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | smart pointers whose contents to swap |
### Return value
(none).
### Complexity
Constant.
### Example
```
#include <iostream>
#include <memory>
#include <string>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::unique_ptr<Foo> p1 = std::make_unique<Foo>(100);
std::unique_ptr<Foo> p2 = std::make_unique<Foo>(200);
auto print = [&]() {
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
std::swap(p1, p2);
print();
p1.reset();
print();
std::swap(p1, p2);
print();
}
```
Output:
```
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
~Foo...
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap](swap "cpp/memory/unique ptr/swap") | swaps the contents (public member function) |
cpp std::unique_ptr<T,Deleter>::operator= std::unique\_ptr<T,Deleter>::operator=
======================================
| | | |
| --- | --- | --- |
| members of the primary template, unique\_ptr<T> | | |
|
```
unique_ptr& operator=( unique_ptr&& r ) noexcept;
```
| (1) | (constexpr since C++23) |
|
```
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ) noexcept;
```
| (2) | (constexpr since C++23) |
|
```
unique_ptr& operator=( std::nullptr_t ) noexcept;
```
| (3) | (constexpr since C++23) |
| members of the specialization for arrays, unique\_ptr<T[]> | | |
|
```
unique_ptr& operator=( unique_ptr&& r ) noexcept;
```
| (1) | (constexpr since C++23) |
|
```
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ) noexcept;
```
| (2) | (constexpr since C++23) |
|
```
unique_ptr& operator=( std::nullptr_t ) noexcept;
```
| (3) | (constexpr since C++23) |
1) Move assignment operator. Transfers ownership from `r` to `*this` as if by calling `reset(r.release())` followed by an assignment of `[get\_deleter()](get_deleter "cpp/memory/unique ptr/get deleter")` from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Deleter>(r.get\_deleter())`. If `Deleter` is not a reference type, requires that it is nothrow-[MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable").
If `Deleter` is a reference type, requires that `[std::remove\_reference](http://en.cppreference.com/w/cpp/types/remove_reference)<Deleter>::type` is nothrow-[CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable").
The move assignment operator only participates in overload resolution if `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Deleter>::value` is `true`.
2) Converting assignment operator. Behaves same as (1), except that * This assignment operator of the primary template only participates in overload resolution if `U` is not an array type and `unique_ptr<U,E>::pointer` is implicitly convertible to `pointer` and `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<Deleter&, E&&>::value` is `true`.
* This assignment operator in the specialization for arrays, `std::unique_ptr<T[]>` behaves the same as in the primary template, except that will only participate in overload resolution if all of the following is true:
+ `U` is an array type
+ `pointer` is the same type as `element_type*`
+ `unique_ptr<U,E>::pointer` is the same type as `unique_ptr<U,E>::element_type*`
+ `unique_ptr<U,E>::element_type(*)[]` is convertible to `element_type(*)[]`
+ `[std::is\_assignable](http://en.cppreference.com/w/cpp/types/is_assignable)<Deleter&, E&&>::value` is `true`
3) Effectively the same as calling `reset()`. Note that `unique_ptr`'s assignment operator only accepts [rvalues](../../language/value_category "cpp/language/value category"), which are typically generated by `std::move`. (The `unique_ptr` class explicitly deletes its [lvalue](../../language/value_category "cpp/language/value category") copy constructor and [lvalue](../../language/value_category "cpp/language/value category") assignment operator.).
### Parameters
| | | |
| --- | --- | --- |
| r | - | smart pointer from which ownership will be transferred |
### Return value
`*this`.
### Example
```
#include <iostream>
#include <memory>
struct Foo {
int id;
Foo(int id) : id(id) { std::cout << "Foo " << id << '\n'; }
~Foo() { std::cout << "~Foo " << id << '\n'; }
};
int main()
{
std::unique_ptr<Foo> p1( std::make_unique<Foo>(1) );
{
std::cout << "Creating new Foo...\n";
std::unique_ptr<Foo> p2( std::make_unique<Foo>(2) );
// p1 = p2; // Error ! can't copy unique_ptr
p1 = std::move(p2);
std::cout << "About to leave inner block...\n";
// Foo instance will continue to live,
// despite p2 going out of scope
}
std::cout << "About to leave program...\n";
}
```
Output:
```
Foo 1
Creating new Foo...
Foo 2
~Foo 1
About to leave inner block...
About to leave program...
~Foo 2
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2118](https://cplusplus.github.io/LWG/issue2118) | C++11 | `unique_ptr<T[]>::operator=` rejected qualification conversions | accepts |
| [LWG 2228](https://cplusplus.github.io/LWG/issue2228) | C++11 | the converting assignment operator was not constrained | constrained |
| [LWG 2899](https://cplusplus.github.io/LWG/issue2899) | C++11 | the move assignment operator was not constrained | constrained |
cpp std::unique_ptr<T,Deleter>::unique_ptr std::unique\_ptr<T,Deleter>::unique\_ptr
========================================
| | | |
| --- | --- | --- |
| members of the primary template, unique\_ptr<T> | | |
|
```
constexpr unique_ptr() noexcept;
constexpr unique_ptr( std::nullptr_t ) noexcept;
```
| (1) | |
|
```
explicit unique_ptr( pointer p ) noexcept;
```
| (2) | (constexpr since C++23) |
|
```
unique_ptr( pointer p, /* see below */ d1 ) noexcept;
```
| (3) | (constexpr since C++23) |
|
```
unique_ptr( pointer p, /* see below */ d2 ) noexcept;
```
| (4) | (constexpr since C++23) |
|
```
unique_ptr( unique_ptr&& u ) noexcept;
```
| (5) | (constexpr since C++23) |
|
```
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u ) noexcept;
```
| (6) | (constexpr since C++23) |
|
```
template< class U >
unique_ptr( std::auto_ptr<U>&& u ) noexcept;
```
| (7) | (removed in C++17) |
| members of the specialization for arrays, unique\_ptr<T[]> | | |
|
```
constexpr unique_ptr() noexcept;
constexpr unique_ptr( std::nullptr_t ) noexcept;
```
| (1) | |
|
```
template< class U > explicit unique_ptr( U p ) noexcept;
```
| (2) | (constexpr since C++23) |
|
```
template< class U > unique_ptr( U p, /* see below */ d1 ) noexcept;
```
| (3) | (constexpr since C++23) |
|
```
template< class U > unique_ptr( U p, /* see below */ d2 ) noexcept;
```
| (4) | (constexpr since C++23) |
|
```
unique_ptr( unique_ptr&& u ) noexcept;
```
| (5) | (constexpr since C++23) |
|
```
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u ) noexcept;
```
| (6) | (constexpr since C++23) |
1) Constructs a `std::unique_ptr` that owns nothing. Value-initializes the stored pointer and the stored deleter. Requires that `Deleter` is [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible") and that construction does not throw an exception. These overloads participate in overload resolution only if `[std::is\_default\_constructible](http://en.cppreference.com/w/cpp/types/is_default_constructible)<Deleter>::value` is `true` and `Deleter` is not a pointer type.
2) Constructs a `std::unique_ptr` which owns p, initializing the stored pointer with p and value-initializing the stored deleter. Requires that `Deleter` is [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible") and that construction does not throw an exception. This overload participates in overload resolution only if `[std::is\_default\_constructible](http://en.cppreference.com/w/cpp/types/is_default_constructible)<Deleter>::value` is `true` and `Deleter` is not a pointer type.
| | |
| --- | --- |
| This constructor is not selected by [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++17) |
3-4) Constructs a `std::unique_ptr` object which owns `p`, initializing the stored pointer with `p` and initializing a deleter `D` as below (depends upon whether `D` is a reference type)
a) If `D` is non-reference type `A`, then the signatures are:
| | | |
| --- | --- | --- |
|
```
unique_ptr(pointer p, const A& d) noexcept;
```
| (1) | (requires that `Deleter` is nothrow-[CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible")) |
|
```
unique_ptr(pointer p, A&& d) noexcept;
```
| (2) | (requires that `Deleter` is nothrow-[MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible")) |
b) If `D` is an lvalue-reference type `A&`, then the signatures are:
| | | |
| --- | --- | --- |
|
```
unique_ptr(pointer p, A& d) noexcept;
```
| (1) | |
|
```
unique_ptr(pointer p, A&& d) = delete;
```
| (2) | |
c) If `D` is an lvalue-reference type `const A&`, then the signatures are:
| | | |
| --- | --- | --- |
|
```
unique_ptr(pointer p, const A& d) noexcept;
```
| (1) | |
|
```
unique_ptr(pointer p, const A&& d) = delete;
```
| (2) | |
In all cases the deleter is initialized from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<decltype(d)>(d)`. These overloads participate in overload resolution only if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<D, decltype(d)>::value` is `true`.
| | |
| --- | --- |
| These two constructors are not selected by [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++17) |
2-4) in the specialization for arrays behave the same as the constructors that take a pointer parameter in the primary template except that they additionally do not participate in overload resolution unless one of the following is true: * `U` is the same type as `pointer`, or
* `U` is `[std::nullptr\_t](../../types/nullptr_t "cpp/types/nullptr t")`, or
* `pointer` is the same type as `element_type*` and `U` is some pointer type `V*` such that `V(*)[]` is implicitly convertible to `element_type(*)[]`.
5) Constructs a `unique_ptr` by transferring ownership from `u` to `*this` and stores the null pointer in `u`. This constructor only participates in overload resolution if `[std::is\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<Deleter>::value` is `true`. If `Deleter` is not a reference type, requires that it is nothrow-[MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") (if `Deleter` is a reference, `get_deleter()` and `u.get_deleter()` after move construction reference the same value)
6) Constructs a `unique_ptr` by transferring ownership from `u` to `*this`, where `u` is constructed with a specified deleter (`E`). It depends upon whether `E` is a reference type, as following:
a) if `E` is a reference type, this deleter is copy constructed from `u`'s deleter (requires that this construction does not throw)
b) if `E` is a non-reference type, this deleter is move constructed from `u`'s deleter (requires that this construction does not throw)
This constructor only participates in overload resolution if all of the following is true:
a) `unique_ptr<U, E>::pointer` is implicitly convertible to `pointer`
b) U is not an array type
c) Either `Deleter` is a reference type and `E` is the same type as `D`, or `Deleter` is not a reference type and `E` is implicitly convertible to `D`
6) in the specialization for arrays behaves the same as in the primary template, except that it will only participate in overload resolution if all of the following is true * `U` is an array type
* `pointer` is the same type as `element_type*`
* `unique_ptr<U,E>::pointer` is the same type as `unique_ptr<U,E>::element_type*`
* `unique_ptr<U,E>::element_type(*)[]` is convertible to `element_type(*)[]`
* either `Deleter` is a reference type and `E` is the same type as `Deleter`, or `Deleter` is not a reference type and `E` is implicitly convertible to `Deleter`.
7) Constructs a `unique_ptr` where the stored pointer is initialized with [`u.release()`](../auto_ptr/release "cpp/memory/auto ptr/release") and the stored deleter is value-initialized. This constructor only participates in overload resolution if `U*` is implicitly convertible to `T*` and `Deleter` is the same type as `[std::default\_delete](http://en.cppreference.com/w/cpp/memory/default_delete)<T>`. ### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to an object to manage |
| d1,d2 | - | a deleter to use to destroy the object |
| u | - | another smart pointer to acquire the ownership from |
### Notes
| | |
| --- | --- |
| Instead of using the overload (2) together with new, it is often a better idea to use `[std::make\_unique<T>](make_unique "cpp/memory/unique ptr/make unique")`. | (since C++14) |
`[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<Derived>` is implicitly convertible to `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<Base>` through the overload (6) (because both the managed pointer and `[std::default\_delete](../default_delete "cpp/memory/default delete")` are implicitly convertible).
Because the default constructor is `constexpr`, static unique\_ptrs are initialized as part of [static non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization"), before any dynamic non-local initialization begins. This makes it safe to use a unique\_ptr in a constructor of any static object.
| | |
| --- | --- |
| There is no [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") from pointer type because it is impossible to distinguish a pointer obtained from array and non-array forms of `new`. | (since C++17) |
### Example
```
#include <iostream>
#include <memory>
struct Foo { // object to manage
Foo() { std::cout << "Foo ctor\n"; }
Foo(const Foo&) { std::cout << "Foo copy ctor\n"; }
Foo(Foo&&) { std::cout << "Foo move ctor\n"; }
~Foo() { std::cout << "~Foo dtor\n"; }
};
struct D { // deleter
D() {};
D(const D&) { std::cout << "D copy ctor\n"; }
D(D&) { std::cout << "D non-const copy ctor\n";}
D(D&&) { std::cout << "D move ctor \n"; }
void operator()(Foo* p) const {
std::cout << "D is deleting a Foo\n";
delete p;
};
};
int main()
{
std::cout << "Example constructor(1)...\n";
std::unique_ptr<Foo> up1; // up1 is empty
std::unique_ptr<Foo> up1b(nullptr); // up1b is empty
std::cout << "Example constructor(2)...\n";
{
std::unique_ptr<Foo> up2(new Foo); //up2 now owns a Foo
} // Foo deleted
std::cout << "Example constructor(3)...\n";
D d;
{ // deleter type is not a reference
std::unique_ptr<Foo, D> up3(new Foo, d); // deleter copied
}
{ // deleter type is a reference
std::unique_ptr<Foo, D&> up3b(new Foo, d); // up3b holds a reference to d
}
std::cout << "Example constructor(4)...\n";
{ // deleter is not a reference
std::unique_ptr<Foo, D> up4(new Foo, D()); // deleter moved
}
std::cout << "Example constructor(5)...\n";
{
std::unique_ptr<Foo> up5a(new Foo);
std::unique_ptr<Foo> up5b(std::move(up5a)); // ownership transfer
}
std::cout << "Example constructor(6)...\n";
{
std::unique_ptr<Foo, D> up6a(new Foo, d); // D is copied
std::unique_ptr<Foo, D> up6b(std::move(up6a)); // D is moved
std::unique_ptr<Foo, D&> up6c(new Foo, d); // D is a reference
std::unique_ptr<Foo, D> up6d(std::move(up6c)); // D is copied
}
#if (__cplusplus < 201703L)
std::cout << "Example constructor(7)...\n";
{
std::auto_ptr<Foo> up7a(new Foo);
std::unique_ptr<Foo> up7b(std::move(up7a)); // ownership transfer
}
#endif
std::cout << "Example array constructor...\n";
{
std::unique_ptr<Foo[]> up(new Foo[3]);
} // three Foo objects deleted
}
```
Output:
```
Example constructor(1)...
Example constructor(2)...
Foo ctor
~Foo dtor
Example constructor(3)...
Foo ctor
D copy ctor
D is deleting a Foo
~Foo dtor
Foo ctor
D is deleting a Foo
~Foo dtor
Example constructor(4)...
Foo ctor
D move ctor
D is deleting a Foo
~Foo dtor
Example constructor(5)...
Foo ctor
~Foo dtor
Example constructor(6)...
Foo ctor
D copy ctor
D move ctor
Foo ctor
D non-const copy ctor
D is deleting a Foo
~Foo dtor
D is deleting a Foo
~Foo dtor
Example constructor(7)...
Foo ctor
~Foo dtor
Example array constructor...
Foo ctor
Foo ctor
Foo ctor
~Foo dtor
~Foo dtor
~Foo dtor
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2118](https://cplusplus.github.io/LWG/issue2118) | C++11 | Constructors of `unique_ptr<T[]>` rejected qualification conversions. | Accept. |
| [LWG 2520](https://cplusplus.github.io/LWG/issue2520) | C++11 | `unique_ptr<T[]>` was accidentally made non-constructible from `nullptr_t`. | Made constructible. |
| [LWG 2801](https://cplusplus.github.io/LWG/issue2801) | C++11 | The default constructor was not constrained. | Constrained. |
| [LWG 2899](https://cplusplus.github.io/LWG/issue2899) | C++11 | The move constructor was not constrained. | Constrained. |
| [LWG 2905](https://cplusplus.github.io/LWG/issue2905) | C++11 | Constraint on the constructor from a pointer and a deleter was wrong. | Corrected. |
| [LWG 2944](https://cplusplus.github.io/LWG/issue2944) | C++11 | Some preconditions were accidentally dropped by LWG 2905 | Restored. |
| programming_docs |
cpp std::make_unique, std::make_unique_for_overwrite std::make\_unique, std::make\_unique\_for\_overwrite
====================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
```
| (since C++14) (until C++23) (only for non-array types) |
|
```
template< class T, class... Args >
constexpr unique_ptr<T> make_unique( Args&&... args );
```
| (since C++23) (only for non-array types) |
| | (2) | |
|
```
template< class T >
unique_ptr<T> make_unique( std::size_t size );
```
| (since C++14) (until C++23) (only for array types with unknown bound) |
|
```
template< class T >
constexpr unique_ptr<T> make_unique( std::size_t size );
```
| (since C++23) (only for array types with unknown bound) |
|
```
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete;
```
| (3) | (since C++14) (only for array types with known bound) |
| | (4) | |
|
```
template< class T >
unique_ptr<T> make_unique_for_overwrite( );
```
| (since C++20) (until C++23) (only for non-array types) |
|
```
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite( );
```
| (since C++23) (only for non-array types) |
| | (5) | |
|
```
template< class T >
unique_ptr<T> make_unique_for_overwrite( std::size_t size );
```
| (since C++20) (until C++23) (only for array types with unknown bound) |
|
```
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite( std::size_t size );
```
| (since C++23) (only for array types with unknown bound) |
|
```
template< class T, class... Args >
/* unspecified */ make_unique_for_overwrite( Args&&... args ) = delete;
```
| (6) | (since C++20) (only for array types with known bound) |
Constructs an object of type `T` and wraps it in a `[std::unique\_ptr](../unique_ptr "cpp/memory/unique ptr")`.
1) Constructs a non-array type `T`. The arguments `args` are passed to the constructor of `T`. This overload participates in overload resolution only if `T` is not an array type. The function is equivalent to:
```
unique_ptr<T>(new T(std::forward<Args>(args)...))
```
2) Constructs an array of the given dynamic size. The array elements are [value-initialized](../../language/value_initialization "cpp/language/value initialization"). This overload participates in overload resolution only if `T` is an array of unknown bound. The function is equivalent to:
```
unique_ptr<T>(new std::remove_extent_t<T>[size]())
```
3,6) Construction of arrays of known bound is disallowed.
4) Same as (1), except that the object is [default-initialized](../../language/default_initialization "cpp/language/default initialization"). This overload participates in overload resolution only if `T` is not an array type. The function is equivalent to:
```
unique_ptr<T>(new T)
```
5) Same as (2), except that the array is default-initialized. This overload participates in overload resolution only if `T` is an array of unknown bound. The function is equivalent to:
```
unique_ptr<T>(new std::remove_extent_t<T>[size])
```
### Parameters
| | | |
| --- | --- | --- |
| args | - | list of arguments with which an instance of `T` will be constructed. |
| size | - | the length of the array to construct |
### Return value
`[std::unique\_ptr](../unique_ptr "cpp/memory/unique ptr")` of an instance of type `T`.
### Exceptions
May throw `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` or any exception thrown by the constructor of `T`. If an exception is thrown, this function has no effect.
### Possible Implementation
| First version |
| --- |
|
```
// C++14 make_unique
namespace detail {
template<class>
constexpr bool is_unbounded_array_v = false;
template<class T>
constexpr bool is_unbounded_array_v<T[]> = true;
template<class>
constexpr bool is_bounded_array_v = false;
template<class T, std::size_t N>
constexpr bool is_bounded_array_v<T[N]> = true;
} // namespace detail
template<class T, class... Args>
std::enable_if_t<!std::is_array<T>::value, std::unique_ptr<T>>
make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<class T>
std::enable_if_t<detail::is_unbounded_array_v<T>, std::unique_ptr<T>>
make_unique(std::size_t n)
{
return std::unique_ptr<T>(new std::remove_extent_t<T>[n]());
}
template<class T, class... Args>
std::enable_if_t<detail::is_bounded_array_v<T>> make_unique(Args&&...) = delete;
```
|
| Second version |
|
```
// C++20 make_unique_for_overwrite
template<class T>
requires !std::is_array_v<T>
std::unique_ptr<T> make_unique_for_overwrite()
{
return std::unique_ptr<T>(new T);
}
template<class T>
requires std::is_unbounded_array_v<T>
std::unique_ptr<T> make_unique_for_overwrite(std::size_t n)
{
return std::unique_ptr<T>(new std::remove_extent_t<T>[n]);
}
template<class T, class... Args>
requires std::is_bounded_array_v<T>
void make_unique_for_overwrite(Args&&...) = delete;
```
|
### Notes
Unlike `[std::make\_shared](../shared_ptr/make_shared "cpp/memory/shared ptr/make shared")` (which has `[std::allocate\_shared](../shared_ptr/allocate_shared "cpp/memory/shared ptr/allocate shared")`), `std::make_unique` does not have an allocator-aware counterpart. `allocate_unique` proposed in [P0211](https://wg21.link/P0211) would be required to invent the deleter type `D` for the `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<T,D>` it returns which would contain an allocator object and invoke both `destroy` and `deallocate` in its `operator()`.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_make_unique`](../../feature_test#Library_features "cpp/feature test") | `201304L` | (C++14) |
| [`__cpp_lib_smart_ptr_for_overwrite`](../../feature_test#Library_features "cpp/feature test") | `202002L` | (C++20) | for overloads (4-6) |
| [`__cpp_lib_constexpr_memory`](../../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | `constexpr` for overloads (1,2,4,5) |
### Example
```
#include <iostream>
#include <iomanip>
#include <memory>
struct Vec3
{
int x, y, z;
// following constructor is no longer needed since C++20
Vec3(int x = 0, int y = 0, int z = 0) noexcept : x(x), y(y), z(z) { }
friend std::ostream& operator<<(std::ostream& os, const Vec3& v) {
return os << "{ x=" << v.x << ", y=" << v.y << ", z=" << v.z << " }";
}
};
int main()
{
// Use the default constructor.
std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
// Use the constructor that matches these arguments
std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0,1,2);
// Create a unique_ptr to an array of 5 elements
std::unique_ptr<Vec3[]> v3 = std::make_unique<Vec3[]>(5);
std::cout << "make_unique<Vec3>(): " << *v1 << '\n'
<< "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
<< "make_unique<Vec3[]>(5): ";
for (int i = 0; i < 5; i++) {
std::cout << std::setw(i ? 30 : 0) << v3[i] << '\n';
}
}
```
Output:
```
make_unique<Vec3>(): { x=0, y=0, z=0 }
make_unique<Vec3>(0,1,2): { x=0, y=1, z=2 }
make_unique<Vec3[]>(5): { x=0, y=0, z=0 }
{ x=0, y=0, z=0 }
{ x=0, y=0, z=0 }
{ x=0, y=0, z=0 }
{ x=0, y=0, z=0 }
```
### See also
| | |
| --- | --- |
| [(constructor)](unique_ptr "cpp/memory/unique ptr/unique ptr") | constructs a new `unique_ptr` (public member function) |
| [make\_sharedmake\_shared\_for\_overwrite](../shared_ptr/make_shared "cpp/memory/shared ptr/make shared")
(C++20) | creates a shared pointer that manages a new object (function template) |
cpp operator==,!=,<,<=,>,>=,<=>(std::unique_ptr)
operator==,!=,<,<=,>,>=,<=>(std::unique\_ptr)
=============================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator==( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator!=( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (2) | (since C++11) (until C++20) |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator<( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (3) | (since C++11) |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator<=( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (4) | (since C++11) |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator>( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (5) | (since C++11) |
|
```
template< class T1, class D1, class T2, class D2 >
bool operator>=( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (6) | (since C++11) |
|
```
template< class T1, class D1, class T2, class D2 >
requires std::three_way_comparable_with<
typename unique_ptr<T1, D1>::pointer,
typename unique_ptr<T2, D2>::pointer>
std::compare_three_way_result_t<typename unique_ptr<T1, D1>::pointer,
typename unique_ptr<T2, D2>::pointer>
operator<=>( const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y );
```
| (7) | (since C++20) |
|
```
template< class T, class D >
bool operator==( const unique_ptr<T, D>& x, std::nullptr_t) noexcept;
```
| (8) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator==(std::nullptr_t, const unique_ptr<T, D>& x) noexcept;
```
| (9) | (since C++11) (until C++20) |
|
```
template< class T, class D >
bool operator!=( const unique_ptr<T, D>& x, std::nullptr_t) noexcept;
```
| (10) | (since C++11) (until C++20) |
|
```
template< class T, class D >
bool operator!=(std::nullptr_t, const unique_ptr<T, D>& x) noexcept;
```
| (11) | (since C++11) (until C++20) |
|
```
template< class T, class D >
bool operator<( const unique_ptr<T, D>& x, std::nullptr_t );
```
| (12) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator<(std::nullptr_t, const unique_ptr<T, D>& y );
```
| (13) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator<=( const unique_ptr<T, D>& x, std::nullptr_t );
```
| (14) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator<=(std::nullptr_t, const unique_ptr<T, D>& y );
```
| (15) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator>( const unique_ptr<T, D>& x, std::nullptr_t );
```
| (16) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator>(std::nullptr_t, const unique_ptr<T, D>& y );
```
| (17) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator>=( const unique_ptr<T, D>& x, std::nullptr_t );
```
| (18) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
bool operator>=(std::nullptr_t, const unique_ptr<T, D>& y );
```
| (19) | (since C++11) (constexpr since C++23) |
|
```
template< class T, class D >
requires std::three_way_comparable<typename unique_ptr<T, D>::pointer>
std::compare_three_way_result_t<typename unique_ptr<T, D>::pointer>
operator<=>( const unique_ptr<T, D>& x, std::nullptr_t );
```
| (20) | (since C++20) (constexpr since C++23) |
Compares the pointer values of two `unique_ptr`s, or a `unique_ptr` and `nullptr`.
1-7) Compares two `unique_ptr`s
8-20) Compares a `unique_ptr` and `nullptr`.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | `unique_ptr`s to compare |
### Return value
1) `x.get() == y.get()`
2) `x.get() != y.get()`
3) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<CT>()(x.get(), y.get())`, where `CT` is `[std::common\_type](http://en.cppreference.com/w/cpp/types/common_type)<unique_ptr<T1, D1>::pointer, unique_ptr<T2, D2>::pointer>::type`
4) `!(y < x)`
5) `y < x`
6) `!(x < y)`
7) `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way){}(x.get(), y.get())`
8-9) `!x`
10-11) `(bool)x`
12) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<unique_ptr<T,D>::pointer>()(x.get(), nullptr)`
13) `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<unique_ptr<T,D>::pointer>()(nullptr, y.get())`
14) `!(nullptr < x)`
15) `!(y < nullptr)`
16) `nullptr < x`
17) `y < nullptr`
18) `!(x < nullptr)`
19) `!(nullptr < y)`
20) `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way){}(x.get(), static\_cast<typename unique_ptr<T, D>::pointer>(nullptr))`
### Example
```
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> p1(new int(42));
std::unique_ptr<int> p2(new int(42));
std::cout << std::boolalpha
<< "(p1 == p1) : " << (p1 == p1) << '\n'
<< "(p1 <=> p1) == 0 : " << ((p1 <=> p1) == 0) << '\n' // Since C++20
// p1 and p2 point to different memory locations, so p1 != p2
<< "(p1 == p2) : " << (p1 == p2) << '\n'
<< "(p1 < p2) : " << (p1 < p2) << '\n'
<< "(p1 <=> p2) < 0 : " << ((p1 <=> p2) < 0) << '\n' // Since C++20
<< "(p1 <=> p2) == 0 : " << ((p1 <=> p2) == 0) << '\n'; // Since C++20
}
```
Possible output:
```
(p1 == p1) : true
(p1 <=> p1) == 0 : true
(p1 == p2) : false
(p1 < p2) : true
(p1 <=> p2) < 0 : true
(p1 <=> p2) == 0 : false
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3426](https://cplusplus.github.io/LWG/issue3426) | C++20 | `operator<=>(unique_ptr, nullptr_t)` was ill-formed | constraints and definition fixed |
### See also
| | |
| --- | --- |
| [get](get "cpp/memory/unique ptr/get") | returns a pointer to the managed object (public member function) |
cpp std::unique_ptr<T,Deleter>::get std::unique\_ptr<T,Deleter>::get
================================
| | | |
| --- | --- | --- |
|
```
pointer get() const noexcept;
```
| | (since C++11) (constexpr since C++23) |
Returns a pointer to the managed object or `nullptr` if no object is owned.
### Parameters
(none).
### Return value
Pointer to the managed object or `nullptr` if no object is owned.
### Example
```
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
class Res {
std::string s;
public:
Res(std::string arg) : s{ std::move(arg) } {
std::cout << "Res::Res(" << std::quoted(s) << ");\n";
}
~Res() {
std::cout << "Res::~Res();\n";
}
private:
friend std::ostream& operator<< (std::ostream& os, Res const& r) {
return os << "Res { s = " << quoted(r.s) << "; }";
}
};
int main()
{
std::unique_ptr<Res> up(new Res{"Hello, world!"});
Res *res = up.get();
std::cout << *res << '\n';
}
```
Output:
```
Res::Res("Hello, world!");
Res { s = "Hello, world!"; }
Res::~Res();
```
### See also
| | |
| --- | --- |
| [release](release "cpp/memory/unique ptr/release") | returns a pointer to the managed object and releases the ownership (public member function) |
cpp std::allocator_traits<Alloc>::deallocate std::allocator\_traits<Alloc>::deallocate
=========================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
static void deallocate( Alloc& a, pointer p, size_type n );
```
| | (since C++11) (until C++20) |
|
```
static constexpr void deallocate( Alloc& a, pointer p, size_type n );
```
| | (since C++20) |
Uses the allocator `a` to deallocate the storage referenced by `p`, by calling `a.deallocate(p, n)`.
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator to use |
| p | - | pointer to the previously allocated storage |
| n | - | the number of objects the storage was allocated for |
### Return value
(none).
### See also
| | |
| --- | --- |
| [allocate](allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function) |
| [deallocate](../allocator/deallocate "cpp/memory/allocator/deallocate") | deallocates storage (public member function of `std::allocator<T>`) |
cpp std::allocator_traits<Alloc>::max_size std::allocator\_traits<Alloc>::max\_size
========================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
static size_type max_size( const Alloc& a ) noexcept;
```
| | (since C++11) (until C++20) |
|
```
static constexpr size_type max_size( const Alloc& a ) noexcept;
```
| | (since C++20) |
If possible, obtains the maximum theoretically possible allocation size from the allocator `a`, by calling `a.max_size()`.
If the above is not possible (e.g. `Alloc` does not have the member function `max_size()`), then returns `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<size_type>::max() / sizeof(value_type)`.
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator to detect |
### Return value
Theoretical maximum allocation size.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2162](https://cplusplus.github.io/LWG/issue2162) | C++11 | `max_size` was not requied to be noexcept | required |
| [LWG 2466](https://cplusplus.github.io/LWG/issue2466) | C++11 | theoretical maximum allocation size in bytes was returned as fallback | size in elements is returned |
### See also
| | |
| --- | --- |
| [max\_size](../allocator/max_size "cpp/memory/allocator/max size")
(until C++20) | returns the largest supported allocation size (public member function of `std::allocator<T>`) |
cpp std::allocator_traits<Alloc>::construct std::allocator\_traits<Alloc>::construct
========================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T, class... Args >
static void construct( Alloc& a, T* p, Args&&... args );
```
| | (since C++11) (until C++20) |
|
```
template< class T, class... Args >
static constexpr void construct( Alloc& a, T* p, Args&&... args );
```
| | (since C++20) |
If possible, constructs an object of type `T` in allocated uninitialized storage pointed to by `p`, by calling.
`a.construct(p, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`.
If the above is not possible (e.g. `Alloc` does not have the member function `construct()`), then calls.
| | |
| --- | --- |
| `::new (static\_cast<void\*>(p)) T([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`. | (until C++20) |
| `[std::construct\_at](http://en.cppreference.com/w/cpp/memory/construct_at)(p, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator to use for construction |
| p | - | pointer to the uninitialized storage on which a `T` object will be constructed |
| args... | - | the constructor arguments to pass to `a.construct()` or to placement-new (until C++20)`[std::construct\_at()](../construct_at "cpp/memory/construct at")` (since C++20) |
### Return value
(none).
### Notes
This function is used by the standard library containers when inserting, copying, or moving elements.
Because this function provides the automatic fall back to placement new, the member function `construct()` is an optional [Allocator](../../named_req/allocator "cpp/named req/Allocator") requirement since C++11.
### See also
| | |
| --- | --- |
| [operator newoperator new[]](../new/operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [construct](../allocator/construct "cpp/memory/allocator/construct")
(until C++20) | constructs an object in allocated storage (public member function of `std::allocator<T>`) |
| [construct\_at](../construct_at "cpp/memory/construct at")
(C++20) | creates an object at a given address (function template) |
| programming_docs |
cpp std::allocator_traits<Alloc>::destroy std::allocator\_traits<Alloc>::destroy
======================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
static void destroy( Alloc& a, T* p );
```
| | (since C++11) (until C++20) |
|
```
template< class T >
static constexpr void destroy( Alloc& a, T* p );
```
| | (since C++20) |
Calls the destructor of the object pointed to by `p`. If possible, does so by calling `a.destroy(p)`. If not possible (e.g. `Alloc` does not have the member function `destroy()`), then calls the destructor of `*p` directly, as `p->~T()` (until C++20)`[std::destroy\_at](http://en.cppreference.com/w/cpp/memory/destroy_at)(p)` (since C++20).
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator to use for destruction |
| p | - | pointer to the object being destroyed |
### Return value
(none).
### Notes
Because this function provides the automatic fall back to direct call to the destructor, the member function `destroy()` is an optional [Allocator](../../named_req/allocator "cpp/named req/Allocator") requirement since C++11.
### See also
| | |
| --- | --- |
| [destroy](../allocator/destroy "cpp/memory/allocator/destroy")
(until C++20) | destructs an object in allocated storage (public member function of `std::allocator<T>`) |
cpp std::allocator_traits<Alloc>::select_on_container_copy_construction std::allocator\_traits<Alloc>::select\_on\_container\_copy\_construction
========================================================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
static Alloc select_on_container_copy_construction( const Alloc& a );
```
| | (since C++11) (until C++20) |
|
```
static constexpr Alloc select_on_container_copy_construction( const Alloc& a );
```
| | (since C++20) |
If possible, obtains the copy-constructed version of the allocator `a`, by calling `a.select_on_container_copy_construction()`. If the above is not possible (e.g. `Alloc` does not have the member function `select_on_container_copy_construction()`), then returns `a`, unmodified.
This function is called by the copy constructors of all standard library containers. It allows the allocator used by the constructor's argument to become aware that the container is being copied and modify state if necessary.
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator used by a standard container passed as an argument to a container copy constructor |
### Return value
The allocator to use by the copy-constructed standard containers.
### See also
| | |
| --- | --- |
| [select\_on\_container\_copy\_construction](../scoped_allocator_adaptor/select_on_container_copy_construction "cpp/memory/scoped allocator adaptor/select on container copy construction") | copies the state of scoped\_allocator\_adaptor and all its allocators (public member function of `std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>`) |
cpp std::allocator_traits<Alloc>::allocate std::allocator\_traits<Alloc>::allocate
=======================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
| | (1) | |
|
```
static pointer allocate( Alloc& a, size_type n );
```
| (since C++11) (until C++20) |
|
```
[[nodiscard]] static constexpr pointer allocate( Alloc& a, size_type n );
```
| (since C++20) |
| | (2) | |
|
```
static pointer allocate( Alloc& a, size_type n,
const_void_pointer hint );
```
| (since C++11) (until C++20) |
|
```
[[nodiscard]] static constexpr pointer allocate( Alloc& a, size_type n,
const_void_pointer hint );
```
| (since C++20) |
Uses the allocator `a` to allocate `n*sizeof(Alloc::value_type)` bytes of uninitialized storage. An array of type `Alloc::value_type[n]` is created in the storage, but none of its elements are constructed.
1) Calls `a.allocate(n)`
2) Additionally passes memory locality hint `hint`. Calls `a.allocate(n, hint)` if possible. If not possible (e.g. a has no two-argument member function allocate()), calls `a.allocate(n)`
### Parameters
| | | |
| --- | --- | --- |
| a | - | allocator to use |
| n | - | the number of objects to allocate storage for |
| hint | - | pointer to a nearby memory location |
### Return value
The pointer returned by the call to `a.allocate(n)`.
### Notes
`Alloc::allocate` was not required to create array object until [P0593R6](https://wg21.link/P0593R6), which made using non-default allocator for `[std::vector](../../container/vector "cpp/container/vector")` and some other containers not actually well-defined according to the core language specification.
After calling `allocate` and before construction of elements, pointer arithmetic of `Alloc::value_type*` is well-defined within the allocated array, but the behavior is undefined if elements are accessed.
### See also
| | |
| --- | --- |
| [allocate](../allocator/allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function of `std::allocator<T>`) |
cpp std::allocator<T>::allocator std::allocator<T>::allocator
============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
allocator() throw();
```
| (until C++11) |
|
```
allocator() noexcept;
```
| (since C++11) (until C++20) |
|
```
constexpr allocator() noexcept;
```
| (since C++20) |
| | (2) | |
|
```
allocator( const allocator& other ) throw();
```
| (until C++11) |
|
```
allocator( const allocator& other ) noexcept;
```
| (since C++11) (until C++20) |
|
```
constexpr allocator( const allocator& other ) noexcept;
```
| (since C++20) |
| | (3) | |
|
```
template< class U >
allocator( const allocator<U>& other ) throw();
```
| (until C++11) |
|
```
template< class U >
allocator( const allocator<U>& other ) noexcept;
```
| (since C++11) (until C++20) |
|
```
template< class U >
constexpr allocator( const allocator<U>& other ) noexcept;
```
| (since C++20) |
Constructs the default allocator. Since the default allocator is stateless, the constructors have no visible effect.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another allocator to construct with |
cpp std::allocator<T>::~allocator std::allocator<T>::~allocator
=============================
| | | |
| --- | --- | --- |
|
```
~allocator();
```
| | (until C++20) |
|
```
constexpr ~allocator();
```
| | (since C++20) |
Destroys the default allocator.
cpp std::allocator<T>::allocate_at_least std::allocator<T>::allocate\_at\_least
======================================
| | | |
| --- | --- | --- |
|
```
[[nodiscard]] constexpr std::allocation_result<T*>
allocate_at_least( std::size_t n );
```
| | (since C++23) |
Allocates `count * sizeof(T)` bytes of uninitialized storage, where `count` is an unspecified integer value not less than `n`, by calling `::[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` (an additional `[std::align\_val\_t](../new/align_val_t "cpp/memory/new/align val t")` argument might be provided), but it is unspecified when and how this function is called.
Then, this function creates an array of type `T[count]` in the storage and starts its lifetime, but does not start lifetime of any of its elements.
In order to use this function in a constant expression, the allocated storage must be deallocated within the evaluation of the same expression.
Use of this function is ill-formed if `T` is an [incomplete type](../../language/type#Incomplete_type "cpp/language/type").
### Parameters
| | | |
| --- | --- | --- |
| n | - | the lower bound of number of objects to allocate storage for |
### Return value
`std::allocation_result<T*>{p, count}`, where `p` points to the first element of an array of `count` objects of type `T` whose elements have not been constructed yet.
### Exceptions
Throws `[std::bad\_array\_new\_length](../new/bad_array_new_length "cpp/memory/new/bad array new length")` if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max() / sizeof(T) < n`, or `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if allocation fails.
### Notes
`allocate_at_least` is mainly provided for contiguous containers, e.g. `[std::vector](../../container/vector "cpp/container/vector")` and `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, in order to reduce reallocation by making their capacity match the actually allocated size when possible.
The "unspecified when and how" wording makes it possible to [combine or optimize away heap allocations](../../language/new#Allocation "cpp/language/new") made by the standard library containers, even though such optimizations are disallowed for direct calls to `::[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)`. For example, this is implemented by libc++ ([[1]](https://github.com/llvm-mirror/libcxx/blob/master@%7B2017-02-09%7D/include/memory#L1766-L1772) and [[2]](https://github.com/llvm-mirror/libcxx/blob/master@%7B2017-02-09%7D/include/new#L211-L217)).
After calling `allocate_at_least` and before construction of elements, pointer arithmetic of `T*` is well-defined within the allocated array, but the behavior is undefined if elements are accessed.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_allocate_at_least`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) |
### See also
| | |
| --- | --- |
| [allocate\_at\_least](../allocate_at_least "cpp/memory/allocate at least")
(C++23) | allocates storage at least as large as the requested size via an allocator (function template) |
| [allocation\_result](../allocation_result "cpp/memory/allocation result")
(C++23) | records the address and the actual size of storage allocated by `allocate_at_least` (class template) |
cpp std::allocator<T>::deallocate std::allocator<T>::deallocate
=============================
| | | |
| --- | --- | --- |
|
```
void deallocate( T* p, std::size_t n );
```
| | (until C++20) |
|
```
constexpr void deallocate( T* p, std::size_t n );
```
| | (since C++20) |
Deallocates the storage referenced by the pointer `p`, which must be a pointer obtained by an earlier call to `[allocate()](allocate "cpp/memory/allocator/allocate")` or [`allocate_at_least()`](allocate_at_least "cpp/memory/allocator/allocate at least") (since C++23).
The argument `n` must be equal to the first argument of the call to `[allocate()](allocate "cpp/memory/allocator/allocate")` that originally produced `p`, or in the range `[m, count]` if `p` is obtained from a call to `allocate_at_least(m)` which returned `{p, count}` (since C++23); otherwise, the behavior is undefined.
Calls `::[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)(void\*)` or `::[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)(void\*, [std::align\_val\_t](http://en.cppreference.com/w/cpp/memory/new/align_val_t))` (since C++17), but it is unspecified when and how it is called.
| | |
| --- | --- |
| In evaluation of a constant expression, this function must deallocate storage allocated within the evaluation of the same expression. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer obtained from `[allocate()](allocate "cpp/memory/allocator/allocate")` or [`allocate_at_least()`](allocate_at_least "cpp/memory/allocator/allocate at least") (since C++23) |
| n | - | number of objects earlier passed to `[allocate()](allocate "cpp/memory/allocator/allocate")`, or a number between requested and actually allocated number of objects via [`allocate_at_least()`](allocate_at_least "cpp/memory/allocator/allocate at least") (may be equal to either bound) (since C++23) |
### Return value
(none).
### Example
```
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
class S {
inline static int n{1};
int m{};
void pre() const { std::cout << "#" << m << std::string(m, ' '); }
public:
S(int x) : m{n++} { pre(); std::cout << "S::S(" << x << ");\n"; }
~S() { pre(); std::cout << "S::~S();\n"; }
void id() const { pre(); std::cout << "S::id();\n"; }
};
int main() {
constexpr std::size_t n{4};
std::allocator<S> allocator;
try {
S* s = allocator.allocate(n); // may throw
for (std::size_t i{}; i != n; ++i) {
// allocator.construct(&s[i], i+42); // removed in C++20
std::construct_at(&s[i], i+42); // since C++20
}
std::for_each_n(s, n, [](const auto& e) { e.id(); });
std::destroy_n(s, n);
allocator.deallocate(s, n);
}
catch(std::bad_array_new_length const& ex) { std::cout << ex.what() << '\n'; }
catch(std::bad_alloc const& ex) { std::cout << ex.what() << '\n'; }
}
```
Output:
```
#1 S::S(42);
#2 S::S(43);
#3 S::S(44);
#4 S::S(45);
#1 S::id();
#2 S::id();
#3 S::id();
#4 S::id();
#1 S::~S();
#2 S::~S();
#3 S::~S();
#4 S::~S();
```
### See also
| | |
| --- | --- |
| [allocate](allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function) |
| [allocate\_at\_least](allocate_at_least "cpp/memory/allocator/allocate at least")
(C++23) | allocates uninitialized storage at least as large as requested size (public member function) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::allocator<T>::max_size std::allocator<T>::max\_size
============================
| | | |
| --- | --- | --- |
|
```
size_type max_size() const throw();
```
| | (until C++11) |
|
```
size_type max_size() const noexcept;
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
Returns the maximum theoretically possible value of `n`, for which the call `allocate(n, 0)` could succeed.
In most implementations, this returns `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<size_type>::max() / sizeof(value_type)`.
### Parameters
(none).
### Return value
The maximum supported allocation size.
### See also
| | |
| --- | --- |
| [max\_size](../allocator_traits/max_size "cpp/memory/allocator traits/max size")
[static] | returns the maximum object size supported by the allocator (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::allocator<T>::construct std::allocator<T>::construct
============================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void construct( pointer p, const_reference val );
```
| (1) | (until C++11) |
|
```
template< class U, class... Args >
void construct( U* p, Args&&... args );
```
| (2) | (since C++11) (deprecated in C++17) (removed in C++20) |
Constructs an object of type `T` in allocated uninitialized storage pointed to by `p`, using placement-new.
1) Calls `new((void *)p) T(val)`
2) Calls `::new((void \*)p) U([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to allocated uninitialized storage |
| val | - | the value to use as the copy constructor argument |
| args... | - | the constructor arguments to use |
### Return value
(none).
### See also
| | |
| --- | --- |
| [construct](../allocator_traits/construct "cpp/memory/allocator traits/construct")
[static] | constructs an object in the allocated storage (function template) |
| [construct\_at](../construct_at "cpp/memory/construct at")
(C++20) | creates an object at a given address (function template) |
| [operator newoperator new[]](../new/operator_new "cpp/memory/new/operator new") | allocation functions (function) |
cpp std::allocator<T>::address std::allocator<T>::address
==========================
| | | |
| --- | --- | --- |
|
```
pointer address( reference x ) const;
```
| | (until C++11) |
|
```
pointer address( reference x ) const noexcept;
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
|
```
const_pointer address( const_reference x ) const;
```
| | (until C++11) |
|
```
const_pointer address( const_reference x ) const noexcept;
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
Returns the actual address of `x` even in presence of overloaded `operator&`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | the object to acquire address of |
### Return value
The actual address of `x`.
cpp std::allocator<T>::destroy std::allocator<T>::destroy
==========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void destroy( pointer p );
```
| | (until C++11) |
|
```
template< class U >
void destroy( U* p );
```
| | (since C++11) (deprecated in C++17) (removed in C++20) |
Calls the destructor of the object pointed to by `p`.
1) Calls `((T*)p)->~T()`
2) Calls `p->~U()`
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the object that is going to be destroyed |
### Return value
(none).
### See also
| | |
| --- | --- |
| [destroy](../allocator_traits/destroy "cpp/memory/allocator traits/destroy")
[static] | destructs an object stored in the allocated storage (function template) |
cpp operator==,!=(std::allocator) operator==,!=(std::allocator)
=============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T1, class T2 >
bool operator==( const allocator<T1>& lhs, const allocator<T2>& rhs ) throw();
```
| (until C++11) |
|
```
template< class T1, class T2 >
bool operator==( const allocator<T1>& lhs, const allocator<T2>& rhs ) noexcept;
```
| (since C++11) (until C++20) |
|
```
template< class T1, class T2 >
constexpr bool operator==( const allocator<T1>& lhs, const allocator<T2>& rhs ) noexcept;
```
| (since C++20) |
| | (2) | |
|
```
template< class T1, class T2 >
bool operator!=( const allocator<T1>& lhs, const allocator<T2>& rhs ) throw();
```
| (until C++11) |
|
```
template< class T1, class T2 >
bool operator!=( const allocator<T1>& lhs, const allocator<T2>& rhs ) noexcept;
```
| (since C++11) (until C++20) |
Compares two default allocators. Since default allocators are stateless, two default allocators are always equal.
1) Returns `true`
2) Returns `false`
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | default allocators to compare |
### Return value
1) `true`
2) `false`
cpp std::allocator<T>::allocate std::allocator<T>::allocate
===========================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
pointer allocate( size_type n, const void * hint = 0 );
```
| (until C++17) |
|
```
T* allocate( std::size_t n, const void * hint);
```
| (since C++17) (deprecated) (removed in C++20) |
| | (2) | |
|
```
T* allocate( std::size_t n );
```
| (since C++17) (until C++20) |
|
```
[[nodiscard]] constexpr T* allocate( std::size_t n );
```
| (since C++20) |
Allocates `n * sizeof(T)` bytes of uninitialized storage by calling `::[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t))` or `::[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), [std::align\_val\_t](http://en.cppreference.com/w/cpp/memory/new/align_val_t))` (since C++17), but it is unspecified when and how this function is called. The pointer `hint` may be used to provide locality of reference: the allocator, if supported by the implementation, will attempt to allocate the new memory block as close as possible to `hint`.
Then, this function creates an array of type `T[n]` in the storage and starts its lifetime, but does not start lifetime of any of its elements.
Use of this function is ill-formed if `T` is an [incomplete type](../../language/type#Incomplete_type "cpp/language/type").
| | |
| --- | --- |
| In order to use this function in a constant expression, the allocated storage must be deallocated within the evaluation of the same expression. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of objects to allocate storage for |
| hint | - | pointer to a nearby memory location |
### Return value
Pointer to the first element of an array of `n` objects of type `T` whose elements have not been constructed yet.
### Exceptions
| | |
| --- | --- |
| Throws `[std::bad\_array\_new\_length](../new/bad_array_new_length "cpp/memory/new/bad array new length")` if `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max() / sizeof(T) < n`. | (since C++11) |
Throws `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if allocation fails.
### Notes
The "unspecified when and how" wording makes it possible to [combine or optimize away heap allocations](../../language/new#Allocation "cpp/language/new") made by the standard library containers, even though such optimizations are disallowed for direct calls to `::operator new`. For example, this is implemented by libc++ ([[1]](https://github.com/llvm-mirror/libcxx/blob/master@%7B2017-02-09%7D/include/memory#L1766-L1772) and [[2]](https://github.com/llvm-mirror/libcxx/blob/master@%7B2017-02-09%7D/include/new#L211-L217)).
After calling `allocate` and before construction of elements, pointer arithmetic of `T*` is well-defined within the allocated array, but the behavior is undefined if elements are accessed.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3190](https://cplusplus.github.io/LWG/issue3190) | C++11 | `allocate` might allocate storage of wrong size | throws `bad_array_new_length` instead |
### See also
| | |
| --- | --- |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| programming_docs |
cpp std::weak_ptr<T>::reset std::weak\_ptr<T>::reset
========================
| | | |
| --- | --- | --- |
|
```
void reset() noexcept;
```
| | (since C++11) |
Releases the reference to the managed object. After the call `*this` manages no object.
### Parameters
(none).
### Return value
(none).
### Example
```
#include <memory>
#include <iostream>
int main()
{
auto shared = std::make_shared<int>(), shared2 = shared, shared3 = shared2;
auto weak = std::weak_ptr<int>{shared};
std::cout << std::boolalpha
<< "shared.use_count(): " << shared.use_count() << '\n'
<< "weak.use_count(): " << weak.use_count() << '\n'
<< "weak.expired(): " << weak.expired() << '\n';
weak.reset();
std::cout << "weak.reset();\n"
<< "shared.use_count(): " << shared.use_count() << '\n'
<< "weak.use_count(): " << weak.use_count() << '\n'
<< "weak.expired(): " << weak.expired() << '\n';
}
```
Output:
```
shared.use_count(): 3
weak.use_count(): 3
weak.expired(): false
weak.reset();
shared.use_count(): 3
weak.use_count(): 0
weak.expired(): true
```
### See also
| | |
| --- | --- |
| [expired](expired "cpp/memory/weak ptr/expired") | checks whether the referenced object was already deleted (public member function) |
cpp deduction guides for std::weak_ptr
deduction guides for `std::weak_ptr`
====================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template<class T>
weak_ptr(std::shared_ptr<T>) -> weak_ptr<T>;
```
| | (since C++17) |
One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` to account for the edge case missed by the implicit deduction guides.
### Example
```
#include <memory>
int main()
{
auto p = std::make_shared<int>(42);
std::weak_ptr w{p}; // explicit deduction guide is used in this case
}
```
cpp std::weak_ptr<T>::expired std::weak\_ptr<T>::expired
==========================
| | | |
| --- | --- | --- |
|
```
bool expired() const noexcept;
```
| | (since C++11) |
Equivalent to `use_count() == 0`. The destructor for the managed object may not yet have been called, but this object's destruction is imminent (or may have already happened).
### Parameters
(none).
### Return value
`true` if the managed object has already been deleted, `false` otherwise.
### Notes
This function is inherently racy if the managed object is shared among threads. In particular, a false result may become stale before it can be used. A true result is reliable.
### Example
Demonstrates how expired is used to check validity of the pointer.
```
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
if (!gw.expired()) {
std::cout << "gw is valid\n";
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
```
Output:
```
gw is valid
gw is expired
```
### See also
| | |
| --- | --- |
| [lock](lock "cpp/memory/weak ptr/lock") | creates a `shared_ptr` that manages the referenced object (public member function) |
| [use\_count](use_count "cpp/memory/weak ptr/use count") | returns the number of `shared_ptr` objects that manage the object (public member function) |
cpp std::weak_ptr<T>::swap std::weak\_ptr<T>::swap
=======================
| | | |
| --- | --- | --- |
|
```
void swap( weak_ptr& r ) noexcept;
```
| | (since C++11) |
Exchanges the stored pointer values and the ownerships of `*this` and `r`. Reference counts, if any, are not adjusted.
### Parameters
| | | |
| --- | --- | --- |
| r | - | smart pointer to exchange the contents with |
### Return value
(none).
### Example
```
#include <iostream>
#include <memory>
#include <string>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::shared_ptr<Foo> sp1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> sp2 = std::make_shared<Foo>(200);
std::weak_ptr<Foo> wp1 = sp1;
std::weak_ptr<Foo> wp2 = sp2;
auto print = [&]() {
auto p1 = wp1.lock();
auto p2 = wp2.lock();
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
wp1.swap(wp2);
print();
wp1.reset();
print();
wp1.swap(wp2);
print();
}
```
Output:
```
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
~Foo...
```
cpp std::weak_ptr<T>::weak_ptr std::weak\_ptr<T>::weak\_ptr
============================
| | | |
| --- | --- | --- |
|
```
constexpr weak_ptr() noexcept;
```
| (1) | (since C++11) |
|
```
weak_ptr( const weak_ptr& r ) noexcept;
```
| (2) | (since C++11) |
|
```
template< class Y >
weak_ptr( const weak_ptr<Y>& r ) noexcept;
```
| (2) | (since C++11) |
|
```
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r ) noexcept;
```
| (2) | (since C++11) |
|
```
weak_ptr( weak_ptr&& r ) noexcept;
```
| (3) | (since C++11) |
|
```
template< class Y >
weak_ptr( weak_ptr<Y>&& r ) noexcept;
```
| (3) | (since C++11) |
Constructs new `weak_ptr` that potentially shares an object with `r`.
1) Default constructor. Constructs empty `weak_ptr`.
2) Constructs new `weak_ptr` which shares an object managed by `r`. If `r` manages no object, `*this` manages no object too. The templated overloads don't participate in the overload resolution unless `Y*` is implicitly convertible to `T*`, or `Y` is the type "array of `N` `U`" for some type `U` and some number `N`, and `T` is the type "array of unknown bound of (possibly cv-qualified) `U`" (since C++17).
3) Move constructors. Moves a weak\_ptr instance from `r` into `*this`. After this, `r` is empty and `r.use_count()==0`. The templated overload doesn't participate in the overload resolution unless `Y*` is implicitly convertible to `T*`. ### Parameters
| | | |
| --- | --- | --- |
| r | - | a `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` or `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` that will be viewed by this `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")`. |
### Notes
Because the default constructor is `constexpr`, static `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")`s are initialized as part of [static non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization"), before any dynamic non-local initialization begins. This makes it safe to use a `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` in a constructor of any static object.
### Example
```
#include <memory>
#include <iostream>
struct Foo {};
int main()
{
std::weak_ptr<Foo> w_ptr;
{
auto ptr = std::make_shared<Foo>();
w_ptr = ptr;
std::cout << "w_ptr.use_count() inside scope: " << w_ptr.use_count() << '\n';
}
std::cout << "w_ptr.use_count() out of scope: " << w_ptr.use_count() << '\n';
std::cout << "w_ptr.expired() out of scope: " << std::boolalpha << w_ptr.expired() << '\n';
}
```
Output:
```
w_ptr.use_count() inside scope: 1
w_ptr.use_count() out of scope: 0
w_ptr.expired() out of scope: true
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2315](https://cplusplus.github.io/LWG/issue2315) | C++11 | move semantic was not enabled for `weak_ptr` | enabled |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/memory/weak ptr/operator=") | assigns the `weak_ptr` (public member function) |
cpp std::weak_ptr<T>::~weak_ptr std::weak\_ptr<T>::~weak\_ptr
=============================
| | | |
| --- | --- | --- |
|
```
~weak_ptr();
```
| | (since C++11) |
Destroys the `weak_ptr` object. Results in no effect to the managed object.
### Example
The program shows the effect of "non-breaking" the cycle of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")`s.
```
#include <iostream>
#include <memory>
#include <variant>
class Node {
char id;
std::variant<std::weak_ptr<Node>, std::shared_ptr<Node>> ptr;
public:
Node(char id) : id{id} {}
~Node() { std::cout << " '" << id << "' reclaimed\n"; }
/*...*/
void assign(std::weak_ptr<Node> p) { ptr = p; }
void assign(std::shared_ptr<Node> p) { ptr = p; }
};
enum class shared { all, some };
void test_cyclic_graph(const shared x) {
auto A = std::make_shared<Node>('A');
auto B = std::make_shared<Node>('B');
auto C = std::make_shared<Node>('C');
A->assign(B);
B->assign(C);
if (shared::all == x) {
C->assign(A);
std::cout << "All links are shared pointers";
} else {
C->assign(std::weak_ptr<Node>(A));
std::cout << "One link is a weak_ptr";
}
/*...*/
std::cout << "\nLeaving...\n";
}
int main() {
test_cyclic_graph(shared::some);
test_cyclic_graph(shared::all); // produces a memory leak
}
```
Output:
```
One link is a weak_ptr
Leaving...
'A' reclaimed
'B' reclaimed
'C' reclaimed
All links are shared pointers
Leaving...
```
### See also
| | |
| --- | --- |
| [(destructor)](../shared_ptr/~shared_ptr "cpp/memory/shared ptr/~shared ptr") | destructs the owned object if no more `shared_ptr`s link to it (public member function of `std::shared_ptr<T>`) |
cpp std::swap(std::weak_ptr)
std::swap(std::weak\_ptr)
=========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
void swap( std::weak_ptr<T>& lhs, std::weak_ptr<T>& rhs ) noexcept;
```
| | (since C++11) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | smart pointers whose contents to swap |
### Return value
(none).
### Complexity
Constant.
### Example
```
#include <iostream>
#include <memory>
#include <string>
struct Foo {
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::shared_ptr<Foo> sp1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> sp2 = std::make_shared<Foo>(200);
std::weak_ptr<Foo> wp1 = sp1;
std::weak_ptr<Foo> wp2 = sp2;
auto print = [&]() {
auto p1 = wp1.lock();
auto p2 = wp2.lock();
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
std::swap(wp1, wp2);
print();
wp1.reset();
print();
std::swap(wp1, wp2);
print();
}
```
Output:
```
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
~Foo...
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap](swap "cpp/memory/weak ptr/swap") | swaps the contents (public member function) |
cpp std::atomic(std::weak_ptr)
std::atomic(std::weak\_ptr)
===========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template <class T> struct std::atomic<std::weak_ptr<T>>;
```
| | (since C++20) |
The partial template specialization of `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` for `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` allows users to manipulate weak\_ptr objects atomically.
If multiple threads of execution access the same `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` object without synchronization and any of those accesses uses a non-const member function of `weak_ptr` then a data race will occur unless all such access is performed through an instance of `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)>`.
Associated `use_count` increments are guaranteed to be part of the atomic operation. Associated `use_count` decrements are sequenced after the atomic operation, but are not required to be part of it, except for the `use_count` change when overriding `expected` in a failed CAS. Any associated deletion and deallocation are sequenced after the atomic update step and are not part of the atomic operation.
Note that the control block used by `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` and `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` is thread-safe: different non-atomic `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` objects can be accessed using mutable operations, such as `operator=` or `reset`, simultaneously by multiple threads, even when these instances are copies or otherwise share the same control block internally.
The type `T` may be an incomplete type.
### Member types
| Member type | Definition |
| --- | --- |
| `value_type` | `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` |
### Member functions
All non-specialized `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` functions are also provided by this specialization, and no additional member functions.
atomic<weak\_ptr<T>>::atomic
-----------------------------
| | | |
| --- | --- | --- |
|
```
constexpr atomic() noexcept = default;
```
| (1) | |
|
```
atomic(std::weak_ptr<T> desired) noexcept;
```
| (2) | |
|
```
atomic(const atomic&) = delete;
```
| (3) | |
1) Initializes the underlying `weak_ptr<T>` to default-constructed value.
2) Initializes the underlying `weak_ptr<T>` to a copy of `desired`. As with any `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` type, initialization is not an atomic operation.
3) Atomic types are not copy/move constructible.
atomic<weak\_ptr<T>>::operator=
--------------------------------
| | | |
| --- | --- | --- |
|
```
void operator=(const atomic&) = delete;
```
| (1) | |
|
```
void operator=(std::weak_ptr<T> desired) noexcept;
```
| (2) | |
1) Atomic types are not copy/move assignable.
2) Value assignment, equivalent to `store(desired)`.
atomic<weak\_ptr<T>>::is\_lock\_free
-------------------------------------
| | | |
| --- | --- | --- |
|
```
bool is_lock_free() const noexcept;
```
| | |
Returns true if the atomic operations on all objects of this type are lock-free, false otherwise.
atomic<weak\_ptr<T>>::store
----------------------------
| | | |
| --- | --- | --- |
|
```
void store(std::weak_ptr<T> desired,
std::memory_order order = std::memory_order_seq_cst) noexcept;
```
| | |
Atomically replaces the value of `*this` with the value of `desired` as if by `p.swap(desired)` where `p` is the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>`. Memory is ordered according to `order`. The behavior is undefined if `order` is `[std::memory\_order\_consume](../../atomic/memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_acquire](../../atomic/memory_order "cpp/atomic/memory order")`, or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`.
atomic<weak\_ptr<T>>::load
---------------------------
| | | |
| --- | --- | --- |
|
```
std::weak_ptr<T> load(std::memory_order order = std::memory_order_seq_cst) const noexcept;
```
| | |
Atomically returns a copy of the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>`. Memory is ordered according to `order`. The behavior is undefined if `order` is `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`.
atomic<weak\_ptr<T>>::operator std::weak\_ptr<T>
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
operator std::weak_ptr<T>() const noexcept;
```
| | |
Equivalent to `return load();`
atomic<weak\_ptr<T>>::exchange
-------------------------------
| | | |
| --- | --- | --- |
|
```
std::weak_ptr<T> exchange(std::weak_ptr<T> desired,
std::memory_order order = std::memory_order_seq_cst) noexcept;
```
| | |
Atomically replaces the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` with `desired` as if by `p.swap(desired)` where `p` is the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>`, and returns a copy of the value that `p` had immediately before the swap. Memory is ordered according to `order`. This is an atomic read-modify-write operation.
atomic<weak\_ptr<T>>::compare\_exchange\_weak, compare\_exchange\_strong
-------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
bool compare_exchange_strong(std::weak_ptr<T>& expected, std::weak_ptr<T> desired,
std::memory_order success, std::memory_order failure) noexcept;
```
| (1) | |
|
```
bool compare_exchange_weak(std::weak_ptr<T>& expected, std::weak_ptr<T> desired,
std::memory_order success, std::memory_order failure) noexcept;
```
| (2) | |
|
```
bool compare_exchange_strong(std::weak_ptr<T>& expected, std::weak_ptr<T> desired,
std::memory_order order = std::memory_order_seq_cst) noexcept;
```
| (3) | |
|
```
bool compare_exchange_weak(std::weak_ptr<T>& expected, std::weak_ptr<T> desired,
std::memory_order order = std::memory_order_seq_cst) noexcept;
```
| (4) | |
1) If the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` stores the same pointer value as `expected` and shares ownership with it, or if both underlying and `expected` are empty, assigns from `desired` to the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>`, returns `true`, and orders memory according to `success`, otherwise assigns from the underlying `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>` to `expected`, returns `false`, and orders memory according to `failure`. The behavior is undefined if `failure` is `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`. On success, the operation is an atomic read-modify-write operation on `*this` and `expected` is not accessed after the atomic update. On failure, the operation is an atomic load operation on `*this` and `expected` is updated with the existing value read from the atomic object. This update to `expected`'s use\_count is part of this atomic operation, although the write itself (and any subsequent deallocation/destruction) is not required to be.
2) Same as (1), but may also fail spuriously.
3) Equivalent to: `return compare_exchange_strong(expected, desired, order, fail_order);`, where `fail_order` is the same as `order` except that `std:memory_order_acq_rel` is replaced by `[std::memory\_order\_acquire](../../atomic/memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` is replaced by `[std::memory\_order\_relaxed](../../atomic/memory_order "cpp/atomic/memory order")`.
4) Equivalent to: `return compare_exchange_weak(expected, desired, order, fail_order);` where `fail_order` is the same as `order` except that `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")` is replaced by `[std::memory\_order\_acquire](../../atomic/memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` is replaced by `[std::memory\_order\_relaxed](../../atomic/memory_order "cpp/atomic/memory order")`.
atomic<weak\_ptr<T>>::wait
---------------------------
| | | |
| --- | --- | --- |
|
```
void wait(std::weak_ptr<T> old
std::memory_order order = std::memory_order_seq_cst) const noexcept;
```
| | |
Performs an atomic waiting operation.
Compares `load(order)` with `old` and if they are equivalent then blocks until `*this` is notified by `notify_one()` or `notify_all()`. This is repeated until `load(order)` changes. This function is guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously.
Memory is ordered according to `order`. The behavior is undefined if `order` is `[std::memory\_order\_release](../../atomic/memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../../atomic/memory_order "cpp/atomic/memory order")`.
Notes: two `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")`s are equivalent if they store the same pointer and either share ownership or are both empty.
atomic<weak\_ptr<T>>::notify\_one
----------------------------------
| | | |
| --- | --- | --- |
|
```
void notify_one() noexcept;
```
| | |
Performs an atomic notifying operation.
If there is a thread blocked in atomic waiting operations (i.e. `wait()`) on `*this`, then unblocks at least one such thread; otherwise does nothing.
atomic<weak\_ptr<T>>::notify\_all
----------------------------------
| | | |
| --- | --- | --- |
|
```
void notify_all() noexcept;
```
| | |
Performs an atomic notifying operation.
Unblocks all threads blocked in atomic waiting operations (i.e. `wait()`) on `*this`, if there are any; otherwise does nothing.
### Member constants
The only standard `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` member constant `is_always_lock_free` is also provided by this specialization.
atomic<weak\_ptr<T>>::is\_always\_lock\_free
---------------------------------------------
| | | |
| --- | --- | --- |
|
```
static constexpr bool is_always_lock_free = /*implementation-defined*/;
```
| | |
### Example
### See also
| | |
| --- | --- |
| [atomic](../../atomic/atomic "cpp/atomic/atomic")
(C++11) | atomic class template and specializations for bool, integral, and pointer types (class template) |
| programming_docs |
cpp std::weak_ptr<T>::operator= std::weak\_ptr<T>::operator=
============================
| | | |
| --- | --- | --- |
|
```
weak_ptr& operator=( const weak_ptr& r ) noexcept;
```
| (1) | (since C++11) |
|
```
template< class Y >
weak_ptr& operator=( const weak_ptr<Y>& r ) noexcept;
```
| (2) | (since C++11) |
|
```
template< class Y >
weak_ptr& operator=( const shared_ptr<Y>& r ) noexcept;
```
| (3) | (since C++11) |
|
```
weak_ptr& operator=( weak_ptr&& r ) noexcept;
```
| (4) | (since C++11) |
|
```
template< class Y >
weak_ptr& operator=( weak_ptr<Y>&& r ) noexcept;
```
| (5) | (since C++11) |
Replaces the managed object with the one managed by `r`. The object is shared with `r`. If `r` manages no object, `*this` manages no object too.
1-3) Equivalent to `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>(r).swap(\*this)`.
4,5) Equivalent to `[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<T>(std::move(r)).swap(\*this)`. ### Parameters
| | | |
| --- | --- | --- |
| r | - | smart pointer to share an object with |
### Return value
`*this`.
### Notes
The implementation may meet the requirements without creating a temporary `weak_ptr` object.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2315](https://cplusplus.github.io/LWG/issue2315) | C++11 | move semantic was not enabled for `weak_ptr` | enabled |
### See also
| | |
| --- | --- |
| [(constructor)](weak_ptr "cpp/memory/weak ptr/weak ptr") | creates a new `weak_ptr` (public member function) |
| [swap](swap "cpp/memory/weak ptr/swap") | swaps the managed objects (public member function) |
cpp std::weak_ptr<T>::lock std::weak\_ptr<T>::lock
=======================
| | | |
| --- | --- | --- |
|
```
std::shared_ptr<T> lock() const noexcept;
```
| | (since C++11) |
Creates a new `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` that shares ownership of the managed object. If there is no managed object, i.e. `*this` is empty, then the returned `shared_ptr` also is empty.
Effectively returns `expired() ? shared_ptr<T>() : shared_ptr<T>(*this)`, executed atomically.
### Parameters
(none).
### Return value
A `shared_ptr` which shares ownership of the owned object if `[std::weak\_ptr::expired](expired "cpp/memory/weak ptr/expired")` returns `false`. Else returns default-constructed `shared_ptr` of type T.
### Notes
Both this function and the constructor of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` may be used to acquire temporary ownership of the managed object referred to by a `std::weak_ptr`. The difference is that the constructor of `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` throws an exception when its `std::weak_ptr` argument is empty, while `std::weak_ptr<T>::lock()` constructs an empty `std::shared_ptr<T>`.
### Example
```
#include <iostream>
#include <memory>
void observe(std::weak_ptr<int> weak)
{
if (auto observe = weak.lock()) {
std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *observe << "\n";
} else {
std::cout << "\tobserve() unable to lock weak_ptr<>\n";
}
}
int main()
{
std::weak_ptr<int> weak;
std::cout << "weak_ptr<> not yet initialized\n";
observe(weak);
{
auto shared = std::make_shared<int>(42);
weak = shared;
std::cout << "weak_ptr<> initialized with shared_ptr.\n";
observe(weak);
}
std::cout << "shared_ptr<> has been destructed due to scope exit.\n";
observe(weak);
}
```
Output:
```
weak_ptr<> not yet initialized
observe() unable to lock weak_ptr<>
weak_ptr<> initialized with shared_ptr.
observe() able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit.
observe() unable to lock weak_ptr<>
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2316](https://cplusplus.github.io/LWG/issue2316) | C++11 | lock() was not required to be atomic, but required to be noexcept, which led to a contradiction | specified to be atomic |
### See also
| | |
| --- | --- |
| [expired](expired "cpp/memory/weak ptr/expired") | checks whether the referenced object was already deleted (public member function) |
cpp std::weak_ptr<T>::use_count std::weak\_ptr<T>::use\_count
=============================
| | | |
| --- | --- | --- |
|
```
long use_count() const noexcept;
```
| | (since C++11) |
Returns the number of `shared_ptr` instances that share ownership of the managed object, or `0` if the managed object has already been deleted, i.e. `*this` is empty.
### Parameters
(none).
### Return value
The number of `shared_ptr` instances sharing the ownership of the managed object at the instant of the call.
### Notes
`[expired()](expired "cpp/memory/weak ptr/expired")` may be faster than `use_count()`. This function is inherently racy, if the managed object is shared among threads that might be creating and destroying copies of the `shared_ptr`: then, the result is reliable only if it matches the number of copies uniquely owned by the calling thread, or zero; any other value may become stale before it can be used.
### Example
```
#include <iostream>
#include <memory>
std::weak_ptr<int> gwp;
void observe_gwp() {
std::cout << "use_count(): " << gwp.use_count() << "\t id: ";
if (auto sp = gwp.lock())
std::cout << *sp << '\n';
else
std::cout << "??\n";
}
void share_recursively(std::shared_ptr<int> sp, int depth) {
observe_gwp(); // : 2 3 4
if (1 < depth)
share_recursively(sp, depth - 1);
observe_gwp(); // : 4 3 2
}
int main() {
observe_gwp();
{
auto sp = std::make_shared<int>(42);
gwp = sp;
observe_gwp(); // : 1
share_recursively(sp, 3); // : 2 3 4 4 3 2
observe_gwp(); // : 1
}
observe_gwp(); // : 0
}
```
Output:
```
use_count(): 0 id: ??
use_count(): 1 id: 42
use_count(): 2 id: 42
use_count(): 3 id: 42
use_count(): 4 id: 42
use_count(): 4 id: 42
use_count(): 3 id: 42
use_count(): 2 id: 42
use_count(): 1 id: 42
use_count(): 0 id: ??
```
### See also
| | |
| --- | --- |
| [expired](expired "cpp/memory/weak ptr/expired") | checks whether the referenced object was already deleted (public member function) |
cpp std::weak_ptr<T>::owner_before std::weak\_ptr<T>::owner\_before
================================
| | | |
| --- | --- | --- |
|
```
template< class Y >
bool owner_before( const weak_ptr<Y>& other ) const noexcept;
```
| | |
|
```
template< class Y >
bool owner_before( const std::shared_ptr<Y>& other ) const noexcept;
```
| | |
Checks whether this `weak_ptr` precedes `other` in implementation defined owner-based (as opposed to value-based) order. The order is such that two smart pointers compare equivalent only if they are both empty or if they both own the same object, even if the values of the pointers obtained by `get()` are different (e.g. because they point at different subobjects within the same object).
This ordering is used to make shared and weak pointers usable as keys in associative containers, typically through `[std::owner\_less](../owner_less "cpp/memory/owner less")`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | the `[std::shared\_ptr](../shared_ptr "cpp/memory/shared ptr")` or `[std::weak\_ptr](../weak_ptr "cpp/memory/weak ptr")` to be compared |
### Return value
`true` if `*this` precedes `other`, `false` otherwise. Common implementations compare the addresses of the control blocks.
### Example
```
#include <iostream>
#include <memory>
struct Foo {
int n1;
int n2;
Foo(int a, int b) : n1(a), n2(b) {}
};
int main()
{
auto p1 = std::make_shared<Foo>(1, 2);
std::shared_ptr<int> p2(p1, &p1->n1);
std::shared_ptr<int> p3(p1, &p1->n2);
std::cout << std::boolalpha
<< "p2 < p3 " << (p2 < p3) << '\n'
<< "p3 < p2 " << (p3 < p2) << '\n'
<< "p2.owner_before(p3) " << p2.owner_before(p3) << '\n'
<< "p3.owner_before(p2) " << p3.owner_before(p2) << '\n';
std::weak_ptr<int> w2(p2);
std::weak_ptr<int> w3(p3);
std::cout
// << "w2 < w3 " << (w2 < w3) << '\n' // won't compile
// << "w3 < w2 " << (w3 < w2) << '\n' // won't compile
<< "w2.owner_before(w3) " << w2.owner_before(w3) << '\n'
<< "w3.owner_before(w2) " << w3.owner_before(w2) << '\n';
}
```
Output:
```
p2 < p3 true
p3 < p2 false
p2.owner_before(p3) false
p3.owner_before(p2) false
w2.owner_before(w3) false
w3.owner_before(w2) false
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2873](https://cplusplus.github.io/LWG/issue2873) | C++11 | `owner_before` might not be declared noexcept | declared noexcept |
| [LWG 2942](https://cplusplus.github.io/LWG/issue2942) | C++11 | `weak_ptr::owner_before` is missed in LWG 2873's resolution | made noexcept |
### See also
| | |
| --- | --- |
| [owner\_less](../owner_less "cpp/memory/owner less")
(C++11) | provides mixed-type owner-based ordering of shared and weak pointers (class template) |
cpp std::pointer_traits<Ptr>::to_address std::pointer\_traits<Ptr>::to\_address
======================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
static element_type* to_address(pointer p) noexcept;
```
| | (since C++20) (optional member of program-defined specialization) |
Constructs a raw pointer that references the same object as its pointer-like ("fancy pointer") argument.
This function, if defined, is the inverse of [`pointer_to`](pointer_to "cpp/memory/pointer traits/pointer to"), and exists as the customization point to be called by [`std::to_address`](../to_address "cpp/memory/to address").
### Parameters
| | | |
| --- | --- | --- |
| p | - | fancy pointer/pointer-like object |
### Return value
A raw pointer of the type `element_type*` that references the same memory location as the argument `p`.
### See also
| | |
| --- | --- |
| [pointer\_to](pointer_to "cpp/memory/pointer traits/pointer to")
[static] | obtains a dereferenceable pointer to its argument (public static member function) |
| [to\_address](../to_address "cpp/memory/to address")
(C++20) | obtains a raw pointer from a pointer-like type (function template) |
cpp std::pointer_traits<Ptr>::pointer_to std::pointer\_traits<Ptr>::pointer\_to
======================================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
static pointer
pointer_to( element_type& r );
```
| (1) | (since C++11) (member of `pointer_traits<Ptr>` specialization) |
| | (2) | |
|
```
static pointer
pointer_to( element_type& r ) noexcept;
```
| (since C++11) (until C++20) (member of `pointer_traits<T*>` specialization) |
|
```
static constexpr pointer
pointer_to( element_type& r ) noexcept;
```
| (since C++20) (member of `pointer_traits<T*>` specialization) |
Constructs a dereferenceable pointer or pointer-like object ("fancy pointer") to its argument.
1) The version of this function in the non-specialized `[std::pointer\_traits](../pointer_traits "cpp/memory/pointer traits")` template simply calls `Ptr::pointer_to(r)`, and if Ptr does not provide a static member function `pointer_to`, instantiation of this function is a compile-time error.
2) The version of this function in the specialization of `[std::pointer\_traits](../pointer_traits "cpp/memory/pointer traits")` for pointer types returns `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(r)`
### Parameters
| | | |
| --- | --- | --- |
| r | - | reference to an object of type `element_type&`, except if element\_type is `void`, in which case the type of `r` is unspecified |
### Return value
A dereferenceable pointer to `r`, of the type pointer\_traits<>::pointer.
### Exceptions
1) Unspecified (typically same as `Ptr::pointer_to`) ### Notes
The [Boost.Intrusive library version](http://www.boost.org/doc/libs/release/doc/html/boost/intrusive/pointer_traits.html) of this function returns `pointer([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(r))` if Ptr::pointer\_to does not exist.
### See also
| | |
| --- | --- |
| [addressof](../addressof "cpp/memory/addressof")
(C++11) | obtains actual address of an object, even if the *&* operator is overloaded (function template) |
| [address](../allocator/address "cpp/memory/allocator/address")
(until C++20) | obtains the address of an object, even if `operator&` is overloaded (public member function of `std::allocator<T>`) |
| [to\_address](to_address "cpp/memory/pointer traits/to address")
[static] (C++20)(optional) | obtains a raw pointer from a fancy pointer (inverse of `pointer_to`) (public static member function) |
| [to\_address](../to_address "cpp/memory/to address")
(C++20) | obtains a raw pointer from a pointer-like type (function template) |
cpp std::destroying_delete_t, std::destroying_delete std::destroying\_delete\_t, std::destroying\_delete
===================================================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
struct destroying_delete_t { explicit destroying_delete_t() = default; };
```
| | (since C++20) |
|
```
inline constexpr destroying_delete_t destroying_delete{};
```
| | (since C++20) |
Tag type used to identify the destroying delete form of [`operator delete`](operator_delete "cpp/memory/new/operator delete").
### See also
| | |
| --- | --- |
| [operator deleteoperator delete[]](operator_delete "cpp/memory/new/operator delete") | deallocation functions (function) |
cpp std::bad_array_new_length std::bad\_array\_new\_length
============================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
class bad_array_new_length;
```
| | (since C++11) |
`std::bad_array_new_length` is the type of the object thrown as exceptions by the [new-expressions](../../language/new "cpp/language/new") to report invalid array lengths if.
1) array length is negative.
2) total size of the new array would exceed implementation-defined maximum value.
3) the number of initializer-clauses exceeds the number of elements to initialize.
Only the first array dimension may generate this exception; dimensions other than the first are constant expressions and are checked at compile time.
![std-bad array new length-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs a new `bad_array_new_length` object (public member function) |
| operator= | replaces the `bad_array_new_length` object (public member function) |
| what | returns the explanatory string (public member function) |
std::bad\_array\_new\_length::bad\_array\_new\_length
------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
bad_array_new_length() noexcept;
```
| (1) | (since C++11) |
|
```
bad_array_new_length( const bad_array_new_length& other ) noexcept;
```
| (2) | (since C++11) |
Constructs a new `bad_array_new_length` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what").
1) Default constructor.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_array_new_length` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to copy |
std::bad\_array\_new\_length::operator=
----------------------------------------
| | | |
| --- | --- | --- |
|
```
bad_array_new_length& operator=( const bad_array_new_length& other ) noexcept;
```
| | (since C++11) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_array_new_length` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::bad\_array\_new\_length::what
-----------------------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const noexcept;
```
| | (since C++11) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")
------------------------------------------------------------------------
Inherited from [std::exception](../../error/exception "cpp/error/exception")
------------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
### Example
Three conditions where `std::bad_array_new_length` should be thrown:
```
#include <iostream>
#include <new>
#include <climits>
int main()
{
try {
int negative = -1;
new int[negative];
} catch(const std::bad_array_new_length &e) {
std::cout << "1) " << e.what() << ": negative size\n";
}
try {
int small = 1;
new int[small]{1,2,3};
} catch(const std::bad_array_new_length &e) {
std::cout << "2) " << e.what() << ": too many initializers\n";
}
try {
long large = LONG_MAX;
new int[large][1000];
} catch(const std::bad_array_new_length &e) {
std::cout << "3) " << e.what() << ": too large\n";
}
std::cout << "End\n";
}
```
Possible output:
```
1) std::bad_array_new_length: negative size
2) std::bad_array_new_length: too many initializers
3) std::bad_array_new_length: too large
End
```
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [bad\_alloc](bad_alloc "cpp/memory/new/bad alloc") | exception thrown when memory allocation fails (class) |
cpp std::nothrow std::nothrow
============
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
struct nothrow_t {};
```
| | (until C++11) |
|
```
struct nothrow_t { explicit nothrow_t() = default; };
```
| | (since C++11) |
|
```
extern const std::nothrow_t nothrow;
```
| | |
`std::nothrow_t` is an empty class type used to disambiguate the overloads of throwing and non-throwing [allocation functions](operator_new "cpp/memory/new/operator new"). `std::nothrow` is a constant of it.
### Example
```
#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul]; // throwing overload
}
} catch (const std::bad_alloc& e) {
std::cout << e.what() << '\n';
}
while (true) {
int* p = new(std::nothrow) int[100000000ul]; // non-throwing overload
if (p == nullptr) {
std::cout << "Allocation returned nullptr\n";
break;
}
}
}
```
Output:
```
std::bad_alloc
Allocation returned nullptr
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | the default constructor was non-explicit, which could lead to ambiguity | made explicit |
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| programming_docs |
cpp operator delete, operator delete[] operator delete, operator delete[]
==================================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
| replaceable usual deallocation functions | | |
| | (1) | |
|
```
void operator delete ( void* ptr ) throw();
```
| (until C++11) |
|
```
void operator delete ( void* ptr ) noexcept;
```
| (since C++11) |
| | (2) | |
|
```
void operator delete[]( void* ptr ) throw();
```
| (until C++11) |
|
```
void operator delete[]( void* ptr ) noexcept;
```
| (since C++11) |
|
```
void operator delete ( void* ptr, std::align_val_t al ) noexcept;
```
| (3) | (since C++17) |
|
```
void operator delete[]( void* ptr, std::align_val_t al ) noexcept;
```
| (4) | (since C++17) |
|
```
void operator delete ( void* ptr, std::size_t sz ) noexcept;
```
| (5) | (since C++14) |
|
```
void operator delete[]( void* ptr, std::size_t sz ) noexcept;
```
| (6) | (since C++14) |
|
```
void operator delete ( void* ptr, std::size_t sz,
std::align_val_t al ) noexcept;
```
| (7) | (since C++17) |
|
```
void operator delete[]( void* ptr, std::size_t sz,
std::align_val_t al ) noexcept;
```
| (8) | (since C++17) |
| replaceable placement deallocation functions | | |
| | (9) | |
|
```
void operator delete ( void* ptr, const std::nothrow_t& tag ) throw();
```
| (until C++11) |
|
```
void operator delete ( void* ptr, const std::nothrow_t& tag ) noexcept;
```
| (since C++11) |
| | (10) | |
|
```
void operator delete[]( void* ptr, const std::nothrow_t& tag ) throw();
```
| (until C++11) |
|
```
void operator delete[]( void* ptr, const std::nothrow_t& tag ) noexcept;
```
| (since C++11) |
|
```
void operator delete ( void* ptr, std::align_val_t al,
const std::nothrow_t& tag ) noexcept;
```
| (11) | (since C++17) |
|
```
void operator delete[]( void* ptr, std::align_val_t al,
const std::nothrow_t& tag ) noexcept;
```
| (12) | (since C++17) |
| non-allocating placement deallocation functions | | |
| | (13) | |
|
```
void operator delete ( void* ptr, void* place ) throw();
```
| (until C++11) |
|
```
void operator delete ( void* ptr, void* place ) noexcept;
```
| (since C++11) |
| | (14) | |
|
```
void operator delete[]( void* ptr, void* place ) throw();
```
| (until C++11) |
|
```
void operator delete[]( void* ptr, void* place ) noexcept;
```
| (since C++11) |
| user-defined placement deallocation functions | | |
|
```
void operator delete ( void* ptr, args... );
```
| (15) | |
|
```
void operator delete[]( void* ptr, args... );
```
| (16) | |
| class-specific usual deallocation functions | | |
|
```
void T::operator delete ( void* ptr );
```
| (17) | |
|
```
void T::operator delete[]( void* ptr );
```
| (18) | |
|
```
void T::operator delete ( void* ptr, std::align_val_t al );
```
| (19) | (since C++17) |
|
```
void T::operator delete[]( void* ptr, std::align_val_t al );
```
| (20) | (since C++17) |
|
```
void T::operator delete ( void* ptr, std::size_t sz );
```
| (21) | |
|
```
void T::operator delete[]( void* ptr, std::size_t sz );
```
| (22) | |
|
```
void T::operator delete ( void* ptr, std::size_t sz, std::align_val_t al );
```
| (23) | (since C++17) |
|
```
void T::operator delete[]( void* ptr, std::size_t sz, std::align_val_t al );
```
| (24) | (since C++17) |
| class-specific placement deallocation functions | | |
|
```
void T::operator delete ( void* ptr, args... );
```
| (25) | |
|
```
void T::operator delete[]( void* ptr, args... );
```
| (26) | |
| class-specific usual destroying deallocation functions | | |
|
```
void T::operator delete( T* ptr, std::destroying_delete_t );
```
| (27) | (since C++20) |
|
```
void T::operator delete( T* ptr, std::destroying_delete_t,
std::align_val_t al );
```
| (28) | (since C++20) |
|
```
void T::operator delete( T* ptr, std::destroying_delete_t, std::size_t sz );
```
| (29) | (since C++20) |
|
```
void T::operator delete( T* ptr, std::destroying_delete_t,
std::size_t sz, std::align_val_t al );
```
| (30) | (since C++20) |
Deallocates storage previously allocated by a matching `[operator new](operator_new "cpp/memory/new/operator new")`. These deallocation functions are called by [delete-expressions](../../language/delete "cpp/language/delete") and by [new-expressions](../../language/new "cpp/language/new") to deallocate memory after destructing (or failing to construct) objects with dynamic storage duration. They may also be called using regular function call syntax.
1) Called by [delete-expressions](../../language/delete "cpp/language/delete") to deallocate storage previously allocated for a single object. The behavior of the standard library implementation of this function is undefined unless `ptr` is a null pointer or is a pointer previously obtained from the standard library implementation of `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)(size_t)` or `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)(size_t, [std::nothrow\_t](http://en.cppreference.com/w/cpp/memory/new/nothrow_t))`.
2) Called by [delete[]-expressions](../../language/delete "cpp/language/delete") to deallocate storage previously allocated for an array of objects. The behavior of the standard library implementation of this function is undefined unless `ptr` is a null pointer or is a pointer previously obtained from the standard library implementation of `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)[](size_t)` or `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)[](size_t, [std::nothrow\_t](http://en.cppreference.com/w/cpp/memory/new/nothrow_t))`.
3,4) Same as (1,2), except called if the alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
5-6) Called instead of (1-2) if a user-defined replacement is provided, except that it's unspecified whether (1-2) or (5-6) is called when deleting objects of incomplete type and arrays of non-class and trivially-destructible class types. A memory allocator can use the given size to be more efficient. The standard library implementations are identical to (1-2).
7-8) Same as (5-6), except called if the alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
9) Called by the non-throwing single-object [new-expressions](../../language/new "cpp/language/new") if a constructor of the object throws an exception. The standard library implementation behaves the same as (1)
10) Called by the non-throwing array [new[]-expressions](../../language/new "cpp/language/new") if a constructor of any object throws an exception (after executing the destructors of all objects in the array that were successfully constructed). The standard library implementation behaves the same as (2)
11,12) Same as (9,10), except called if the alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
13) Called by the standard single-object [placement new](../../language/new "cpp/language/new") expression if the object's constructor throws an exception. The standard library implementation of this function does nothing.
14) Called by the standard array form of the [placement new[]](../../language/new "cpp/language/new") expression if any of the objects' constructors throws an exception (after executing the destructors of all objects that were constructed successfully). The standard library implementation of this function does nothing.
15) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature if the object's constructor throws an exception. If a class-specific version (25) is defined, it is called in preference to (9). If neither (25) nor (15) is provided by the user, no deallocation function is called.
16) If defined, called by the custom array form of [placement new[]](../../language/new "cpp/language/new") expression with the matching signature if any of the objects' constructors throws an exception (after executing the destructors for all objects that were constructed successfully). If a class-specific version (16) is defined, it is called in preference to (10). If neither (26) nor (16) is provided by the user, no deallocation function is called
17) If defined, called by the usual single-object [delete-expressions](../../language/delete "cpp/language/delete") if deallocating an object of type `T`.
18) If defined, called by the usual array [delete[]-expressions](../../language/delete "cpp/language/delete") if deallocating an array of objects of type `T`.
19,20) If defined, called in preference to (17,18) if the alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`.
21) If defined, and if (17) is not defined, called by the usual single-object [delete-expressions](../../language/delete "cpp/language/delete") if deallocating an object of type `T`.
22) If defined, and if (18) is not defined, called by the usual array [delete[]-expressions](../../language/delete "cpp/language/delete") if deallocating an array of objects of type `T`.
23,24) If defined, and if (19,20) are not defined, called in preference to allocator-unaware members if the alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`.
25) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature if the object's constructor throws an exception. If this function is not provided, and a matching (15) is not provided either, no deallocation function is called.
26) If defined, called by the custom array form of [placement new[]](../../language/new "cpp/language/new") expression with the matching signature if any of the objects' constructors throws an exception (after executing the destructors for all objects that were constructed successfully). If this function is not provided, and a matching (16) is not provided either, no deallocation function is called.
27-30) If defined, [delete-expressions](../../language/delete "cpp/language/delete") does not execute the destructor for `*p` before placing a call to `operator delete`. Instead, direct invocation of the destructor such as by `p->~T();` becomes the responsibility of this user-defined operator delete.
| | |
| --- | --- |
| See [delete-expression](../../language/delete "cpp/language/delete") for exact details on the overload resolution rules between alignment-aware and alignment-unaware overloads of usual (non-placement) deallocation functions. | (since C++17) |
In all cases, if `ptr` is a null pointer, the standard library deallocation functions do nothing. If the pointer passed to the standard library deallocation function was not obtained from the corresponding standard library allocation function, the behavior is undefined.
After the standard library deallocation function returns, all pointers referring to any part of the deallocated storage become invalid.
Indirection through a pointer that became invalid in this manner and passing it to a deallocation function (double-delete) is undefined behavior. Any other use is implementation-defined.
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to a memory block to deallocate or a null pointer |
| sz | - | the size that was passed to the matching allocation function |
| place | - | pointer used as the placement parameter in the matching placement new |
| tag | - | overload disambiguation tag matching the tag used by non-throwing operator new |
| al | - | alignment of the object or array element that was allocated |
| args | - | arbitrary parameters matching a placement allocation function (may include `[std::size\_t](../../types/size_t "cpp/types/size t")` and `[std::align\_val\_t](align_val_t "cpp/memory/new/align val t")`) |
### Return value
(none).
### Exceptions
| | |
| --- | --- |
| All deallocation functions are `noexcept(true)` unless specified otherwise in the declaration. | (since C++11) |
If a deallocation function terminates by throwing an exception, the behavior is undefined, even if it is declared with `noexcept(false)` (since C++11).
### Global replacements
The replaceable deallocation functions (1-12) are implicitly declared in each translation unit even if the [`<new>`](../../header/new "cpp/header/new") header is not included. These functions are *replaceable*: a user-provided non-member function with the same signature defined anywhere in the program, in any source file, replaces the corresponding implicit version for the entire program. Its declaration does not need to be visible.
The program is ill-formed, no diagnostic required if more than one replacement is provided in the program or if a replacement is declared with the [`inline` specifier](../../language/inline "cpp/language/inline") . The program is ill-formed if a replacement is defined in namespace other than global namespace, or if it is defined as a static non-member function at global scope.
| | |
| --- | --- |
| The standard library implementations of the nothrow versions (9,10) directly call the corresponding throwing versions (1,2). The standard library implementations of the size-aware deallocation functions (5-8) directly call the corresponding size-unaware deallocation functions (1-4). The standard library implementations of size-unaware throwing array forms (2,4) directly calls the corresponding single-object forms (1,3).
Thus, replacing the throwing single object deallocation functions (1,3) is sufficient to handle all deallocations. | (since C++11) |
```
#include <cstdio>
#include <cstdlib>
#include <new>
// replacement of a minimal set of functions:
// no inline, required by [replacement.functions]/3
void* operator new(std::size_t sz)
{
std::printf("global op new called, size = %zu\n", sz);
if (sz == 0)
++sz; // avoid std::malloc(0) which may return nullptr on success
if (void *ptr = std::malloc(sz))
return ptr;
throw std::bad_alloc{}; // required by [new.delete.single]/3
}
void operator delete(void* ptr) noexcept
{
std::puts("global op delete called");
std::free(ptr);
}
int main()
{
int* p1 = new int;
delete p1;
int* p2 = new int[10]; // guaranteed to call the replacement in C++11
delete[] p2;
}
```
Possible output:
```
global op new called, size = 4
global op delete called
global op new called, size = 40
global op delete called
```
Overloads of `operator delete` and `operator delete[]` with additional user-defined parameters ("placement forms", (15,16)) may be declared at global scope as usual, and are called by the matching placement forms of *new-expressions* if a constructor of the object that is being allocated throws an exception.
The standard library placement forms of `operator delete` (13,14) cannot be replaced and can only be customized if the placement new-expression did not use the `::new` syntax, by providing a class-specific placement delete (25,26) with matching signature: `void T::operator delete(void*, void*)` or `void T::operator delete[](void*, void*)`.
### Class-specific overloads
Deallocation functions (17-24) may be defined as static member functions of a class. These deallocation functions, if provided, are called by [delete-expressions](../../language/delete "cpp/language/delete") when deleting objects (17,19,21) and arrays (18,20,22) of this class, unless the delete expression used the form `::delete` which bypasses class-scope lookup. The keyword `static` is optional for these function declarations: whether the keyword is used or not, the deallocation function is always a static member function.
The delete expression looks for appropriate deallocation function's name starting from the class scope (array form looks in the scope of the array element class) and proceeds to the global scope if no members are found as usual. Note, that as per [name lookup rules](../../language/lookup "cpp/language/lookup"), any deallocation functions declared in class scope hides all global deallocation functions.
If the static type of the object that is being deleted differs from its dynamic type (such as when deleting a [polymorphic](../../language/object "cpp/language/object") object through a pointer to base), and if the destructor in the static type is virtual, the single object form of delete begins lookup of the deallocation function's name starting from the point of definition of the final overrider of its virtual destructor. Regardless of which deallocation function would be executed at run time, the statically visible version of operator delete must be accessible in order to compile. In other cases, when deleting an array through a pointer to base, or when deleting through pointer to base with non-virtual destructor, the behavior is undefined.
If the single-argument overload (17,18) is not provided, but the size-aware overload taking `[std::size\_t](../../types/size_t "cpp/types/size t")` as the second parameter (21,22) is provided, the size-aware form is called for normal deallocation, and the C++ runtime passes the size of the object to be deallocated as the second argument. If both forms are defined, the size-unaware version is called.
```
#include <iostream>
// sized class-specific deallocation functions
struct X
{
static void operator delete(void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
::operator delete(ptr);
}
static void operator delete[](void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
::operator delete(ptr);
}
};
int main()
{
X* p1 = new X;
delete p1;
X* p2 = new X[10];
delete[] p2;
}
```
Possible output:
```
custom delete for size 1
custom delete for size 18
```
Overloads of `operator delete` and `operator delete[]` with additional user-defined parameters ("placement forms", (25,26)) may also be defined as class members. When the failed placement new expression looks for the corresponding placement delete function to call, it begins lookup at class scope before examining the global scope, and looks for the function with the signature matching the placement new:
```
#include <stdexcept>
#include <iostream>
struct X
{
X() { throw std::runtime_error(""); }
// custom placement new
static void* operator new(std::size_t sz, bool b)
{
std::cout << "custom placement new called, b = " << b << '\n';
return ::operator new(sz);
}
// custom placement delete
static void operator delete(void* ptr, bool b)
{
std::cout << "custom placement delete called, b = " << b << '\n';
::operator delete(ptr);
}
};
int main()
{
try
{
X* p1 = new (true) X;
}
catch (const std::exception&) {}
}
```
Output:
```
custom placement new called, b = 1
custom placement delete called, b = 1
```
If class-level `operator delete` is a template function, it must have the return type of `void`, the first argument `void*`, and it must have two or more parameters. In other words, only placement forms can be templates. A template instance is never a usual deallocation function, regardless of its signature. The specialization of the template operator delete is chosen with [template argument deduction](../../language/template_argument_deduction "cpp/language/template argument deduction").
### Notes
The call to the class-specific `T::operator delete` on a polymorphic class is the only case where a static member function is called through dynamic dispatch.
If the behavior of an deallocation function does not satisfy the default constraints , the behavior is undefined.
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](operator_new "cpp/memory/new/operator new") and **`operator delete`**
* User replacement versions of global [`operator new`](operator_new "cpp/memory/new/operator new") and **`operator delete`**
* `[std::calloc](../c/calloc "cpp/memory/c/calloc")`, `[std::malloc](../c/malloc "cpp/memory/c/malloc")`, `[std::realloc](../c/realloc "cpp/memory/c/realloc")`, `[std::aligned\_alloc](../c/aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `[std::free](../c/free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 220](https://cplusplus.github.io/CWG/issues/220.html) | C++98 | user-defined deallocation functions were permitted to throw | throwing from a deallocation functionresults in undefined behavior |
| [CWG 1438](https://cplusplus.github.io/CWG/issues/1438.html) | C++98 | any use of an invalid pointer value was undefined behavior | only indirection and deallocation are |
| [LWG 2458](https://cplusplus.github.io/LWG/issue2458) | C++14 | overloads taking (void\*,size\_t,const nothrow\_t&)were specified, but could never be called | spurious overloads removed |
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [return\_temporary\_buffer](../return_temporary_buffer "cpp/memory/return temporary buffer")
(deprecated in C++17)(removed in C++20) | frees uninitialized storage (function template) |
| [free](../c/free "cpp/memory/c/free") | deallocates previously allocated memory (function) |
| programming_docs |
cpp std::new_handler std::new\_handler
=================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
typedef void (*new_handler)();
```
| | |
`std::new_handler` is the function pointer type (pointer to function that takes no arguments and returns void), which is used by the functions `[std::set\_new\_handler](set_new_handler "cpp/memory/new/set new handler")` and `[std::get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")`.
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [set\_new\_handler](set_new_handler "cpp/memory/new/set new handler") | registers a new handler (function) |
| [get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")
(C++11) | obtains the current new handler (function) |
cpp std::align_val_t std::align\_val\_t
==================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
enum class align_val_t : std::size_t {};
```
| | (since C++17) |
Both [new-expression](../../language/new "cpp/language/new") and [delete-expression](../../language/delete "cpp/language/delete"), when used with objects whose alignment requirement is greater than `__STDCPP_DEFAULT_NEW_ALIGNMENT__`, pass that alignment requirement as an argument of type `std::align_val_t` to the selected allocation/deallocation function.
### Notes
Alignment (as obtained by `alignof`) has the type `[std::size\_t](../../types/size_t "cpp/types/size t")`, but placement forms of allocation and deallocation functions that take `[std::size\_t](../../types/size_t "cpp/types/size t")` as an additional parameter are already in use, so this type is used instead.
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [operator deleteoperator delete[]](operator_delete "cpp/memory/new/operator delete") | deallocation functions (function) |
cpp std::bad_alloc std::bad\_alloc
===============
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
class bad_alloc;
```
| | |
`std::bad_alloc` is the type of the object thrown as exceptions by the [allocation functions](operator_new "cpp/memory/new/operator new") to report failure to allocate storage.
![std-bad alloc-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs a new `bad_alloc` object (public member function) |
| operator= | replaces the `bad_alloc` object (public member function) |
| what | returns the explanatory string (public member function) |
std::bad\_alloc::bad\_alloc
----------------------------
| | | |
| --- | --- | --- |
| | (1) | |
|
```
bad_alloc() throw();
```
| (until C++11) |
|
```
bad_alloc() noexcept;
```
| (since C++11) |
| | (2) | |
|
```
bad_alloc( const bad_alloc& other ) throw();
```
| (until C++11) |
|
```
bad_alloc( const bad_alloc& other ) noexcept;
```
| (since C++11) |
Constructs a new `bad_alloc` object with an implementation-defined null-terminated byte string which is accessible through [`what()`](../../error/exception/what "cpp/error/exception/what").
1) Default constructor.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::bad_alloc` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11)
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to copy |
std::bad\_alloc::operator=
---------------------------
| | | |
| --- | --- | --- |
|
```
bad_alloc& operator=( const bad_alloc& other ) throw();
```
| | (until C++11) |
|
```
bad_alloc& operator=( const bad_alloc& other ) noexcept;
```
| | (since C++11) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::bad_alloc` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11).
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::bad\_alloc::what
----------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const throw();
```
| | (until C++11) |
|
```
virtual const char* what() const noexcept;
```
| | (since C++11) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::exception](../../error/exception "cpp/error/exception")
------------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
### Example
```
#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul];
}
} catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << '\n';
}
}
```
Possible output:
```
Allocation failed: std::bad_alloc
```
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
cpp std::get_new_handler std::get\_new\_handler
======================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
std::new_handler get_new_handler() noexcept;
```
| | (since C++11) |
Returns the currently installed new-handler, which may be a null pointer.
This function is thread-safe. Previous call to `[std::set\_new\_handler](set_new_handler "cpp/memory/new/set new handler")` *synchronizes-with* (see `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) the subsequent calls to `std::get_new_handler`.
### Parameters
(none).
### Return value
The currently installed *new-handler*, which may be a null pointer value.
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [set\_new\_handler](set_new_handler "cpp/memory/new/set new handler") | registers a new handler (function) |
| [new\_handler](new_handler "cpp/memory/new/new handler") | function pointer type of the new handler (typedef) |
cpp operator new, operator new[] operator new, operator new[]
============================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
| replaceable allocation functions
| | |
| --- | --- |
| `[[nodiscard]]` | (since C++20) |
| | |
|
```
void* operator new ( std::size_t count );
```
| (1) | |
|
```
void* operator new[]( std::size_t count );
```
| (2) | |
|
```
void* operator new ( std::size_t count, std::align_val_t al );
```
| (3) | (since C++17) |
|
```
void* operator new[]( std::size_t count, std::align_val_t al );
```
| (4) | (since C++17) |
| replaceable non-throwing allocation functions
| | |
| --- | --- |
| `noexcept`. | (since C++11) |
| | |
| --- | --- |
| `[[nodiscard]]` | (since C++20) |
| | |
|
```
void* operator new ( std::size_t count, const std::nothrow_t& tag );
```
| (5) | |
|
```
void* operator new[]( std::size_t count, const std::nothrow_t& tag );
```
| (6) | |
|
```
void* operator new ( std::size_t count,
std::align_val_t al, const std::nothrow_t& );
```
| (7) | (since C++17) |
|
```
void* operator new[]( std::size_t count,
std::align_val_t al, const std::nothrow_t& );
```
| (8) | (since C++17) |
| non-allocating placement allocation functions
| | |
| --- | --- |
| `noexcept`. | (since C++11) |
| | |
| --- | --- |
| `[[nodiscard]]` | (since C++20) |
| | |
|
```
void* operator new ( std::size_t count, void* ptr );
```
| (9) | |
|
```
void* operator new[]( std::size_t count, void* ptr );
```
| (10) | |
| user-defined placement allocation functions | | |
|
```
void* operator new ( std::size_t count, user-defined-args... );
```
| (11) | |
|
```
void* operator new[]( std::size_t count, user-defined-args... );
```
| (12) | |
|
```
void* operator new ( std::size_t count,
std::align_val_t al, user-defined-args... );
```
| (13) | (since C++17) |
|
```
void* operator new[]( std::size_t count,
std::align_val_t al, user-defined-args... );
```
| (14) | (since C++17) |
| class-specific allocation functions | | |
|
```
void* T::operator new ( std::size_t count );
```
| (15) | |
|
```
void* T::operator new[]( std::size_t count );
```
| (16) | |
|
```
void* T::operator new ( std::size_t count, std::align_val_t al );
```
| (17) | (since C++17) |
|
```
void* T::operator new[]( std::size_t count, std::align_val_t al );
```
| (18) | (since C++17) |
| class-specific placement allocation functions | | |
|
```
void* T::operator new ( std::size_t count, user-defined-args... );
```
| (19) | |
|
```
void* T::operator new[]( std::size_t count, user-defined-args... );
```
| (20) | |
|
```
void* T::operator new ( std::size_t count,
std::align_val_t al, user-defined-args... );
```
| (21) | (since C++17) |
|
```
void* T::operator new[]( std::size_t count,
std::align_val_t al, user-defined-args... );
```
| (22) | (since C++17) |
Attempts to allocate requested number of bytes, and the allocation request can fail (even if the requested number of bytes is zero). These allocation functions are called by [new-expressions](../../language/new "cpp/language/new") to allocate memory in which new object would then be initialized. They may also be called using regular function call syntax.
1) Called by non-array [new-expressions](../../language/new "cpp/language/new") to allocate storage required for a single object. The standard library implementation allocates `count` bytes from free store. In case of failure, the standard library implementation calls the function pointer returned by `[std::get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")` and repeats allocation attempts until new handler does not return or becomes a null pointer, at which time it throws `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")`. This function is required to return a pointer suitably aligned to point to an object of the requested size.
2) Called by the array form of [new[]-expressions](../../language/new "cpp/language/new") to allocate all storage required for an array (including possible *new-expression* overhead). The standard library implementation calls version (1)
3) Called by non-array [new-expressions](../../language/new "cpp/language/new") to allocate storage required for a single object whose alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
4) Called by the array form of [new[]-expressions](../../language/new "cpp/language/new") to allocate all storage required for an array of objects whose alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
5) Called by the non-throwing non-array [new-expressions](../../language/new "cpp/language/new"). The standard library implementation calls the version (1) and returns a null pointer on failure instead of propagating the exception.
6) Called by the non-throwing array form of [new[]-expressions](../../language/new "cpp/language/new"). The standard library implementation calls the version (2) and returns a null pointer on failure instead of propagating the exception.
7) Called by the non-throwing non-array [new-expressions](../../language/new "cpp/language/new") when the object's alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. The standard library implementation calls the version (3) and returns a null pointer on failure instead of propagating the exception.
8) Called by the non-throwing array form of [new[]-expressions](../../language/new "cpp/language/new") when the alignment requirement of array elements exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. The standard library implementation calls the version (4) and returns a null pointer on failure instead of propagating the exception.
9) Called by the standard single-object [placement new](../../language/new "cpp/language/new") expression. The standard library implementation performs no action and returns `ptr` unmodified. The behavior is undefined if this function is called through a placement new expression and `ptr` is a null pointer.
10) Called by the standard array form [placement new](../../language/new "cpp/language/new") expression. The standard library implementation performs no action and returns `ptr` unmodified. The behavior is undefined if this function is called through a placement new expression and `ptr` is a null pointer.
11) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature. If a class-specific version (19) is defined, it is called in preference to (11). If neither (11) nor (19) is provided by the user, the placement new expression is ill-formed.
12) If defined, called by the custom array form [placement new](../../language/new "cpp/language/new") expression with the matching signature. If a class-specific version (20) is defined, it is called in preference to (12). If neither (12) nor (20) is provided by the user, the placement new expression is ill-formed.
13) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature if the object's alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If a class-specific version is defined ((15) or (17)), it is called instead. If neither class-specific nor global alignment-aware (this one) placement form is provided, alignment-unaware placement form (11) is looked up instead.
14) If defined, called by the custom array form [placement new](../../language/new "cpp/language/new") expression with the matching signature if the element's alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If a class-specific version ((16) or (18)) is defined, it is called instead. If neither class-specific nor global alignment-aware (this one) placement form is provided, alignment-unaware placement form (12) is looked up instead.
15) If defined, called by the usual single-object [new-expressions](../../language/new "cpp/language/new") if allocating an object of type T.
16) If defined, called by the usual array [new[]-expressions](../../language/new "cpp/language/new") if allocating an array of objects of type T.
17) If defined, called by the usual single-object [new-expressions](../../language/new "cpp/language/new") if allocating an object of type T if its alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If this overload is not provided, but alignment-unaware member form (15) is, alignment-unaware member overload is called instead.
18) If defined, called by the usual array [new[]-expressions](../../language/new "cpp/language/new") if allocating an array of objects of type T if its alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If this overload is not provided, but alignment-unaware member form (16) is, alignment-unaware member overload is called instead.
19) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature if allocating an object of type T.
20) If defined, called by the custom array form of [placement new[]](../../language/new "cpp/language/new") expression with the matching signature if allocating an array of objects of type T.
21) If defined, called by the custom single-object [placement new](../../language/new "cpp/language/new") expression with the matching signature if allocating an object of type T if its alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If this overload is not provided, but alignment-unaware member form (19) is, alignment-unaware member overload is called instead.
22) If defined, called by the custom array form of [placement new[]](../../language/new "cpp/language/new") expression with the matching signature if allocating an array of objects of type T if its alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`. If this overload is not provided, but alignment-unaware member form (20) is, alignment-unaware member overload is called instead. ### Parameters
| | | |
| --- | --- | --- |
| count | - | number of bytes to allocate |
| ptr | - | pointer to a memory area to initialize the object at |
| tag | - | disambiguation tag used to select non-throwing overloads |
| al | - | alignment to use. The behavior is undefined if this is not a valid alignment value |
### Return value
1-4) if the allocation succeeds, a non-null pointer `p0` which points to suitably aligned memory of size at least `size` and is different from any previously returned value `p1`, unless that value `p1` was subsequently passed to a replaceable [deallocation function](operator_delete "cpp/memory/new/operator delete"); if the allocation fails, does not return (an exception is thrown, see below)
5-8) same as (1-4), but returns a null pointer if the allocation fails
9-10) `ptr`
11-22) same as (1-4) if the function does not return on allocation failure, otherwise same as (5-8)
### Exceptions
1-4) throws an exception of a type that would match a handler of type `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")` on failure to allocate memory
11-22) same as (1-4) if the function does not return on allocation failure, otherwise same as (5-8)
### Global replacements
The versions (1-4) are implicitly declared in each translation unit even if the [`<new>`](../../header/new "cpp/header/new") header is not included. Versions (1-8) are *replaceable*: a user-provided non-member function with the same signature defined anywhere in the program, in any source file, replaces the default version. Its declaration does not need to be visible.
The program is ill-formed, no diagnostic required if more than one replacement is provided in the program for any of the replaceable allocation function, or if a replacement is declared with the `inline` specifier. The program is ill-formed if a replacement is defined in namespace other than global namespace, or if it is defined as a static non-member function at global scope.
| | |
| --- | --- |
| The standard library implementations of the nothrow versions (5-8) directly calls the corresponding throwing versions (1-4). The standard library implementation of the throwing array versions (2,4) directly calls the corresponding single-object version (1,3). Thus, replacing the throwing single object allocation functions is sufficient to handle all allocations. | (since C++11) |
```
#include <cstdio>
#include <cstdlib>
#include <new>
// replacement of a minimal set of functions:
// no inline, required by [replacement.functions]/3
void* operator new(std::size_t sz)
{
std::printf("global op new called, size = %zu\n", sz);
if (sz == 0)
++sz; // avoid std::malloc(0) which may return nullptr on success
if (void *ptr = std::malloc(sz))
return ptr;
throw std::bad_alloc{}; // required by [new.delete.single]/3
}
void operator delete(void* ptr) noexcept
{
std::puts("global op delete called");
std::free(ptr);
}
int main()
{
int* p1 = new int;
delete p1;
int* p2 = new int[10]; // guaranteed to call the replacement in C++11
delete[] p2;
}
```
Possible output:
```
global op new called, size = 4
global op delete called
global op new called, size = 40
global op delete called
```
Overloads of `operator new` and `operator new[]` with additional user-defined parameters ("placement forms", versions (11-14)) may be declared at global scope as usual, and are called by the matching placement forms of *new-expressions*.
The standard library's non-allocating placement forms of operator new (9-10) cannot be replaced and can only be customized if the placement new-expression did not use the `::new` syntax, by providing a class-specific placement new (19,20) with matching signature: `void* T::operator new(size_t, void*)` or `void* T::operator new[](size_t, void*)`.
| | |
| --- | --- |
| The placement form `void\* operator new([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t))` is not allowed because the matching signature of the deallocation function, `void [operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)(void\*, [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t))`, is a usual (not placement) deallocation function. | (since C++14) |
### Class-specific overloads
Both single-object and array allocation functions may be defined as public static member functions of a class (versions (15-18)). If defined, these allocation functions are called by [new-expressions](../../language/new "cpp/language/new") to allocate memory for single objects and arrays of this class, unless the new expression used the form `::new` which bypasses class-scope lookup. The keyword [`static`](../../keyword/static "cpp/keyword/static") is optional for these functions: whether used or not, the allocation function is a static member function.
The new expression looks for appropriate allocation function's name firstly in the class scope, and after that in the global scope. Note, that as per [name lookup rules](../../language/lookup "cpp/language/lookup"), any allocation functions declared in class scope hides all global allocation functions for the new-expressions that attempt to allocate objects of this class.
| | |
| --- | --- |
| When allocating objects and arrays of objects whose alignment exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`, overload resolution is performed twice: first, for alignment-aware function signatures, then for alignment-unaware function signatures. This means that if a class with extended alignment has an alignment-unaware class-specific allocation function, it is the function that will be called, not the global alignment-aware allocation function. This is intentional: the class member is expected to know best how to handle that class. | (since C++17) |
```
#include <iostream>
// class-specific allocation functions
struct X
{
static void* operator new(std::size_t count)
{
std::cout << "custom new for size " << count << '\n';
return ::operator new(count);
}
static void* operator new[](std::size_t count)
{
std::cout << "custom new[] for size " << count << '\n';
return ::operator new[](count);
}
};
int main()
{
X* p1 = new X;
delete p1;
X* p2 = new X[10];
delete[] p2;
}
```
Possible output:
```
custom new for size 1
custom new[] for size 10
```
Overloads of `operator new` and `operator new[]` with additional user-defined parameters ("placement forms"), may also be defined as class members (19-22)). When the placement new expression with the matching signature looks for the corresponding allocation function to call, it begins at class scope before examining the global scope, and if the class-specific placement new is provided, it is called.
| | |
| --- | --- |
| When allocating objects and arrays of objects whose alignment exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`, overload resolution for placement forms is performed twice just as for regular forms: first, for alignment-aware function signatures, then for alignment-unaware function signatures. | (since C++17) |
```
#include <stdexcept>
#include <iostream>
struct X
{
X() { throw std::runtime_error(""); }
// custom placement new
static void* operator new(std::size_t count, bool b)
{
std::cout << "custom placement new called, b = " << b << '\n';
return ::operator new(count);
}
// custom placement delete
static void operator delete(void* ptr, bool b)
{
std::cout << "custom placement delete called, b = " << b << '\n';
::operator delete(ptr);
}
};
int main()
{
try
{
X* p1 = new (true) X;
}
catch(const std::exception&) {}
}
```
Output:
```
custom placement new called, b = 1
custom placement delete called, b = 1
```
If class-level `operator new` is a template function, it must have the return type of `void*`, the first argument `[std::size\_t](../../types/size_t "cpp/types/size t")`, and it must have two or more parameters. In other words, only placement forms can be templates.
### Notes
Even though the non-allocating placement new (9,10) cannot be replaced, a function with the same signature may be defined at class scope as described above. In addition, global overloads that look like placement new but take a non-void pointer type as the second argument are allowed, so the code that wants to ensure that the true placement new is called (e.g. `[std::allocator::construct](../allocator/construct "cpp/memory/allocator/construct")`), must use `::new` and also cast the pointer to `void*`.
If the behavior of an deallocation function does not satisfy the default constraints , the behavior is undefined.
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of **`operator new`** and [`operator delete`](operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global **`operator new`** and [`operator delete`](operator_delete "cpp/memory/new/operator delete")
* `[std::calloc](../c/calloc "cpp/memory/c/calloc")`, `[std::malloc](../c/malloc "cpp/memory/c/malloc")`, `[std::realloc](../c/realloc "cpp/memory/c/realloc")`, `[std::aligned\_alloc](../c/aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `[std::free](../c/free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
It is unspecified whether library versions of `operator new` make any calls to `[std::malloc](../c/malloc "cpp/memory/c/malloc")` or `[std::aligned\_alloc](../c/aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17).
For loading a large file, file mapping via OS-specific functions, e.g. [`mmap`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html) on POSIX or `CreateFileMapping`([`A`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga)/[`W`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-createfilemappingw)) along with [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile) on Windows, is preferable to allocating a buffer for file reading.
### Defect Reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 521](https://cplusplus.github.io/CWG/issues/521.html) | C++98 | any class derived from `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")` could be thrown,even if the `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")` base is ambiguous or inaccessible | the exception thrown should matcha handler of type `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")` |
| [LWG 9](https://cplusplus.github.io/LWG/issue9) | C++98 | multiple calls for allocating zerobytes could yield the same pointer | only allowed if all such previouslyyielded pointers have beenpassed to deallocation functions |
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 17.6 Dynamic memory management [support.dynamic]
* C++17 standard (ISO/IEC 14882:2017):
+ 21.6 Dynamic memory management [support.dynamic]
* C++14 standard (ISO/IEC 14882:2014):
+ 18.6 Dynamic memory management [support.dynamic]
* C++11 standard (ISO/IEC 14882:2011):
+ 18.6 Dynamic memory management [support.dynamic]
### See also
| | |
| --- | --- |
| [operator deleteoperator delete[]](operator_delete "cpp/memory/new/operator delete") | deallocation functions (function) |
| [get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")
(C++11) | obtains the current new handler (function) |
| [set\_new\_handler](set_new_handler "cpp/memory/new/set new handler") | registers a new handler (function) |
| [get\_temporary\_buffer](../get_temporary_buffer "cpp/memory/get temporary buffer")
(deprecated in C++17)(removed in C++20) | obtains uninitialized storage (function template) |
| [malloc](../c/malloc "cpp/memory/c/malloc") | allocates memory (function) |
| [aligned\_alloc](../c/aligned_alloc "cpp/memory/c/aligned alloc")
(C++17) | allocates aligned memory (function) |
| programming_docs |
cpp std::set_new_handler std::set\_new\_handler
======================
| Defined in header `[<new>](../../header/new "cpp/header/new")` | | |
| --- | --- | --- |
|
```
std::new_handler set_new_handler( std::new_handler new_p ) throw();
```
| | (until C++11) |
|
```
std::new_handler set_new_handler( std::new_handler new_p ) noexcept;
```
| | (since C++11) |
Makes `new_p` the new global new-handler function and returns the previously installed new-handler.
The *new-handler* function is the function called by [allocation functions](operator_new "cpp/memory/new/operator new") whenever a memory allocation attempt fails. Its intended purpose is one of three things:
1) make more memory available
2) terminate the program (e.g. by calling `[std::terminate](../../error/terminate "cpp/error/terminate")`)
3) throw exception of type `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")` or derived from `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")`. The default implementation throws `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")`. The user can install his own *new-handler*, which may offer behavior different than the default one.
If *new-handler* returns, the allocation function repeats the previously-failed allocation attempt and calls the *new-handler* again if the allocation fails again. To end the loop, *new-handler* may call `std::set_new_handler(nullptr)`: if, after a failed allocation attempt, allocation function finds that `[std::get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")` returns a null pointer value, it will throw `[std::bad\_alloc](bad_alloc "cpp/memory/new/bad alloc")`.
At program startup, *new-handler* is a null pointer.
| | |
| --- | --- |
| This function is thread-safe. Every call to `std::set_new_handler` *synchronizes-with* (see `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) the subsequent `std::set_new_handler` and `[std::get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")` calls. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| new\_p | - | pointer to function of type `[std::new\_handler](new_handler "cpp/memory/new/new handler")`, or null pointer |
### Return value
The previously-installed new handler, or a null pointer value if none was installed.
### Example
```
#include <iostream>
#include <new>
void handler()
{
std::cout << "Memory allocation failed, terminating\n";
std::set_new_handler(nullptr);
}
int main()
{
std::set_new_handler(handler);
try {
while (true) {
new int[1000'000'000ul]();
}
} catch (const std::bad_alloc& e) {
std::cout << e.what() << '\n';
}
}
```
Possible output:
```
Memory allocation failed, terminating
std::bad_alloc
```
### See also
| | |
| --- | --- |
| [operator newoperator new[]](operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [get\_new\_handler](get_new_handler "cpp/memory/new/get new handler")
(C++11) | obtains the current new handler (function) |
| [new\_handler](new_handler "cpp/memory/new/new handler") | function pointer type of the new handler (typedef) |
| [bad\_alloc](bad_alloc "cpp/memory/new/bad alloc") | exception thrown when memory allocation fails (class) |
cpp deduction guides for std::scoped_allocator_adaptor
deduction guides for `std::scoped_allocator_adaptor`
====================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
template<class OuterAlloc, class... InnerAllocs>
scoped_allocator_adaptor(OuterAlloc, InnerAllocs...)
-> scoped_allocator_adaptor<OuterAlloc, InnerAllocs...>;
```
| | (since C++17) |
One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::scoped\_allocator\_adaptor](../scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")` to make it possible to deduce its outer allocator.
### Example
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::deallocate std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::deallocate
=====================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
void deallocate( pointer p, size_type n ) noexcept;
```
| | (since C++11) |
Uses the outer allocator to deallocate the storage referenced by `p`, by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::deallocate(outer_allocator(), p, n)`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the previously allocated memory |
| n | - | the number of objects for which the memory was allocated |
### Return value
(none).
### See also
| | |
| --- | --- |
| [deallocate](../allocator/deallocate "cpp/memory/allocator/deallocate") | deallocates storage (public member function of `std::allocator<T>`) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::max_size std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::max\_size
====================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
size_type max_size() const;
```
| | (since C++11) |
Reports the maximum allocation size supported by the outer allocator, by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::max\_size(outer_allocator())`.
### Parameters
(none).
### Return value
The maximum allocation size for OuterAlloc.
### See also
| | |
| --- | --- |
| [max\_size](../allocator/max_size "cpp/memory/allocator/max size")
(until C++20) | returns the largest supported allocation size (public member function of `std::allocator<T>`) |
| [max\_size](../allocator_traits/max_size "cpp/memory/allocator traits/max size")
[static] | returns the maximum object size supported by the allocator (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::construct std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::construct
====================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
template < class T, class... Args >
void construct( T* p, Args&&... args );
```
| (1) | |
|
```
template< class T1, class T2, class... Args1, class... Args2 >
void construct( std::pair<T1, T2>* p,
std::piecewise_construct_t,
std::tuple<Args1...> x,
std::tuple<Args2...> y );
```
| (2) | (until C++20) |
|
```
template< class T1, class T2 >
void construct( std::pair<T1, T2>* p );
```
| (3) | (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, U&& x, V&& y );
```
| (4) | (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, const std::pair<U, V>& xy );
```
| (5) | (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, std::pair<U, V>&& xy );
```
| (6) | (until C++20) |
|
```
template< class T1, class T2, class NonPair >
void construct( std::pair<T1, T2>* p, NonPair&& non_pair );
```
| (7) | (until C++20) |
Constructs an object in allocated, but not initialized storage pointed to by `p` using OuterAllocator and the provided constructor arguments. If the object is of type that itself uses allocators, or if it is std::pair, passes InnerAllocator down to the constructed object.
First, retrieve the outermost allocator `OUTERMOST` by calling `this->outer_allocator()`, and then calling the `outer_allocator()` member function recursively on the result of this call until reaching an allocator that has no such member function.
Define OUTERMOST\_ALLOC\_TRAITS(x) as `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<decltype(OUTERMOST(x))>>`
1) Creates an object of the given type `T` by means of [uses-allocator construction](../uses_allocator#Uses-allocator_construction "cpp/memory/uses allocator") at the uninitialized memory location indicated by p, using OUTERMOST as the allocator. After adjustment for uses-allocator convention expected by T's constructor, calls `OUTERMOST_ALLOC_TRAITS(*this)::construct`.
| | |
| --- | --- |
| This overload participates in overload resolution only if `U` is not a specialization of `[std::pair](../../utility/pair "cpp/utility/pair")`. | (until C++20) |
| Equivalent to
```
std::apply(
[p,this](auto&&... newargs) {
OUTERMOST_ALLOC_TRAITS(*this)::construct(
OUTERMOST(*this), p, std::forward<decltype(newargs)>(newargs)...);
},
std::uses_allocator_construction_args(
inner_allocator(),
std::forward<Args>(args)...
)
);
```
| (since C++20) |
| | |
| --- | --- |
| 2) First, if either `T1` or `T2` is allocator-aware, modifies the tuples `x` and `y` to include the appropriate inner allocator, resulting in the two new tuples `xprime` and `yprime`, according to the following three rules: 2a) if `T1` is not allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, inner_allocator_type>::value==false`, then `xprime` is `[std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Args1&&...>(std::move(x))`. (it is also required that `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, Args1...>::value==true`) 2b) if `T1` is allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, inner_allocator_type>::value==true`), and its constructor takes an allocator tag (`[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, [std::allocator\_arg\_t](http://en.cppreference.com/w/cpp/memory/allocator_arg_t), inner_allocator_type&, Args1...>::value==true`), then `xprime` is
```
std::tuple_cat(std::tuple<std::allocator_arg_t, inner_allocator_type&>(
std::allocator_arg, inner_allocator()
),
std::tuple<Args1&&...>(std::move(x)))
```
2c) if `T1` is allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, inner_allocator_type>::value==true`), and its constructor takes the allocator as the last argument (`[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, Args1..., inner_allocator_type&>::value==true`), then `xprime` is `[std::tuple\_cat](http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat)([std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<Args1&&...>(std::move(x)), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<inner_allocator_type&>(inner_allocator()))`. Same rules apply to `T2` and the replacement of `y` with `yprime` Once `xprime` and `yprime` are constructed, constructs the pair `p` in allocated storage by calling
```
std::allocator_traits<O>::construct( OUTERMOST,
p,
std::piecewise_construct,
std::move(xprime),
std::move(yprime));
```
3) Equivalent to `construct(p, [std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>(), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>())`, that is, passes the inner allocator on to the pair's member types if they accept them. 4) Equivalent to
```
construct(p, std::piecewise_construct, std::forward_as_tuple(std::forward<U>(x)),
std::forward_as_tuple(std::forward<V>(y)))
```
5) Equivalent to
```
construct(p, std::piecewise_construct, std::forward_as_tuple(xy.first),
std::forward_as_tuple(xy.second))
```
6) Equivalent to
```
construct(p, std::piecewise_construct,
std::forward_as_tuple(std::forward<U>(xy.first)),
std::forward_as_tuple(std::forward<V>(xy.second)))
```
7) This overload participates in overload resolution only if given the exposition-only function template
```
template< class A, class B >
void /*deduce-as-pair*/( const std::pair<A, B>& );
```
, `/*deduce-as-pair*/(non_pair)` is ill-formed when considered as an unevaluated operand. Equivalent to.
```
construct<T1, T2, T1, T2>(p, std::forward<NonPair>(non_pair));
```
| (until C++20) |
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to allocated, but not initialized storage |
| args... | - | the constructor arguments to pass to the constructor of `T` |
| x | - | the constructor arguments to pass to the constructor of `T1` |
| y | - | the constructor arguments to pass to the constructor of `T2` |
| xy | - | the pair whose two members are the constructor arguments for `T1` and `T2` |
| non\_pair | - | non-`pair` argument to convert to `pair` for further construction |
### Return value
(none).
### Notes
This function is called (through `[std::allocator\_traits](../allocator_traits "cpp/memory/allocator traits")`) by any allocator-aware object, such as `[std::vector](../../container/vector "cpp/container/vector")`, that was given a `[std::scoped\_allocator\_adaptor](../scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")` as the allocator to use. Since `inner_allocator` is itself an instance of `[std::scoped\_allocator\_adaptor](../scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")`, this function will also be called when the allocator-aware objects constructed through this function start constructing their own members.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2975](https://cplusplus.github.io/LWG/issue2975) | C++11 | first overload is mistakenly used for pair construction in some cases | constrained to not accept pairs |
| [P0475R1](https://wg21.link/P0475R1) | C++11 | pair piecewise construction may copy the arguments | transformed to tuples of references to avoid copy |
| [LWG 3525](https://cplusplus.github.io/LWG/issue3525) | C++11 | no overload could handle non-`pair` types convertible to `pair` | reconstructing overload added |
### See also
| | |
| --- | --- |
| [construct](../allocator_traits/construct "cpp/memory/allocator traits/construct")
[static] | constructs an object in the allocated storage (function template) |
| [construct](../allocator/construct "cpp/memory/allocator/construct")
(until C++20) | constructs an object in allocated storage (public member function of `std::allocator<T>`) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::destroy std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::destroy
==================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
template< class T >
void destroy( T* p );
```
| | (since C++11) |
Uses the outer allocator to call the destructor of the object pointed to by `p`, by calling.
`[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OUTERMOST>::destroy(OUTERMOST(\*this), p)`.
where OUTERMOST is the type that would be returned by calling `this->outer_allocator()`, and then calling the `outer_allocator()` member function recursively on the result of this call until reaching the type that has no such member function.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the object that is going to be destroyed |
### Return value
(none).
### See also
| | |
| --- | --- |
| [destroy](../allocator_traits/destroy "cpp/memory/allocator traits/destroy")
[static] | destructs an object stored in the allocated storage (function template) |
| [destroy](../allocator/destroy "cpp/memory/allocator/destroy")
(until C++20) | destructs an object in allocated storage (public member function of `std::allocator<T>`) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::operator= std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::operator=
====================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
scoped_allocator_adaptor& operator=(const scoped_allocator_adaptor& other) = default;
```
| (1) | |
|
```
scoped_allocator_adaptor& operator=(scoped_allocator_adaptor&& other) = default;
```
| (2) | |
1) Explicitly defaulted copy assignment operator that copy assigns the base class (`OuterAlloc`, the outer allocator) and all inner allocators.
2) Explicitly defaulted move assignment operator that move assigns the base class (`OuterAlloc`, the outer allocator) and all inner allocators.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another `std::scoped_allocator_adaptor` |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::outer_allocator std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::outer\_allocator
===========================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
outer_allocator_type& outer_allocator() noexcept;
```
| (1) | (since C++11) |
|
```
const outer_allocator_type& outer_allocator() const noexcept;
```
| (2) | (since C++11) |
Obtains a reference to the outer allocator used to declare this class.
1) Returns `static_cast<OuterAlloc&>(*this)`.
2) Returns `static_cast<const OuterAlloc&>(*this)`. ### Parameters
(none).
### Return value
A reference to `OuterAlloc`.
### See also
| | |
| --- | --- |
| [inner\_allocator](inner_allocator "cpp/memory/scoped allocator adaptor/inner allocator") | obtains an `inner_allocator` reference (public member function) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>:: select_on_container_copy_construction std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>:: select\_on\_container\_copy\_construction
=====================================================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
scoped_allocator_adaptor select_on_container_copy_construction() const;
```
| | (since C++11) |
Creates a new instance of `std::scoped_allocator_adaptor`, where the outer allocator base class and each inner allocator subobject are obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::select\_on\_container\_copy\_construction()`.
### Parameters
(none).
### Return value
A new `std::scoped_allocator_adaptor` object, constructed from correctly copied allocators.
### See also
| | |
| --- | --- |
| [select\_on\_container\_copy\_construction](../allocator_traits/select_on_container_copy_construction "cpp/memory/allocator traits/select on container copy construction")
[static] | obtains the allocator to use after copying a standard container (public static member function of `std::allocator_traits<Alloc>`) |
| programming_docs |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::inner_allocator std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::inner\_allocator
===========================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
inner_allocator_type& inner_allocator() noexcept;
```
| (1) | (since C++11) |
|
```
const inner_allocator_type& inner_allocator() const noexcept;
```
| (2) | (since C++11) |
Obtains a reference to the inner allocator used to declare this `scoped_allocator_adaptor`.
If `sizeof...(InnerAllocs) == 0`, that is, no inner allocators were declared, returns `*this`. Otherwise returns a reference to `[std::scoped\_allocator\_adaptor](http://en.cppreference.com/w/cpp/memory/scoped_allocator_adaptor)<InnerAllocs...>`, that is, a scoped allocator composed of all inner allocators of `*this`, with the first inner allocator becoming the outer allocator.
### Parameters
(none).
### Return value
A reference to the inner allocator, which is itself a `std::scoped_allocator_adaptor`.
### See also
| | |
| --- | --- |
| [outer\_allocator](outer_allocator "cpp/memory/scoped allocator adaptor/outer allocator") | obtains an `outer_allocator` reference (public member function) |
cpp operator==,!=(std::scoped_allocator_adaptor) operator==,!=(std::scoped\_allocator\_adaptor)
==============================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
template< class OuterAlloc1, class OuterAlloc2, class... InnerAllocs >
bool operator==( const scoped_allocator_adaptor<OuterAlloc1, InnerAllocs...>& lhs,
const scoped_allocator_adaptor<OuterAlloc2, InnerAllocs...>& rhs ) noexcept;
```
| | (since C++11) |
|
```
template< class OuterAlloc1, class OuterAlloc2, class... InnerAllocs >
bool operator!=( const scoped_allocator_adaptor<OuterAlloc1, InnerAllocs...>& lhs,
const scoped_allocator_adaptor<OuterAlloc2, InnerAllocs...>& rhs ) noexcept;
```
| | (since C++11) (until C++20) |
Compares two scoped allocator adaptors. Two such allocators are equal if:
* `lhs.outer_allocator() == rhs.outer_allocator()`, and
* if `sizeof...(InnerAllocs) > 0`, `lhs.inner_allocator() == rhs.inner_allocator()`.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | scoped allocator adaptors to compare |
### Return value
1) Returns `true` if `lhs` and `rhs` are equal, `false` otherwise.
2) Returns `true` if `lhs` and `rhs` are not equal, `false` otherwise.
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>::allocate std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>::allocate
===================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
| | (1) | |
|
```
pointer allocate( size_type n );
```
| (since C++11) (until C++20) |
|
```
[[nodiscard]] pointer allocate( size_type n );
```
| (since C++20) |
| | (2) | |
|
```
pointer allocate( size_type n, const_void_pointer hint );
```
| (since C++11) (until C++20) |
|
```
[[nodiscard]] pointer allocate( size_type n, const_void_pointer hint );
```
| (since C++20) |
Uses the outer allocator to allocate uninitialized storage.
1) Calls `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::allocate(outer_allocator(), n)`
2) Additionally provides memory locality hint, by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<OuterAlloc>::allocate(outer_allocator(), n, hint)`
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of objects to allocate storage for |
| hint | - | pointer to a nearby memory location |
### Return value
The pointer to the allocated storage.
### See also
| | |
| --- | --- |
| [allocate](../allocator/allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function of `std::allocator<T>`) |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>:: ~scoped_allocator_adaptor std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>:: ~scoped\_allocator\_adaptor
=======================================================================================
| | | |
| --- | --- | --- |
|
```
~scoped_allocator_adaptor();
```
| | (since C++11) |
Destroys the scoped allocator adaptor.
cpp std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>:: scoped_allocator_adaptor std::scoped\_allocator\_adaptor<OuterAlloc,InnerAlloc...>:: scoped\_allocator\_adaptor
======================================================================================
| Defined in header `[<scoped\_allocator>](../../header/scoped_allocator "cpp/header/scoped allocator")` | | |
| --- | --- | --- |
|
```
scoped_allocator_adaptor();
```
| (1) | (since C++11) |
|
```
template< class OuterA2 >
scoped_allocator_adaptor( OuterA2&& outerAlloc, const InnerAllocs&... innerAllocs) noexcept;
```
| (2) | (since C++11) |
|
```
scoped_allocator_adaptor( const scoped_allocator_adaptor& other ) noexcept;
```
| (3) | (since C++11) |
|
```
scoped_allocator_adaptor( scoped_allocator_adaptor&& other ) noexcept;
```
| (4) | (since C++11) |
|
```
template< class OuterA2 >
scoped_allocator_adaptor( const scoped_allocator_adaptor<OuterA2, InnerAllocs...>& other ) noexcept;
```
| (5) | (since C++11) |
|
```
template< class OuterA2 >
scoped_allocator_adaptor( scoped_allocator_adaptor<OuterA2, InnerAllocs...>&& other ) noexcept;
```
| (6) | (since C++11) |
1) Default constructor: value-initializes the `OuterAlloc` base class and the inner allocator member object, if used by the implementation.
2) Constructs the base class `OuterAlloc` from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<OuterA2>(outerAlloc)`, and the inner allocators with `innerAllocs...`. This overload participates in overload resolution only if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<OuterAlloc, OuterA2>::value` is `true`.
3) Copy-constructor: initializes each allocator from the corresponding allocator of `other`
4) Move-constructor: moves each allocator from the corresponding allocator of `other` into `*this`
5) Initializes each allocator from the corresponding allocator of `other`. This overload participates in overload resolution only if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<OuterAlloc, const OuterA2&>::value` is `true`.
6) Initializes each allocator from the corresponding allocator of `other`, using move semantics. This overload participates in overload resolution only if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<OuterAlloc, OuterA2>::value` is `true`. ### Parameters
| | | |
| --- | --- | --- |
| outerAlloc | - | constructor argument for the outer allocator |
| innerAllocs... | - | constructor arguments for the inner allocators |
| other | - | another `std::scoped_allocator_adaptor` |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2782](https://cplusplus.github.io/LWG/issue2782) | C++11 | constructors taking `OuterA2` weren't constrained, interfering with metaprogramming | constraint added |
### See also
| | |
| --- | --- |
| [allocate](allocate "cpp/memory/scoped allocator adaptor/allocate") | allocates uninitialized storage using the outer allocator (public member function) |
| [construct](construct "cpp/memory/scoped allocator adaptor/construct") | constructs an object in allocated storage, passing the inner allocator to its constructor if appropriate (public member function) |
cpp std::declare_reachable std::declare\_reachable
=======================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void declare_reachable( void* p );
```
| | (since C++11) (removed in C++23) |
Declares the object referenced by the pointer `p` reachable. Reachable objects will not be deleted by the garbage collector or considered to be a leak by a leak detector even if all pointers to it are destroyed. An object may be declared reachable multiple times, in which case multiple calls to `[std::undeclare\_reachable](undeclare_reachable "cpp/memory/gc/undeclare reachable")` would be needed to remove this property. For example, a [XOR linked list](https://en.wikipedia.org/wiki/XOR_linked_list "enwiki:XOR linked list") needs to declare its nodes reachable if the implementation has garbage collection enabled.
### Parameters
| | | |
| --- | --- | --- |
| p | - | a safely-derived pointer or a null pointer |
### Return value
(none).
### Exceptions
May throw `[std::bad\_alloc](../new/bad_alloc "cpp/memory/new/bad alloc")` if the system cannot allocate memory required to track reachable objects.
### Example
### See also
| | |
| --- | --- |
| [undeclare\_reachable](undeclare_reachable "cpp/memory/gc/undeclare reachable")
(C++11)(removed in C++23) | declares that an object can be recycled (function template) |
cpp std::undeclare_no_pointers std::undeclare\_no\_pointers
============================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void undeclare_no_pointers( char *p, std::size_t n );
```
| | (since C++11) (removed in C++23) |
Unregisters a range earlier registered with `[std::declare\_no\_pointers](http://en.cppreference.com/w/cpp/memory/gc/declare_no_pointers)()`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the beginning of the range previosly registered with `[std::declare\_no\_pointers](declare_no_pointers "cpp/memory/gc/declare no pointers")` |
| n | - | the number of bytes in the range, same value as previously used with `[std::declare\_no\_pointers](declare_no_pointers "cpp/memory/gc/declare no pointers")` |
### Return value
(none).
### Exceptions
Throws nothing.
### Example
### See also
| | |
| --- | --- |
| [declare\_no\_pointers](declare_no_pointers "cpp/memory/gc/declare no pointers")
(C++11)(removed in C++23) | declares that a memory area does not contain traceable pointers (function) |
cpp std::undeclare_reachable std::undeclare\_reachable
=========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
template< class T >
T* undeclare_reachable( T* p );
```
| | (since C++11) (removed in C++23) |
Removes the reachable status of the object, referenced by the pointer `p`, if it was previously set by `[std::declare\_reachable](declare_reachable "cpp/memory/gc/declare reachable")`. If the object was declared reachable multiple times, equal number of calls to `undeclare_reachable` would be needed to remove this status. Once the object is not declared reachable and has no pointers referencing it, it may be reclaimed by garbage collector or reported as a leak by a leak detector.
### Parameters
| | | |
| --- | --- | --- |
| p | - | a pointer to an object previously declared reachable and not destructed since then |
### Return value
A safely-derived copy of `p`.
### Exceptions
Throws nothing.
### Example
### See also
| | |
| --- | --- |
| [declare\_reachable](declare_reachable "cpp/memory/gc/declare reachable")
(C++11)(removed in C++23) | declares that an object can not be recycled (function) |
cpp std::pointer_safety std::pointer\_safety
====================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
enum class pointer_safety {
relaxed,
preferred,
strict
};
```
| | (since C++11) (removed in C++23) |
The scoped enumeration type `pointer_safety` lists the pointer safety modes supported by C++.
### Enumeration constants
| | |
| --- | --- |
| `pointer_safety::strict` | Only safely-derived pointers (pointers to objects allocated with new or subobjects thereof) may be dereferenced or deallocated. Garbage collector may be active. |
| `pointer_safety::preferred` | All pointers are considered valid and may be dereferenced or deallocated. A reachability-based leak detector may be active. |
| `pointer_safety::relaxed` | All pointers are considered valid and may be dereferenced or deallocated. |
### See also
| | |
| --- | --- |
| [get\_pointer\_safety](get_pointer_safety "cpp/memory/gc/get pointer safety")
(C++11)(removed in C++23) | returns the current pointer safety model (function) |
cpp std::get_pointer_safety std::get\_pointer\_safety
=========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
std::pointer_safety get_pointer_safety() noexcept;
```
| | (since C++11) (removed in C++23) |
Obtains the implementation-defined pointer safety model, which is a value of type `[std::pointer\_safety](pointer_safety "cpp/memory/gc/pointer safety")`.
### Parameters
(none).
### Return value
The pointer safety used by this implementation.
### Example
```
#include <iostream>
#include <memory>
int main()
{
std::cout << "Pointer safety: ";
switch (std::get_pointer_safety()) {
case std::pointer_safety::strict: std::cout << "strict\n"; break;
case std::pointer_safety::preferred: std::cout << "preferred\n"; break;
case std::pointer_safety::relaxed: std::cout << "relaxed\n"; break;
}
}
```
Possible output:
```
Pointer safety: relaxed
```
### See also
| | |
| --- | --- |
| [pointer\_safety](pointer_safety "cpp/memory/gc/pointer safety")
(C++11)(removed in C++23) | lists pointer safety models (enum) |
cpp std::declare_no_pointers std::declare\_no\_pointers
==========================
| Defined in header `[<memory>](../../header/memory "cpp/header/memory")` | | |
| --- | --- | --- |
|
```
void declare_no_pointers( char *p, std::size_t n );
```
| | (since C++11) (removed in C++23) |
Informs the garbage collector or leak detector that the specified memory region (`n` bytes beginning at the byte pointed to by `p`) contains no traceable pointers. If any part of the region is within an allocated object, the entire region must be contained in the same object.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the beginning of the range |
| n | - | the number of bytes in the range |
### Return value
(none).
### Exceptions
Throws nothing.
### Example
### See also
| | |
| --- | --- |
| [undeclare\_no\_pointers](undeclare_no_pointers "cpp/memory/gc/undeclare no pointers")
(C++11)(removed in C++23) | cancels the effect of `std::declare_no_pointers` (function) |
cpp std::pmr::memory_resource::do_deallocate std::pmr::memory\_resource::do\_deallocate
==========================================
| | | |
| --- | --- | --- |
|
```
virtual void do_deallocate( void* p, std::size_t bytes, std::size_t alignment ) = 0;
```
| | (since C++17) |
Deallocates the storage pointed to by `p`.
`p` must have been returned by a prior call to `allocate(bytes, alignment)` on a `memory_resource` that compares equal to `*this`, and the storage it points to must not yet have been deallocated, otherwise the behavior is undefined.
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [deallocate](deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function) |
cpp std::pmr::memory_resource::deallocate std::pmr::memory\_resource::deallocate
======================================
| | | |
| --- | --- | --- |
|
```
void deallocate( void* p,
std::size_t bytes,
std::size_t alignment = alignof(std::max_align_t) );
```
| | (since C++17) |
Deallocates the storage pointed to by `p`. `p` shall have been returned by a prior call to `allocate(bytes, alignment)` on a `memory_resource` that compares equal to `*this`, and the storage it points to shall not yet have been deallocated.
Equivalent to `do_deallocate(p, bytes, alignment);`.
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [do\_deallocate](do_deallocate "cpp/memory/memory resource/do deallocate")
[virtual] | deallocates memory (virtual private member function) |
cpp std::pmr::memory_resource::do_allocate std::pmr::memory\_resource::do\_allocate
========================================
| | | |
| --- | --- | --- |
|
```
virtual void* do_allocate( std::size_t bytes, std::size_t alignment ) = 0;
```
| | (since C++17) |
Allocates storage with a size of at least `bytes` bytes, aligned to the specified `alignment`.
`alignment` shall be a power of two.
### Exceptions
Throws an exception if storage of the requested size and alignment cannot be obtained.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2843](https://cplusplus.github.io/LWG/issue2843) | C++17 | handling of unsupported alignment contradictory | throws an exception |
### See also
| | |
| --- | --- |
| [allocate](allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function) |
cpp std::pmr::memory_resource::do_is_equal std::pmr::memory\_resource::do\_is\_equal
=========================================
| | | |
| --- | --- | --- |
|
```
virtual bool do_is_equal( const std::pmr::memory_resource& other ) const noexcept = 0;
```
| | (since C++17) |
Compares `*this` for equality with `other`.
Two `memory_resource`s compare equal if and only if memory allocated from one `memory_resource` can be deallocated from the other and vice versa.
### Notes
The most-derived type of `other` may not match the most derived type of `*this`. A derived class implementation therefore must typically check whether the most derived types of `*this` and `other` match using [`dynamic_cast`](../../language/dynamic_cast "cpp/language/dynamic cast"), and immediately return `false` if the cast fails.
### See also
| | |
| --- | --- |
| [is\_equal](is_equal "cpp/memory/memory resource/is equal") | compare for equality with another `memory_resource` (public member function) |
cpp std::pmr::memory_resource::is_equal std::pmr::memory\_resource::is\_equal
=====================================
| | | |
| --- | --- | --- |
|
```
bool is_equal( const memory_resource& other ) const noexcept;
```
| | (since C++17) |
Compares `*this` for equality with `other`. Two `memory_resource`s compare equal if and only if memory allocated from one `memory_resource` can be deallocated from the other and vice versa.
Equivalent to `return do_is_equal(other);`.
### See also
| | |
| --- | --- |
| [do\_is\_equal](do_is_equal "cpp/memory/memory resource/do is equal")
[virtual] | compare for equality with another `memory_resource` (virtual private member function) |
| programming_docs |
cpp std::pmr::operator==, std::pmr::operator!= std::pmr::operator==, std::pmr::operator!=
==========================================
| Defined in header `[<memory\_resource>](../../header/memory_resource "cpp/header/memory resource")` | | |
| --- | --- | --- |
|
```
bool operator==( const std::pmr::memory_resource& a,
const std::pmr::memory_resource& b ) noexcept;
```
| (1) | (since C++17) |
|
```
bool operator!=( const std::pmr::memory_resource& a,
const std::pmr::memory_resource& b ) noexcept;
```
| (2) | (since C++17) (until C++20) |
Compares the `memory_resource`s `a` and `b` for equality. Two `memory_resource`s compare equal if and only if memory allocated from one `memory_resource` can be deallocated from the other and vice versa.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Return value
1) `&a == &b || a.is_equal(b)`
2) `!(a == b)`
### See also
| | |
| --- | --- |
| [is\_equal](is_equal "cpp/memory/memory resource/is equal") | compare for equality with another `memory_resource` (public member function) |
cpp std::pmr::memory_resource::allocate std::pmr::memory\_resource::allocate
====================================
| | | |
| --- | --- | --- |
|
```
void* allocate( std::size_t bytes,
std::size_t alignment = alignof(std::max_align_t) );
```
| | (since C++17) (until C++20) |
|
```
[[nodiscard]] void* allocate( std::size_t bytes,
std::size_t alignment = alignof(std::max_align_t) );
```
| | (since C++20) |
Allocates storage with a size of at least `bytes` bytes, aligned to the specified `alignment`.
Equivalent to `return do_allocate(bytes, alignment);`.
### Exceptions
Throws an exception if storage of the requested size and alignment cannot be obtained.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2843](https://cplusplus.github.io/LWG/issue2843) | ??? | over-alignment was allowed to be unsupported | alignment must be honoured |
### See also
| | |
| --- | --- |
| [do\_allocate](do_allocate "cpp/memory/memory resource/do allocate")
[virtual] | allocates memory (virtual private member function) |
cpp std::pmr::memory_resource::memory_resource std::pmr::memory\_resource::memory\_resource
============================================
| | | |
| --- | --- | --- |
|
```
memory_resource() = default;
```
| (1) | (since C++17) (implicitly declared) |
|
```
memory_resource( const memory_resource& ) = default;
```
| (2) | (since C++17) (implicitly declared) |
1) Implicitly declared default constructor.
2) Implicitly declared copy constructor.
cpp std::pmr::polymorphic_allocator<T>::delete_object std::pmr::polymorphic\_allocator<T>::delete\_object
===================================================
| | | |
| --- | --- | --- |
|
```
template <class U>
void delete_object( U* p );
```
| | (since C++20) |
Destroys the object of type `U` and deallocates storage allocated for it.
Equivalent to
`[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<polymorphic_allocator>::destroy(\*this, p);
deallocate_object(p);`
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the object to destroy and deallocate |
### Exceptions
Throws nothing.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization.
### See also
| | |
| --- | --- |
| [deallocate\_bytes](deallocate_bytes "cpp/memory/polymorphic allocator/deallocate bytes")
(C++20) | Free raw memory obtained from allocate\_bytes (public member function) |
| [deallocate\_object](deallocate_object "cpp/memory/polymorphic allocator/deallocate object")
(C++20) | Frees raw memory obtained by allocate\_object (public member function) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::allocate_object std::pmr::polymorphic\_allocator<T>::allocate\_object
=====================================================
| | | |
| --- | --- | --- |
|
```
template< class U >
[[nodiscard]] U* allocate_object( std::size_t n = 1 );
```
| | (since C++20) |
Allocates storage for `n` objects of type `U` using the underlying memory resource.
If `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max() / sizeof(U) < n`, throws `[std::bad\_array\_new\_length](../new/bad_array_new_length "cpp/memory/new/bad array new length")`, otherwise equivalent to `return static_cast<U*>(allocate_bytes(n * sizeof(U), alignof(U)) );`
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of objects to allocate storage for |
### Return value
A pointer to the allocated storage.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization as a shortcut to avoid having to rebind from `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<T>` to `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<U>`.
Since `U` is not deduced, it must be provided as a template argument when calling this function.
### Exceptions
Throws `[std::bad\_array\_new\_length](../new/bad_array_new_length "cpp/memory/new/bad array new length")` if `n > [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max() / sizeof(U)`; may also be any exceptions thrown by the call to `resource()->allocate`.
### See also
| | |
| --- | --- |
| [allocate\_bytes](allocate_bytes "cpp/memory/polymorphic allocator/allocate bytes")
(C++20) | Allocate raw aligned memory from the underlying resource (public member function) |
| [new\_object](new_object "cpp/memory/polymorphic allocator/new object")
(C++20) | Allocates and constructs an object (public member function) |
| [allocate](allocate "cpp/memory/polymorphic allocator/allocate") | Allocate memory (public member function) |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::deallocate std::pmr::polymorphic\_allocator<T>::deallocate
===============================================
| | | |
| --- | --- | --- |
|
```
void deallocate( T* p, std::size_t n );
```
| | (since C++17) |
Deallocates the storage pointed to by `p`, which must have been allocated from a `[std::pmr::memory\_resource](../memory_resource "cpp/memory/memory resource")` `x` that compares equal to `*resource()` using `x.allocate(n * sizeof(T), alignof(T))`.
Equivalent to `this->resource()->deallocate(p, n * sizeof(T), alignof(T));`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to memory to deallocate |
| n | - | the number of objects originally allocated |
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [deallocate\_bytes](deallocate_bytes "cpp/memory/polymorphic allocator/deallocate bytes")
(C++20) | Free raw memory obtained from allocate\_bytes (public member function) |
| [deallocate\_object](deallocate_object "cpp/memory/polymorphic allocator/deallocate object")
(C++20) | Frees raw memory obtained by allocate\_object (public member function) |
| [delete\_object](delete_object "cpp/memory/polymorphic allocator/delete object")
(C++20) | Destroys and deallocates an object (public member function) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::resource std::pmr::polymorphic\_allocator<T>::resource
=============================================
| | | |
| --- | --- | --- |
|
```
std::pmr::memory_resource* resource() const;
```
| | (since C++17) |
Returns the [memory resource](../memory_resource "cpp/memory/memory resource") pointer used by this polymorphic allocator.
### Parameters
(none).
### Return value
The memory resource pointer used by this polymorphic allocator.
cpp std::pmr::polymorphic_allocator<T>::polymorphic_allocator std::pmr::polymorphic\_allocator<T>::polymorphic\_allocator
===========================================================
| | | |
| --- | --- | --- |
|
```
polymorphic_allocator() noexcept;
```
| (1) | |
|
```
polymorphic_allocator( const polymorphic_allocator& other ) = default;
```
| (2) | |
|
```
template< class U >
polymorphic_allocator( const polymorphic_allocator<U>& other ) noexcept;
```
| (3) | |
|
```
polymorphic_allocator( std::pmr::memory_resource* r );
```
| (4) | |
Constructs a new `polymorphic_allocator`.
1) Constructs a `polymorphic_allocator` using the return value of `[std::pmr::get\_default\_resource](http://en.cppreference.com/w/cpp/memory/get_default_resource)()` as the underlying memory resource.
2-3) Constructs a `polymorphic_allocator` using `other.resource()` as the underlying memory resource.
4) Constructs a `polymorphic_allocator` using `r` as the underlying memory resource. This constructor provides an implicit conversion from `[std::pmr::memory\_resource](http://en.cppreference.com/w/cpp/memory/memory_resource)\*`. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another `polymorphic_allocator` to copy from |
| r | - | pointer to the memory resource to use. May not be null. |
### Exceptions
4) Throws nothing. ### Notes
Copying a container using a `polymorphic_allocator` will not call the allocator's copy constructor. Instead, the new container will use the return value of `[select\_on\_container\_copy\_construction](select_on_container_copy_construction "cpp/memory/polymorphic allocator/select on container copy construction")` (a default-constructed `polymorphic_allocator`) as its allocator.
### See also
| | |
| --- | --- |
| [select\_on\_container\_copy\_construction](select_on_container_copy_construction "cpp/memory/polymorphic allocator/select on container copy construction") | Create a new `polymorphic_allocator` for use by a container's copy constructor (public member function) |
cpp std::pmr::polymorphic_allocator<T>::construct std::pmr::polymorphic\_allocator<T>::construct
==============================================
| | | |
| --- | --- | --- |
|
```
template < class U, class... Args >
void construct( U* p, Args&&... args );
```
| (1) | (since C++17) |
|
```
template< class T1, class T2, class... Args1, class... Args2 >
void construct( std::pair<T1, T2>* p,
std::piecewise_construct_t,
std::tuple<Args1...> x,
std::tuple<Args2...> y );
```
| (2) | (since C++17) (until C++20) |
|
```
template< class T1, class T2 >
void construct( std::pair<T1, T2>* p );
```
| (3) | (since C++17) (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, U&& x, V&& y );
```
| (4) | (since C++17) (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, const std::pair<U, V>& xy );
```
| (5) | (since C++17) (until C++20) |
|
```
template< class T1, class T2, class U, class V >
void construct( std::pair<T1, T2>* p, std::pair<U, V>&& xy );
```
| (6) | (since C++17) (until C++20) |
|
```
template< class T1, class T2, class NonPair >
void construct( std::pair<T1, T2>* p, NonPair&& non_pair );
```
| (7) | (since C++17) (until C++20) |
Constructs an object in allocated, but not initialized storage pointed to by `p` the provided constructor arguments. If the object is of type that itself uses allocators, or if it is std::pair, passes `this->resource()` down to the constructed object.
1) Creates an object of the given type `U` by means of [uses-allocator construction](../uses_allocator#Uses-allocator_construction "cpp/memory/uses allocator") at the uninitialized memory location indicated by p, using `*this` as the allocator. This overload participates in overload resolution only if `U` is not a specialization of `[std::pair](../../utility/pair "cpp/utility/pair")`. (until C++20)
| | |
| --- | --- |
| 2) First, if either `T1` or `T2` is allocator-aware, modifies the tuples `x` and `y` to include `this->resource()`, resulting in the two new tuples `xprime` and `yprime`, according to the following three rules: 2a) if `T1` is not allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, polymorphic_allocator>::value==false`) and `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, Args1...>::value==true`, then `xprime` is `x`, unmodified. 2b) if `T1` is allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, polymorphic_allocator>::value==true`), and its constructor takes an allocator tag (`[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, [std::allocator\_arg\_t](http://en.cppreference.com/w/cpp/memory/allocator_arg_t), polymorphic_allocator, Args1...>::value==true`, then `xprime` is `[std::tuple\_cat](http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat)([std::make\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/make_tuple)([std::allocator\_arg](http://en.cppreference.com/w/cpp/memory/allocator_arg), \*this), std::move(x))` 2c) if `T1` is allocator-aware (`[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<T1, polymorphic_allocator>::value==true`), and its constructor takes the allocator as the last argument (`[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<T1, Args1..., polymorphic_allocator>::value==true`), then `xprime` is `[std::tuple\_cat](http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat)(std::move(x), [std::make\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/make_tuple)(\*this))`. 2d) Otherwise, the program is ill-formed. Same rules apply to `T2` and the replacement of `y` with `yprime`. Once `xprime` and `yprime` are constructed, constructs the pair `p` in allocated storage as if by `::new((void \*) p) pair<T1, T2>([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), std::move(xprime), std::move(yprime));` 3) Equivalent to `construct(p, [std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>(), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>())`, that is, passes the memory resource on to the pair's member types if they accept them. 4) Equivalent to
```
construct(p, std::piecewise_construct, std::forward_as_tuple(std::forward<U>(x)),
std::forward_as_tuple(std::forward<V>(y)))
```
5) Equivalent to
```
construct(p, std::piecewise_construct, std::forward_as_tuple(xy.first),
std::forward_as_tuple(xy.second))
```
6) Equivalent to
```
construct(p, std::piecewise_construct, std::forward_as_tuple(std::forward<U>(xy.first)),
std::forward_as_tuple(std::forward<V>(xy.second)))
```
7) This overload participates in overload resolution only if given the exposition-only function template
```
template< class A, class B >
void /*deduce-as-pair*/( const std::pair<A, B>& );
```
, `/*deduce-as-pair*/(non_pair)` is ill-formed when considered as an unevaluated operand. Equivalent to.
```
construct<T1, T2, T1, T2>(p, std::forward<NonPair>(non_pair));
```
| (until C++20) |
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to allocated, but not initialized storage |
| args... | - | the constructor arguments to pass to the constructor of `T` |
| x | - | the constructor arguments to pass to the constructor of `T1` |
| y | - | the constructor arguments to pass to the constructor of `T2` |
| xy | - | the pair whose two members are the constructor arguments for `T1` and `T2` |
| non\_pair | - | non-`pair` argument to convert to `pair` for further construction |
### Return value
(none).
### Notes
This function is called (through `[std::allocator\_traits](../allocator_traits "cpp/memory/allocator traits")`) by any allocator-aware object, such as `[std::pmr::vector](../../container/vector "cpp/container/vector")` (or another `[std::vector](../../container/vector "cpp/container/vector")` that was given a `std::pmr::polymorphic_allocator` as the allocator to use).
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2969](https://cplusplus.github.io/LWG/issue2969) | C++17 | uses-allocator construction passed `resource()` | passes `*this` |
| [LWG 2975](https://cplusplus.github.io/LWG/issue2975) | C++17 | first overload is mistakenly used for pair construction in some cases | constrained to not accept pairs |
| [LWG 3525](https://cplusplus.github.io/LWG/issue3525) | C++17 | no overload could handle non-`pair` types convertible to `pair` | reconstructing overload added |
### See also
| | |
| --- | --- |
| [construct](../allocator_traits/construct "cpp/memory/allocator traits/construct")
[static] | constructs an object in the allocated storage (function template) |
| [construct](../allocator/construct "cpp/memory/allocator/construct")
(until C++20) | constructs an object in allocated storage (public member function of `std::allocator<T>`) |
cpp std::pmr::polymorphic_allocator<T>::destroy std::pmr::polymorphic\_allocator<T>::destroy
============================================
| | | |
| --- | --- | --- |
|
```
template<class U>
void destroy( U* p );
```
| | (since C++17) (deprecated in C++20) |
Destroys the object pointed to by `p`, as if by calling `p->~U()`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to the object being destroyed |
### Notes
This function is deprecated via [LWG issue 3036](https://cplusplus.github.io/LWG/issue3036), because its functionality can be provided by the default implementation of `[std::allocator\_traits::destroy](../allocator_traits/destroy "cpp/memory/allocator traits/destroy")` and hence extraneous.
### See also
| | |
| --- | --- |
| [destroy](../allocator_traits/destroy "cpp/memory/allocator traits/destroy")
[static] | destructs an object stored in the allocated storage (function template) |
| programming_docs |
cpp std::pmr::polymorphic_allocator<T>::deallocate_object std::pmr::polymorphic\_allocator<T>::deallocate\_object
=======================================================
| | | |
| --- | --- | --- |
|
```
template <class U>
void deallocate_object( U* p, std::size_t n = 1 );
```
| | (since C++20) |
Deallocates the storage pointed to by `p`, which must have been allocated from a `[std::pmr::memory\_resource](../memory_resource "cpp/memory/memory resource")` `x` that compares equal to `*resource()`, using `x.allocate(n*sizeof(U), alignof(U))`, typically through a call to `allocate_object<U>(n)`.
Equivalent to `deallocate_bytes(p, n*sizeof(U), alignof(U));`
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to memory to deallocate |
| n | - | number of objects of type U the memory was for |
### Exceptions
Throws nothing.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization.
### See also
| | |
| --- | --- |
| [deallocate\_bytes](deallocate_bytes "cpp/memory/polymorphic allocator/deallocate bytes")
(C++20) | Free raw memory obtained from allocate\_bytes (public member function) |
| [delete\_object](delete_object "cpp/memory/polymorphic allocator/delete object")
(C++20) | Destroys and deallocates an object (public member function) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::allocate_bytes std::pmr::polymorphic\_allocator<T>::allocate\_bytes
====================================================
| | | |
| --- | --- | --- |
|
```
[[nodiscard]] void* allocate_bytes( std::size_t nbytes,
std::size_t alignment = alignof(std::max_align_t) );
```
| | (since C++20) |
Allocates `nbytes` bytes of storage at specified alignment `alignment` using the underlying memory resource. Equivalent to `return resource()->allocate(nbytes, alignment);`.
### Parameters
| | | |
| --- | --- | --- |
| nbytes | - | the number of bytes to allocate |
| alignment | - | the alignment to use |
### Return value
A pointer to the allocated storage.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization.
The return type is `void*` (rather than, e.g., `[std::byte](http://en.cppreference.com/w/cpp/types/byte)\*`) to support conversion to an arbitrary pointer type `U*` by `static_cast<U*>`.
### Exceptions
May throw any exceptions thrown by the call to `resource()->allocate`.
### See also
| | |
| --- | --- |
| [allocate\_object](allocate_object "cpp/memory/polymorphic allocator/allocate object")
(C++20) | Allocates raw memory suitable for an object or an array (public member function) |
| [new\_object](new_object "cpp/memory/polymorphic allocator/new object")
(C++20) | Allocates and constructs an object (public member function) |
| [allocate](allocate "cpp/memory/polymorphic allocator/allocate") | Allocate memory (public member function) |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::deallocate_bytes std::pmr::polymorphic\_allocator<T>::deallocate\_bytes
======================================================
| | | |
| --- | --- | --- |
|
```
void deallocate_bytes( void* p,
std::size_t nbytes,
std::size_t alignment = alignof(std::max_align_t) );
```
| | (since C++20) |
Deallocates the storage pointed to by `p`, which must have been allocated from a `[std::pmr::memory\_resource](../memory_resource "cpp/memory/memory resource")` `x` that compares equal to `*resource()`. using `x.allocate(nbytes, alignment)`, typically through a call to `allocate_bytes(nbytes, alignment)`.
Equivalent to `resource()->deallocate(p, nbytes, alignment);`
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to memory to deallocate |
| nbytes | - | the number of bytes originally allocated |
| alignment | - | the alignment originally allocated |
### Exceptions
Throws nothing.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization.
### See also
| | |
| --- | --- |
| [deallocate\_object](deallocate_object "cpp/memory/polymorphic allocator/deallocate object")
(C++20) | Frees raw memory obtained by allocate\_object (public member function) |
| [delete\_object](delete_object "cpp/memory/polymorphic allocator/delete object")
(C++20) | Destroys and deallocates an object (public member function) |
| [deallocate](../allocator_traits/deallocate "cpp/memory/allocator traits/deallocate")
[static] | deallocates storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [deallocate](../memory_resource/deallocate "cpp/memory/memory resource/deallocate") | deallocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>:: select_on_container_copy_construction std::pmr::polymorphic\_allocator<T>:: select\_on\_container\_copy\_construction
===============================================================================
| | | |
| --- | --- | --- |
|
```
polymorphic_allocator select_on_container_copy_construction() const;
```
| | (since C++17) |
Returns a default-constructed `polymorphic_allocator` object.
### Parameters
(none).
### Return value
A default-constructed `polymorphic_allocator` object.
### Notes
`polymorphic_allocator`s do not propagate on container copy construction.
### See also
| | |
| --- | --- |
| [select\_on\_container\_copy\_construction](../allocator_traits/select_on_container_copy_construction "cpp/memory/allocator traits/select on container copy construction")
[static] | obtains the allocator to use after copying a standard container (public static member function of `std::allocator_traits<Alloc>`) |
cpp std::pmr::polymorphic_allocator<T>::new_object std::pmr::polymorphic\_allocator<T>::new\_object
================================================
| | | |
| --- | --- | --- |
|
```
template< class U, class... CtorArgs >
[[nodiscard]] U* new_object( CtorArgs&&... ctor_args );
```
| | (since C++20) |
Allocates and constructs an object of type `U`.
Given `alloc` is a `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<T>`:
```
U* p = alloc.new_object<U>(std::forward<CtorArgs>(ctor_args)...);
```
is equivalent to.
```
U* p = alloc.allocate_object<U>();
try {
alloc.construct(p, std::forward<CtorArgs>(ctor_args)...);
} catch (...) {
alloc.deallocate_object(p);
throw;
}
```
### Parameters
| | | |
| --- | --- | --- |
| ctor\_args | - | the arguments to forward to the constructor of `U` |
### Return value
A pointer to the allocated and constructed object.
### Notes
This function was introduced for use with the fully-specialized allocator `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<>`, but it may be useful in any specialization as a shortcut to avoid having to rebind from `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<T>` to `[std::pmr::polymorphic\_allocator](http://en.cppreference.com/w/cpp/memory/polymorphic_allocator)<U>`, and having to call `allocate`, `construct`, and `deallocate` individually.
Since `U` is not deduced, it must be provided as a template argument when calling this function.
### Exceptions
May throw any exceptions thrown by the call to `allocate_object` or the constructor of `U`.
### See also
| | |
| --- | --- |
| [allocate\_bytes](allocate_bytes "cpp/memory/polymorphic allocator/allocate bytes")
(C++20) | Allocate raw aligned memory from the underlying resource (public member function) |
| [allocate\_object](allocate_object "cpp/memory/polymorphic allocator/allocate object")
(C++20) | Allocates raw memory suitable for an object or an array (public member function) |
| [allocate](allocate "cpp/memory/polymorphic allocator/allocate") | Allocate memory (public member function) |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::pmr::polymorphic_allocator<T>::allocate std::pmr::polymorphic\_allocator<T>::allocate
=============================================
| | | |
| --- | --- | --- |
|
```
T* allocate( std::size_t n );
```
| | (since C++17) (until C++20) |
|
```
[[nodiscard]] T* allocate( std::size_t n );
```
| | (since C++20) |
Allocates storage for `n` objects of type `T` using the underlying memory resource. Equivalent to `return static_cast<T*>(resource()->allocate(n * sizeof(T), alignof(T)));`.
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of objects to allocate storage for |
### Return value
A pointer to the allocated storage.
### Exceptions
Throws `[std::bad\_array\_new\_length](../new/bad_array_new_length "cpp/memory/new/bad array new length")` if `n > [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>::max() / sizeof(T)`; may also throw any exceptions thrown by the call to `resource()->allocate`.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3038](https://cplusplus.github.io/LWG/issue3038) | C++17 | `allocate` might allocate storage of wrong size | throws `length_error` instead |
| [LWG 3237](https://cplusplus.github.io/LWG/issue3237) | C++17 | the exception thrown by `allocate` was inconsistent with `std::allocator::allocate` | made consistent |
### See also
| | |
| --- | --- |
| [allocate\_bytes](allocate_bytes "cpp/memory/polymorphic allocator/allocate bytes")
(C++20) | Allocate raw aligned memory from the underlying resource (public member function) |
| [allocate\_object](allocate_object "cpp/memory/polymorphic allocator/allocate object")
(C++20) | Allocates raw memory suitable for an object or an array (public member function) |
| [new\_object](new_object "cpp/memory/polymorphic allocator/new object")
(C++20) | Allocates and constructs an object (public member function) |
| [allocate](../allocator_traits/allocate "cpp/memory/allocator traits/allocate")
[static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) |
| [allocate](../memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) |
cpp std::malloc std::malloc
===========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void* malloc( std::size_t size );
```
| | |
Allocates `size` bytes of uninitialized storage.
If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any scalar type (at least as strictly as `[std::max\_align\_t](../../types/max_align_t "cpp/types/max align t")`).
If `size` is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage, but has to be passed to `[std::free](free "cpp/memory/c/free")`).
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* `[std::calloc](calloc "cpp/memory/c/calloc")`, `std::malloc`, `[std::realloc](realloc "cpp/memory/c/realloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `[std::free](free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| size | - | number of bytes to allocate |
### Return value
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[std::free()](free "cpp/memory/c/free")` or `[std::realloc()](realloc "cpp/memory/c/realloc")`.
On failure, returns a null pointer.
### Notes
This function does not call constructors or initialize memory in any way. There are no ready-to-use smart pointers that could guarantee that the matching deallocation function is called. The preferred method of memory allocation in C++ is using RAII-ready functions `[std::make\_unique](../unique_ptr/make_unique "cpp/memory/unique ptr/make unique")`, `[std::make\_shared](../shared_ptr/make_shared "cpp/memory/shared ptr/make shared")`, container constructors, etc, and, in low-level library code, [new-expression](../../language/new "cpp/language/new").
For loading a large file, file mapping via OS-specific functions, e.g. [`mmap`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html) on POSIX or `CreateFileMapping`([`A`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga)/[`W`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-createfilemappingw)) along with [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile) on Windows, is preferable to allocating a buffer for file reading.
### Example
```
#include <iostream>
#include <cstdlib>
#include <string>
#include <memory>
int main()
{
constexpr std::size_t size = 4;
if (auto ptr = reinterpret_cast<std::string*>(
std::malloc(size * sizeof(std::string))))
{ try
{ for (std::size_t i = 0; i < size; ++i)
std::construct_at(ptr + i, 5, 'a' + i);
for (std::size_t i = 0; i < size; ++i)
std::cout << "ptr[" << i << "] == " << ptr[i] << '\n';
std::destroy_n(ptr, size);
}
catch(...) {}
std::free(ptr);
}
}
```
Output:
```
p[0] == aaaaa
p[1] == bbbbb
p[2] == ccccc
p[3] == ddddd
```
### See also
| | |
| --- | --- |
| [operator newoperator new[]](../new/operator_new "cpp/memory/new/operator new") | allocation functions (function) |
| [get\_temporary\_buffer](../get_temporary_buffer "cpp/memory/get temporary buffer")
(deprecated in C++17)(removed in C++20) | obtains uninitialized storage (function template) |
| [C documentation](https://en.cppreference.com/w/c/memory/malloc "c/memory/malloc") for `malloc` |
cpp std::free std::free
=========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void free( void* ptr );
```
| | |
Deallocates the space previously allocated by `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), or `[std::realloc](realloc "cpp/memory/c/realloc")`.
If `ptr` is a null pointer, the function does nothing.
The behavior is undefined if the value of `ptr` does not equal a value returned earlier by `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), or `[std::realloc](realloc "cpp/memory/c/realloc")`.
The behavior is undefined if the memory area referred to by `ptr` has already been deallocated, that is, `std::free` or `[std::realloc](realloc "cpp/memory/c/realloc")` has already been called with `ptr` as the argument and no calls to `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), or `[std::realloc](realloc "cpp/memory/c/realloc")` resulted in a pointer equal to `ptr` afterwards.
The behavior is undefined if after `std::free` returns, an access is made through the pointer `ptr` (unless another allocation function happened to result in a pointer value equal to `ptr`).
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::realloc](realloc "cpp/memory/c/realloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `std::free`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to the memory to deallocate |
### Return value
(none).
### Notes
The function accepts (and does nothing with) the null pointer to reduce the amount of special-casing. Whether allocation succeeds or not, the pointer returned by an allocation function can be passed to `std::free`.
### Example
```
#include <cstdlib>
int main()
{
int* p1 = (int*)std::malloc(10*sizeof *p1);
std::free(p1); // every allocated pointer must be freed
int* p2 = (int*)std::calloc(10, sizeof *p2);
int* p3 = (int*)std::realloc(p2, 1000*sizeof *p3);
if(!p3) // p3 null means realloc failed and p2 must be freed.
std::free(p2);
std::free(p3); // p3 can be freed whether or not it is null.
}
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/memory/free "c/memory/free") for `free` |
| programming_docs |
cpp std::realloc std::realloc
============
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void* realloc( void* ptr, std::size_t new_size );
```
| | |
Reallocates the given area of memory. It must be previously allocated by `[std::malloc()](malloc "cpp/memory/c/malloc")`, `[std::calloc()](calloc "cpp/memory/c/calloc")` or `std::realloc()` and not yet freed with `[std::free()](free "cpp/memory/c/free")`, otherwise, the results are undefined.
The reallocation is done by either:
a) expanding or contracting the existing area pointed to by `ptr`, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined.
b) allocating a new memory block of size `new_size` bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block. If there is not enough memory, the old memory block is not freed and null pointer is returned.
If `ptr` is a null pointer, the behavior is the same as calling `[std::malloc](malloc "cpp/memory/c/malloc")`(`new_size`).
If `new_size` is zero, the behavior is implementation defined: null pointer may be returned (in which case the old memory block may or may not be freed) or some non-null pointer may be returned that may not be used to access storage. Such usage is deprecated (via [C DR 400](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_400)). (since C++20).
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::malloc](malloc "cpp/memory/c/malloc")`, `std::realloc`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `[std::free](free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to the memory area to be reallocated |
| new\_size | - | new size of the array |
### Return value
On success, returns a pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[std::free()](free "cpp/memory/c/free")`, the original pointer `ptr` is invalidated and any access to it is [undefined behavior](../../language/ub "cpp/language/ub") (even if reallocation was in-place).
On failure, returns a null pointer. The original pointer `ptr` remains valid and may need to be deallocated with `[std::free()](free "cpp/memory/c/free")`.
### Notes
Because reallocation may involve bytewise copying (regardless of whether it's to expand or to contract), only the objects of [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") types are safe to access in the preserved part of the memory block after a call to `realloc`.
Some non-standard libraries define a type trait "BitwiseMovable" or "Relocatable", which describes a type that doesn't have:
* external references (e.g. nodes of a list or a tree that holds reference to another element), and
* internal references (e.g. member pointer which might hold the address of another member).
Objects of such type can be accessed after their storage is reallocated even if their copy constructors are not trivial.
### Example
```
#include <cstdlib>
#include <new>
#include <cassert>
class MallocDynamicBuffer
{
char* p;
public:
explicit MallocDynamicBuffer(std::size_t initial = 0) : p(nullptr) {
resize(initial);
}
~MallocDynamicBuffer() { std::free(p); }
void resize(std::size_t newSize) {
if(newSize == 0) { // this check is not strictly needed,
std::free(p); // but zero-size realloc is deprecated in C
p = nullptr;
} else {
if(void* mem = std::realloc(p, newSize))
p = static_cast<char*>(mem);
else
throw std::bad_alloc();
}
}
char& operator[](size_t n) { return p[n]; }
char operator[](size_t n) const { return p[n]; }
};
int main()
{
MallocDynamicBuffer buf1(1024);
buf1[5] = 'f';
buf1.resize(10); // shrink
assert(buf1[5] == 'f');
buf1.resize(1024); // grow
assert(buf1[5] == 'f');
}
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/memory/realloc "c/memory/realloc") for `realloc` |
cpp std::aligned_alloc std::aligned\_alloc
===================
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void* aligned_alloc( std::size_t alignment, std::size_t size );
```
| | (since C++17) |
Allocate `size` bytes of uninitialized storage whose alignment is specified by `alignment`. The `size` parameter must be an integral multiple of `alignment`.
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* `[std::calloc](calloc "cpp/memory/c/calloc")`, `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::realloc](realloc "cpp/memory/c/realloc")`, `std::aligned_alloc` (since C++17), `[std::free](free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| alignment | - | specifies the alignment. Must be a valid alignment supported by the implementation. |
| size | - | number of bytes to allocate. An integral multiple of `alignment` |
### Return value
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[std::free()](free "cpp/memory/c/free")` or `[std::realloc()](realloc "cpp/memory/c/realloc")`.
On failure, returns a null pointer.
### Notes
Passing a `size` which is not an integral multiple of `alignment` or an `alignment` which is not valid or not supported by the implementation causes the function to fail and return a null pointer (C11, as published, specified undefined behavior in this case, this was corrected by DR 460).
As an example of the "supported by the implementation" requirement, POSIX function [posix\_memalign](http://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html) accepts any `alignment` that is a power of two and a multiple of `sizeof(void*)`, and POSIX-based implementations of `aligned_alloc` inherit this requirements.
Regular `[std::malloc](malloc "cpp/memory/c/malloc")` aligns memory suitable for any object type (which, in practice, means that it is aligned to `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))`). This function is useful for over-aligned allocations, such as to SSE, cache line, or VM page boundary.
### Example
```
#include <cstdio>
#include <cstdlib>
int main()
{
int* p1 = static_cast<int*>(std::malloc(10*sizeof *p1));
std::printf("default-aligned address: %p\n", static_cast<void*>(p1));
std::free(p1);
int* p2 = static_cast<int*>(std::aligned_alloc(1024, 1024));
std::printf("1024-byte aligned address: %p\n", static_cast<void*>(p2));
std::free(p2);
}
```
Possible output:
```
default-aligned address: 0x2221c20
1024-byte aligned address: 0x2222400
```
### See also
| | |
| --- | --- |
| [aligned\_storage](../../types/aligned_storage "cpp/types/aligned storage")
(C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) |
| [C documentation](https://en.cppreference.com/w/c/memory/aligned_alloc "c/memory/aligned alloc") for `aligned_alloc` |
cpp std::calloc std::calloc
===========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void* calloc( std::size_t num, std::size_t size );
```
| | |
Allocates memory for an array of `num` objects of size `size` and initializes it to all bits zero.
If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type.
If `size` is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage).
| | |
| --- | --- |
| The following functions are required to be thread-safe:* The library versions of [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* User replacement versions of global [`operator new`](../new/operator_new "cpp/memory/new/operator new") and [`operator delete`](../new/operator_delete "cpp/memory/new/operator delete")
* `std::calloc`, `[std::malloc](malloc "cpp/memory/c/malloc")`, `[std::realloc](realloc "cpp/memory/c/realloc")`, `[std::aligned\_alloc](aligned_alloc "cpp/memory/c/aligned alloc")` (since C++17), `[std::free](free "cpp/memory/c/free")`
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call [happens-before](../../atomic/memory_order "cpp/atomic/memory order") the next allocation (if any) in this order. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| num | - | number of objects |
| size | - | size of each object |
### Return value
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[std::free()](free "cpp/memory/c/free")` or `[std::realloc()](realloc "cpp/memory/c/realloc")`.
On failure, returns a null pointer.
### Notes
Due to the alignment requirements, the number of allocated bytes is not necessarily equal to `num*size`.
Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms).
Originally (in C89), support for zero size was added to accommodate code such as.
```
OBJ *p = calloc(0, sizeof(OBJ)); // "zero-length" placeholder
...
while(1) {
p = realloc(p, c * sizeof(OBJ)); // reallocations until size settles
... // code that may change c or break out of loop
}
```
### Example
```
#include <iostream>
#include <cstdlib>
int main()
{
int* p1 = (int*)std::calloc(4, sizeof(int)); // allocate and zero out an array of 4 int
int* p2 = (int*)std::calloc(1, sizeof(int[4])); // same, naming the array type directly
int* p3 = (int*)std::calloc(4, sizeof *p3); // same, without repeating the type name
if(p2)
for(int n=0; n<4; ++n) // print the array
std::cout << "p2[" << n << "] == " << p2[n] << '\n';
std::free(p1);
std::free(p2);
std::free(p3);
}
```
Output:
```
p2[0] == 0
p2[1] == 0
p2[2] == 0
p2[3] == 0
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/memory/calloc "c/memory/calloc") for `calloc` |
cpp std::coroutine_handle, std::noop_coroutine_handle std::coroutine\_handle, std::noop\_coroutine\_handle
====================================================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
template< class Promise = void > struct coroutine_handle;
```
| (1) | (since C++20) |
|
```
template<> struct coroutine_handle<void>;
```
| (2) | (since C++20) |
|
```
template<> struct coroutine_handle<std::noop_coroutine_promise>;
```
| (3) | (since C++20) |
|
```
using noop_coroutine_handle =
std::coroutine_handle<std::noop_coroutine_promise>;
```
| (4) | (since C++20) |
The class template `coroutine_handle` can be used to refer to a suspended or executing coroutine. Every specialization of `coroutine_handle` is a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType").
1) Primary template, can be created from the promise object of type `Promise`.
2) Specialization `std::coroutine_handle<void>` erases the promise type. It is convertible from other specializations.
3) Specialization `std::coroutine\_handle<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>` refers to no-op coroutines. It cannot be created from a promise object. On typical implementations, every specialization of `std::coroutine_handle` is [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), and holds a pointer to the coroutine state as its only non-static data member.
The behavior of a program that adds specializations for `coroutine_handle` is undefined.
### Member functions
| | |
| --- | --- |
| [(constructor)](coroutine_handle/coroutine_handle "cpp/coroutine/coroutine handle/coroutine handle")
(C++20) | constructs a `coroutine_handle` object (public member function) |
| [operator=](coroutine_handle/operator= "cpp/coroutine/coroutine handle/operator=")
(C++20) | assigns the `coroutine_handle` object (public member function) |
| Conversion |
| [operator coroutine\_handle<>](coroutine_handle/operator_coroutine_handle_void "cpp/coroutine/coroutine handle/operator coroutine handle void")
(C++20) | obtains a type-erased `coroutine_handle` (public member function) |
| Observers |
| [done](coroutine_handle/done "cpp/coroutine/coroutine handle/done")
(C++20) | checks if the coroutine has completed (public member function) |
| [operator bool](coroutine_handle/operator_bool "cpp/coroutine/coroutine handle/operator bool")
(C++20) | checks if the handle represents a coroutine (public member function) |
| Control |
| [operator()resume](coroutine_handle/resume "cpp/coroutine/coroutine handle/resume")
(C++20) | resumes execution of the coroutine (public member function) |
| [destroy](coroutine_handle/destroy "cpp/coroutine/coroutine handle/destroy")
(C++20) | destroys a coroutine (public member function) |
| Promise Access |
| [promise](coroutine_handle/promise "cpp/coroutine/coroutine handle/promise")
(C++20) | access the promise of a coroutine (public member function) |
| [from\_promise](coroutine_handle/from_promise "cpp/coroutine/coroutine handle/from promise")
[static] (C++20) | creates a `coroutine_handle` from the promise object of a coroutine (public static member function) |
| Export/Import |
| [address](coroutine_handle/address "cpp/coroutine/coroutine handle/address")
(C++20) | exports the underlying address, i.e. the pointer backing the coroutine (public member function) |
| [from\_address](coroutine_handle/from_address "cpp/coroutine/coroutine handle/from address")
[static] (C++20) | imports a coroutine from a pointer (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<=>](coroutine_handle/operator_cmp "cpp/coroutine/coroutine handle/operator cmp")
(C++20) | compares two `coroutine_handle` objects (function) |
### Helper classes
| | |
| --- | --- |
| [std::hash<std::coroutine\_handle>](coroutine_handle/hash "cpp/coroutine/coroutine handle/hash")
(C++20) | hash support for `std::coroutine_handle` (class template specialization) |
### Notes
A `coroutine_handle` may be dangling, in which case the `coroutine_handle` must be used carefully in order to avoid undefined behavior.
### Example
```
#include <coroutine>
#include <iostream>
#include <optional>
template<std::movable T>
class Generator {
public:
struct promise_type {
Generator<T> get_return_object() {
return Generator{Handle::from_promise(*this)};
}
static std::suspend_always initial_suspend() noexcept {
return {};
}
static std::suspend_always final_suspend() noexcept {
return {};
}
std::suspend_always yield_value(T value) noexcept {
current_value = std::move(value);
return {};
}
// Disallow co_await in generator coroutines.
void await_transform() = delete;
[[noreturn]]
static void unhandled_exception() {
throw;
}
std::optional<T> current_value;
};
using Handle = std::coroutine_handle<promise_type>;
explicit Generator(const Handle coroutine) :
m_coroutine{coroutine}
{}
Generator() = default;
~Generator() {
if (m_coroutine) {
m_coroutine.destroy();
}
}
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
Generator(Generator&& other) noexcept :
m_coroutine{other.m_coroutine}
{
other.m_coroutine = {};
}
Generator& operator=(Generator&& other) noexcept {
if (this != &other) {
if (m_coroutine) {
m_coroutine.destroy();
}
m_coroutine = other.m_coroutine;
other.m_coroutine = {};
}
return *this;
}
// Range-based for loop support.
class Iter {
public:
void operator++() {
m_coroutine.resume();
}
const T& operator*() const {
return *m_coroutine.promise().current_value;
}
bool operator==(std::default_sentinel_t) const {
return !m_coroutine || m_coroutine.done();
}
explicit Iter(const Handle coroutine) :
m_coroutine{coroutine}
{}
private:
Handle m_coroutine;
};
Iter begin() {
if (m_coroutine) {
m_coroutine.resume();
}
return Iter{m_coroutine};
}
std::default_sentinel_t end() {
return {};
}
private:
Handle m_coroutine;
};
template<std::integral T>
Generator<T> range(T first, const T last) {
while (first < last) {
co_yield first++;
}
}
int main() {
for (const char i : range(65, 91)) {
std::cout << i << ' ';
}
std::cout << '\n';
}
```
Output:
```
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 3460](https://cplusplus.github.io/LWG/issue3460) | C++20 | the public base class of `coroutine_handle` could leave it in an undesired state | inheritance removed |
cpp std::noop_coroutine_promise std::noop\_coroutine\_promise
=============================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
struct noop_coroutine_promise {};
```
| | (since C++20) |
`noop_coroutine_promise` is the promise type of no-op coroutines.
A no-op coroutine behaves as if it.
* does nothing other than the control flow of a coroutine, and
* is suspended immediately after beginning and resumption, and
* has a coroutine state such that destroying the state is no-op, and
* never reaches its final suspended point if there is any `[std::coroutine\_handle](coroutine_handle "cpp/coroutine/coroutine handle")` referring to it.
No-op coroutines can be started by `[std::noop\_coroutine](noop_coroutine "cpp/coroutine/noop coroutine")`, and controlled by the coroutine handle it returns. The returned coroutine handle is of type `[std::noop\_coroutine\_handle](coroutine_handle "cpp/coroutine/coroutine handle")`, which is a synonym for `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<std::noop\_coroutine\_promise>`.
Some operations of a no-op coroutines are determined no-op at compile time through the type `std::noop_coroutine_handle`.
### Example
### See also
| | |
| --- | --- |
| [noop\_coroutine](noop_coroutine "cpp/coroutine/noop coroutine")
(C++20) | creates a coroutine handle that has no observable effects when resumed or destroyed (function) |
| [noop\_coroutine\_handle](coroutine_handle "cpp/coroutine/coroutine handle")
(C++20) | `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<std::noop\_coroutine\_promise>`, intended to refer to a no-op coroutine (typedef) |
| programming_docs |
cpp std::suspend_always std::suspend\_always
====================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
struct suspend_always;
```
| | (since C++20) |
`suspend_always` is an empty class which can be used to indicate that an [await expression](../language/coroutines#co_await "cpp/language/coroutines") always suspends and does not produce a value.
### Member functions
| | |
| --- | --- |
| await\_ready
(C++20) | indicates that an await expression always suspends (public member function) |
| await\_suspend
(C++20) | no-op (public member function) |
| await\_resume
(C++20) | no-op (public member function) |
std::suspend\_always::await\_ready
-----------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr bool await_ready() const noexcept { return false; }
```
| | (since C++20) |
Always returns `false`, indicating that an await expression always suspends.
std::suspend\_always::await\_suspend
-------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr void await_suspend(std::coroutine_handle<>) const noexcept {}
```
| | (since C++20) |
Does nothing.
std::suspend\_always::await\_resume
------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr void await_resume() const noexcept {}
```
| | (since C++20) |
Does nothing. An await expression does not produce a value if `suspend_always` is used.
### Example
### See also
| | |
| --- | --- |
| [suspend\_never](suspend_never "cpp/coroutine/suspend never")
(C++20) | indicates that an await-expression should never suspend (class) |
cpp std::noop_coroutine std::noop\_coroutine
====================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
std::noop_coroutine_handle noop_coroutine() noexcept;
```
| | (since C++20) |
Returns a coroutine handle referring to a no-op coroutine.
If there has been already a coroutine state of no-op coroutine, it is unspecified whether a subsequent call to `noop_coroutine` returns a previously obtained coroutine handle, or a coroutine handle referring to a new coroutine state of no-op coroutine.
### Parameters
(none).
### Return value
A `[std::noop\_coroutine\_handle](coroutine_handle "cpp/coroutine/coroutine handle")` referring to a no-op coroutine.
### Notes
Return values from different calls to `noop_coroutine` may and may not compare equal.
`noop_coroutine` may only return a `noop_coroutine_handle` referring to a coroutine state object without starting a coroutine.
### Example
```
#include <coroutine>
#include <utility>
#include <iostream>
template<class T>
struct task {
struct promise_type {
auto get_return_object() {
return task(std::coroutine_handle<promise_type>::from_promise(*this));
}
std::suspend_always initial_suspend() { return {}; }
struct final_awaiter {
bool await_ready() noexcept { return false; }
void await_resume() noexcept {}
std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> h) noexcept {
// final_awaiter::await_suspend is called when the execution of the
// current coroutine (referred to by 'h') is about to finish.
// If the current coroutine was resumed by another coroutine via
// co_await get_task(), a handle to that coroutine has been stored
// as h.promise().previous. In that case, return the handle to resume
// the previous coroutine.
// Otherwise, return noop_coroutine(), whose resumption does nothing.
auto previous = h.promise().previous;
if (previous) {
return previous;
} else {
return std::noop_coroutine();
}
}
};
final_awaiter final_suspend() noexcept { return {}; }
void unhandled_exception() { throw; }
void return_value(T value) { result = std::move(value); }
T result;
std::coroutine_handle<> previous;
};
task(std::coroutine_handle<promise_type> h) : coro(h) {}
task(task&& t) = delete;
~task() { coro.destroy(); }
struct awaiter {
bool await_ready() { return false; }
T await_resume() { return std::move(coro.promise().result); }
auto await_suspend(std::coroutine_handle<> h) {
coro.promise().previous = h;
return coro;
}
std::coroutine_handle<promise_type> coro;
};
awaiter operator co_await() { return awaiter{coro}; }
T operator()() {
coro.resume();
return std::move(coro.promise().result);
}
private:
std::coroutine_handle<promise_type> coro;
};
task<int> get_random() {
std::cout << "in get_random()\n";
co_return 4;
}
task<int> test() {
task<int> v = get_random();
task<int> u = get_random();
std::cout << "in test()\n";
int x = (co_await v + co_await u);
co_return x;
}
int main() {
task<int> t = test();
int result = t();
std::cout << result << '\n';
}
```
Output:
```
in test()
in get_random()
in get_random()
8
```
### See also
| | |
| --- | --- |
| [noop\_coroutine\_promise](noop_coroutine_promise "cpp/coroutine/noop coroutine promise")
(C++20) | used for coroutines with no observable effects (class) |
| [noop\_coroutine\_handle](coroutine_handle "cpp/coroutine/coroutine handle")
(C++20) | `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`, intended to refer to a no-op coroutine (typedef) |
cpp std::coroutine_traits std::coroutine\_traits
======================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
template< class R, class... Args >
struct coroutine_traits;
```
| | (since C++20) |
Determines the promise type from the return type and parameter types of a coroutine. The standard library implementation provides a publicly accessible member type `promise_type` same as `R::promise_type` if the qualified-id is valid and denotes a type. Otherwise, it has no such member.
Program-defined specializations of `coroutine_traits` shall define a publicly accessible member type `promise_type`; otherwise, the behavior is undefined.
### Template parameters
| | | |
| --- | --- | --- |
| R | - | return type of the coroutine |
| Args | - | parameter types of the coroutine, including the [implicit object parameter](../language/member_functions#ref-qualified_member_functions "cpp/language/member functions") if the coroutine is a non-static member function |
### Member types
| Type | Definition |
| --- | --- |
| `promise_type` | `R::promise_type` if it is valid, or provided by program-defined specializations |
### Possible implementation
| |
| --- |
|
```
template<class, class...>
struct coroutine_traits {};
template<class R, class... Args>
requires requires { typename R::promise_type; }
struct coroutine_traits<R, Args...> {
using promise_type = typename R::promise_type;
};
```
|
### Notes
If the coroutine is a non-static member function, then the first type in `Args...` is the type of the implicit object parameter, and the rest are parameter types of the function (if any).
If `std::coroutine_traits<R, Args...>::promise_type` does not exist or is not a class type, the corresponding coroutine definition is ill-formed.
Users may define explicit or partial specializations of `coroutine_traits` dependent on program-defined types to avoid modification to return types.
### Example
```
#include <chrono>
#include <coroutine>
#include <exception>
#include <future>
#include <iostream>
#include <thread>
#include <type_traits>
// A program-defined type on which the coroutine_traits specializations below depend
struct as_coroutine {};
// Enable the use of std::future<T> as a coroutine type
// by using a std::promise<T> as the promise type.
template <typename T, typename... Args>
requires(!std::is_void_v<T> && !std::is_reference_v<T>)
struct std::coroutine_traits<std::future<T>, as_coroutine, Args...> {
struct promise_type : std::promise<T> {
std::future<T> get_return_object() noexcept {
return this->get_future();
}
std::suspend_never initial_suspend() const noexcept { return {}; }
std::suspend_never final_suspend() const noexcept { return {}; }
void return_value(const T &value)
noexcept(std::is_nothrow_copy_constructible_v<T>) {
this->set_value(value);
}
void return_value(T &&value)
noexcept(std::is_nothrow_move_constructible_v<T>) {
this->set_value(std::move(value));
}
void unhandled_exception() noexcept {
this->set_exception(std::current_exception());
}
};
};
// Same for std::future<void>.
template <typename... Args>
struct std::coroutine_traits<std::future<void>, as_coroutine, Args...> {
struct promise_type : std::promise<void> {
std::future<void> get_return_object() noexcept {
return this->get_future();
}
std::suspend_never initial_suspend() const noexcept { return {}; }
std::suspend_never final_suspend() const noexcept { return {}; }
void return_void() noexcept {
this->set_value();
}
void unhandled_exception() noexcept {
this->set_exception(std::current_exception());
}
};
};
// Allow co_await'ing std::future<T> and std::future<void>
// by naively spawning a new thread for each co_await.
template <typename T>
auto operator co_await(std::future<T> future) noexcept
requires(!std::is_reference_v<T>) {
struct awaiter : std::future<T> {
bool await_ready() const noexcept {
using namespace std::chrono_literals;
return this->wait_for(0s) != std::future_status::timeout;
}
void await_suspend(std::coroutine_handle<> cont) const {
std::thread([this, cont] {
this->wait();
cont();
}).detach();
}
T await_resume() { return this->get(); }
};
return awaiter{std::move(future)};
}
// Utilize the infrastructure we have established.
std::future<int> compute(as_coroutine) {
int a = co_await std::async([] { return 6; });
int b = co_await std::async([] { return 7; });
co_return a * b;
}
std::future<void> fail(as_coroutine) {
throw std::runtime_error("bleah");
co_return;
}
int main() {
std::cout << compute({}).get() << '\n';
try {
fail({}).get();
} catch (const std::runtime_error &e) {
std::cout << "error: " << e.what() << '\n';
}
}
```
Output:
```
42
error: bleah
```
cpp std::suspend_never std::suspend\_never
===================
| Defined in header `[<coroutine>](../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
struct suspend_never;
```
| | (since C++20) |
`suspend_never` is an empty class which can be used to indicate that an [await expression](../language/coroutines#co_await "cpp/language/coroutines") never suspends and does not produce a value.
### Member functions
| | |
| --- | --- |
| await\_ready
(C++20) | indicates that an await expression never suspends (public member function) |
| await\_suspend
(C++20) | no-op (public member function) |
| await\_resume
(C++20) | no-op (public member function) |
std::suspend\_never::await\_ready
----------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr bool await_ready() const noexcept { return true; }
```
| | (since C++20) |
Always returns `true`, indicating that an await expression never suspends.
std::suspend\_never::await\_suspend
------------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr void await_suspend(std::coroutine_handle<>) const noexcept {}
```
| | (since C++20) |
Does nothing.
std::suspend\_never::await\_resume
-----------------------------------
| | | |
| --- | --- | --- |
|
```
constexpr void await_resume() const noexcept {}
```
| | (since C++20) |
Does nothing. An await expression does not produce a value if `suspend_never` is used.
### Example
### See also
| | |
| --- | --- |
| [suspend\_always](suspend_always "cpp/coroutine/suspend always")
(C++20) | indicates that an await-expression should always suspend (class) |
cpp std::coroutine_handle<Promise>::operator(), std::coroutine_handle<Promise>::resume std::coroutine\_handle<Promise>::operator(), std::coroutine\_handle<Promise>::resume
====================================================================================
| | | |
| --- | --- | --- |
| Member of other specializations | | |
|
```
void operator()() const;
void resume() const;
```
| (1) | (since C++20) |
| Member of specialization `std::coroutine_handle<std::noop_coroutine_promise>` | | |
|
```
constexpr void operator()() const noexcept;
constexpr void resume() const noexcept;
```
| (2) | (since C++20) |
1) Resumes the execution of the coroutine to which `*this` refers, or does nothing if the coroutine is a no-op coroutine.
2) Does nothing. The behavior is undefined if `*this` does not refer to suspended coroutine, or the coroutine is not a no-op coroutine and suspended at its final suspend point. A concurrent resumption of the coroutine may result in a data race.
Resumption of a coroutine on an execution agent other than the one on which it was suspended has implementation-defined behavior unless each execution agent either is a thread represented by `[std::thread](../../thread/thread "cpp/thread/thread")` or `[std::jthread](../../thread/jthread "cpp/thread/jthread")`, or is the thread executing `main`.
### Parameters
(none).
### Return value
(none).
### Exceptions
If an exception is thrown from the execution of the coroutine, the exception is caught and `unhandled_exception` is called on the coroutine's promise object. If the call to `unhandled_exception` throws or rethrows an exception, that exception is propagated.
### Notes
A coroutine that is resumed on a different execution agent should avoid relying on consistent thread identity throughout, such as holding a mutex object across a suspend point.
### Example
### See also
| | |
| --- | --- |
| [destroy](destroy "cpp/coroutine/coroutine handle/destroy")
(C++20) | destroys a coroutine (public member function) |
cpp std::coroutine_handle<Promise>::from_promise std::coroutine\_handle<Promise>::from\_promise
==============================================
| | | |
| --- | --- | --- |
|
```
static coroutine_handle from_promise( Promise& p );
```
| | (since C++20) |
Creates a `coroutine_handle` from the promise object of a coroutine. The created `coroutine_handle` refers the coroutine, and `promise()` returns a reference to `p`.
The behavior is undefined if `p` is not a reference to a promise object. This function is only provided for the primary template, i.e. specializations `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>` and `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>` do not have this function.
### Parameters
| | | |
| --- | --- | --- |
| p | - | promise object of a coroutine to refer |
### Return value
A `coroutine_handle` referring the given coroutine.
### Example
### See also
| | |
| --- | --- |
| [(constructor)](coroutine_handle "cpp/coroutine/coroutine handle/coroutine handle")
(C++20) | constructs a `coroutine_handle` object (public member function) |
| [from\_address](from_address "cpp/coroutine/coroutine handle/from address")
[static] (C++20) | imports a coroutine from a pointer (public static member function) |
| [noop\_coroutine](../noop_coroutine "cpp/coroutine/noop coroutine")
(C++20) | creates a coroutine handle that has no observable effects when resumed or destroyed (function) |
cpp std::coroutine_handle<Promise>::coroutine_handle std::coroutine\_handle<Promise>::coroutine\_handle
==================================================
| | | |
| --- | --- | --- |
|
```
constexpr coroutine_handle() noexcept;
```
| (1) | (since C++20) |
|
```
constexpr coroutine_handle( std::nullptr_t ) noexcept;
```
| (2) | (since C++20) |
|
```
coroutine_handle( const coroutine_handle& other ) = default;
```
| (3) | (since C++20) |
|
```
coroutine_handle( coroutine_handle&& other ) = default;
```
| (4) | (since C++20) |
Creates a `coroutine_handle` that does not refer a coroutine, or copies a `coroutine_handle`.
1-2) Initializes the underlying address to `nullptr`. After construction, `address()` returns `nullptr`, and the `coroutine_handle` does not refer a coroutine. These constructors are not declared for the specialization `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`.
3-4) Copies the underlying address. The copy constructor and move constructor are equivalent to implicitly declared ones. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another `coroutine_handle` to copy |
### Notes
`[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>` is neither default constructible nor constructible from `[std::nullptr\_t](../../types/nullptr_t "cpp/types/nullptr t")`. `[std::noop\_coroutine](../noop_coroutine "cpp/coroutine/noop coroutine")` can be used to create a new `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`.
Static member functions `from_promise` and `from_address` can also create a `coroutine_handle`.
### See also
| | |
| --- | --- |
| [from\_promise](from_promise "cpp/coroutine/coroutine handle/from promise")
[static] (C++20) | creates a `coroutine_handle` from the promise object of a coroutine (public static member function) |
| [from\_address](from_address "cpp/coroutine/coroutine handle/from address")
[static] (C++20) | imports a coroutine from a pointer (public static member function) |
| [noop\_coroutine](../noop_coroutine "cpp/coroutine/noop coroutine")
(C++20) | creates a coroutine handle that has no observable effects when resumed or destroyed (function) |
cpp std::coroutine_handle<Promise>::from_address std::coroutine\_handle<Promise>::from\_address
==============================================
| | | |
| --- | --- | --- |
|
```
static constexpr coroutine_handle from_address( void *addr );
```
| | (since C++20) |
Creates a `coroutine_handle` from a null pointer value or an underlying address of another `coroutine_handle`. The underlying address of return value is `addr`.
The behavior is undefined if `addr` is neither a null pointer value nor an underlying address of a `coroutine_handle`. The behavior is also undefined if the `addr` is an underlying address of a `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<P1>`, where both `Promise` and `P1` are not `void`, and `P1` is different from `Promise`.
This function is not declared for specialization `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`.
### Parameters
| | | |
| --- | --- | --- |
| addr | - | underlying address to import |
### Return values
A `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<Promise>` whose underlying address is `addr`.
### Notes
If `addr` is not a null pointer value, it must be obtained from a prior call to `address()` on a `coroutine_handle` referring to some coroutine.
### Example
### See also
| | |
| --- | --- |
| [(constructor)](coroutine_handle "cpp/coroutine/coroutine handle/coroutine handle")
(C++20) | constructs a `coroutine_handle` object (public member function) |
| [from\_promise](from_promise "cpp/coroutine/coroutine handle/from promise")
[static] (C++20) | creates a `coroutine_handle` from the promise object of a coroutine (public static member function) |
| [noop\_coroutine](../noop_coroutine "cpp/coroutine/noop coroutine")
(C++20) | creates a coroutine handle that has no observable effects when resumed or destroyed (function) |
| programming_docs |
cpp std::coroutine_handle<Promise>::promise std::coroutine\_handle<Promise>::promise
========================================
| | | |
| --- | --- | --- |
| Member of the primary template | | |
|
```
Promise& promise() const;
```
| | (since C++20) |
| Member of specialization `std::coroutine_handle<std::noop_coroutine_promise>` | | |
|
```
std::noop_coroutine_promise& promise() const noexcept;
```
| | (since C++20) |
Obtains a reference to the promise object.
The behavior is undefined if `*this` does not refer to a coroutine whose promise object has not been destroyed.
This function is not provided for the specialization `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>`.
### Parameters
(none).
### Return value
A reference to the promise object.
### Notes
The promise object of a no-op coroutine is not destroyed as long as there is some `[std::noop\_coroutine\_handle](../coroutine_handle "cpp/coroutine/coroutine handle")` referring to the coroutine.
### See also
| | |
| --- | --- |
| [from\_promise](from_promise "cpp/coroutine/coroutine handle/from promise")
[static] (C++20) | creates a `coroutine_handle` from the promise object of a coroutine (public static member function) |
cpp std::hash(std::coroutine_handle)
std::hash(std::coroutine\_handle)
=================================
| Defined in header `[<coroutine>](../../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
template< class Promise >
struct hash<std::coroutine_handle<Promise>>;
```
| | (since C++20) |
The template specialization of `[std::hash](../../utility/hash "cpp/utility/hash")` for `[std::coroutine\_handle](../coroutine_handle "cpp/coroutine/coroutine handle")` allows users to obtain hashes of objects of type `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<P>`.
`operator()` of the specialization is noexcept.
### Example
### See also
| | |
| --- | --- |
| [hash](../../utility/hash "cpp/utility/hash")
(C++11) | hash function object (class template) |
cpp std::coroutine_handle<Promise>::operator coroutine_handle<> std::coroutine\_handle<Promise>::operator coroutine\_handle<>
=============================================================
| | | |
| --- | --- | --- |
|
```
constexpr operator coroutine_handle<>() const noexcept;
```
| | (since C++20) |
This conversion function converts a `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<Promise>` value to a `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>` holding the same underlying address. It effectively erases the promise type.
### Parameters
(none).
### Return value
`[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>::from\_address(address())`.
### See also
| | |
| --- | --- |
| [operator==operator<=>](operator_cmp "cpp/coroutine/coroutine handle/operator cmp")
(C++20) | compares two `coroutine_handle` objects (function) |
cpp std::coroutine_handle<Promise>::operator bool std::coroutine\_handle<Promise>::operator bool
==============================================
| | | |
| --- | --- | --- |
|
```
explicit constexpr operator bool() const noexcept;
```
| | (since C++20) |
Checks whether `*this` is non-null, i.e. the value of `*this` is obtained from the promise object of some coroutine. Equivalent to `return bool(address());`.
If `Promise` is `[std::noop\_coroutine\_promise](../noop_coroutine_promise "cpp/coroutine/noop coroutine promise")`, this conversion function always returns `true`.
### Parameters
(none).
### Return value
`bool(address())`, or `true` if `Promise` is `[std::noop\_coroutine\_promise](../noop_coroutine_promise "cpp/coroutine/noop coroutine promise")`.
### See also
| | |
| --- | --- |
| [address](address "cpp/coroutine/coroutine handle/address")
(C++20) | exports the underlying address, i.e. the pointer backing the coroutine (public member function) |
cpp std::coroutine_handle<Promise>::address std::coroutine\_handle<Promise>::address
========================================
| | | |
| --- | --- | --- |
|
```
constexpr void* address() const noexcept;
```
| | (since C++20) |
Returns the underlying address of the `coroutine_handle`. The return value is non-null if and only if the current value of the `coroutine_handle` is obtained from a promise object of a coroutine.
### Parameters
(none).
### Return value
The underlying address.
### Notes
The return value is non-null for specialization `[std::noop\_coroutine\_handle](../coroutine_handle "cpp/coroutine/coroutine handle")`, because a `std::noop_coroutine_handle` cannot be created without referring to a no-op coroutine.
### See also
| | |
| --- | --- |
| [from\_address](from_address "cpp/coroutine/coroutine handle/from address")
[static] (C++20) | imports a coroutine from a pointer (public static member function) |
cpp std::coroutine_handle<Promise>::done std::coroutine\_handle<Promise>::done
=====================================
| | | |
| --- | --- | --- |
| Member of other specializations | | |
|
```
bool done() const;
```
| (1) | (since C++20) |
| Member of specialization `std::coroutine_handle<std::noop_coroutine_promise>` | | |
|
```
constexpr bool done() const noexcept;
```
| (2) | (since C++20) |
Checks if a suspended coroutine is suspended at its final suspended point.
1) Returns `true` if the coroutine to which `*this` refers is suspended at its final suspend point, or `false` if the coroutine is suspended at other suspend points. The behavior is undefined if `*this` does not refer to a suspended coroutine.
2) Always returns `false`. ### Parameters
(none).
### Return value
1) `true` if the coroutine is suspended at its final suspend point, `false` if the coroutine is suspended at other suspend points.
2) `false`. ### Notes
A no-op coroutine is always considered not suspended at its final suspended point.
### Example
cpp std::coroutine_handle<Promise>::destroy std::coroutine\_handle<Promise>::destroy
========================================
| | | |
| --- | --- | --- |
| Member of other specializations | | |
|
```
void destroy() const;
```
| (1) | (since C++20) |
| Member of specialization `std::coroutine_handle<std::noop_coroutine_promise>` | | |
|
```
constexpr void destroy() const noexcept;
```
| (2) | (since C++20) |
1) Destroys the coroutine state of the coroutine to which `*this` refers, or does nothing if the coroutine is a no-op coroutine.
2) Does nothing. The behavior is undefined if destroying is needed and `*this` does not refer to a suspended coroutine.
### Parameters
(none).
### Return value
(none).
### Example
### See also
| | |
| --- | --- |
| [operator()resume](resume "cpp/coroutine/coroutine handle/resume")
(C++20) | resumes execution of the coroutine (public member function) |
cpp std::coroutine_handle<Promise>::operator= std::coroutine\_handle<Promise>::operator=
==========================================
| | | |
| --- | --- | --- |
|
```
coroutine_handle& operator=( std::nullptr_t ) noexcept;
```
| (1) | (since C++20) |
|
```
coroutine_handle& operator=( const coroutine_handle& other ) = default;
```
| (2) | (since C++20) |
|
```
coroutine_handle& operator=( coroutine_handle&& other ) = default;
```
| (3) | (since C++20) |
Replaces the underlying address.
1) Replaces the underlying address with a null pointer value. After assignment, `*this` does not refer to a coroutine. This assignment operator is not declared for specialization `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`.
2-3) Replaces the underlying address with the one of `other`. Copy and move assignment operators are equivalent to implicitly declared ones. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another `coroutine_handle` to assign from |
### Return value
`*this`.
cpp std::operator==, operator<=>(std::coroutine_handle)
std::operator==, operator<=>(std::coroutine\_handle)
====================================================
| Defined in header `[<coroutine>](../../header/coroutine "cpp/header/coroutine")` | | |
| --- | --- | --- |
|
```
constexpr bool
operator==(std::coroutine_handle<> x, std::coroutine_handle<> y) noexcept;
```
| (1) | (since C++20) |
|
```
constexpr std::strong_ordering
operator<=>(std::coroutine_handle<> x, std::coroutine_handle<> y) noexcept;
```
| (2) | (since C++20) |
Compares two `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>` values `x` and `y` according to their underlying addresses.
The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>` values to compare |
### Return value
1) `x.address() == y.address()`.
2) `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way){}(x.address(), y.address())`. ### Notes
Although these operators are only overloaded for `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>`, other specializations of `[std::coroutine\_handle](../coroutine_handle "cpp/coroutine/coroutine handle")` are also equality comparable and three-way comparable, because they are implicitly convertible to `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<>`.
### Example
cpp std::chrono::duration_values std::chrono::duration\_values
=============================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template <class Rep>
struct duration_values;
```
| | (since C++11) |
The `std::chrono::duration_values` type defines three common durations:
* `std::chrono::duration_values::zero`
* `std::chrono::duration_values::min`
* `std::chrono::duration_values::max`
The [zero](duration/zero "cpp/chrono/duration/zero"), [min](duration/min "cpp/chrono/duration/min"), and [max](duration/max "cpp/chrono/duration/max") static member functions in `[std::chrono::duration](duration "cpp/chrono/duration")` forward their work to these functions.
This type can be specialized if the representation `Rep` requires a specific implementation to return these duration objects.
### Member functions
| | |
| --- | --- |
| [zero](duration_values/zero "cpp/chrono/duration values/zero")
[static] | returns a zero-length representation (public static member function) |
| [min](duration_values/min "cpp/chrono/duration values/min")
[static] | returns the smallest possible representation (public static member function) |
| [max](duration_values/max "cpp/chrono/duration values/max")
[static] | returns the largest possible representation (public static member function) |
cpp std::chrono::hh_mm_ss std::chrono::hh\_mm\_ss
=======================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template< class Duration >
class hh_mm_ss;
```
| | (since C++20) |
The class template `hh_mm_ss` splits a `[std::chrono::duration](duration "cpp/chrono/duration")` into a "broken down" time such as *hours*:*minutes*:*seconds*, with the precision of the split determined by the `Duration` template parameter. It is primarily a formatting tool.
`Duration` must be a specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`, otherwise the program is ill-formed.
### Member Constants
| | |
| --- | --- |
| constexpr unsigned fractional\_width
[static] | the smallest possible integer in the range [0, 18] such that `precision` (see below) will exactly represent the value of `Duration{1}`, or 6 if there's no such integer (public static member constant) |
### Member types
| Member type | Definition |
| --- | --- |
| `precision` | `std::chrono::duration<std::common_type_t<Duration::rep, std::chrono::seconds::rep>, std::ratio<1, 10fractional\_width>>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](hh_mm_ss/hh_mm_ss "cpp/chrono/hh mm ss/hh mm ss") | constructs a `hh_mm_ss` (public member function) |
| [is\_negativehoursminutessecondssubseconds](hh_mm_ss/accessors "cpp/chrono/hh mm ss/accessors") | obtains components of the broken-down time (public member function) |
| [operator precisionto\_duration](hh_mm_ss/duration "cpp/chrono/hh mm ss/duration") | obtains the stored `[std::chrono::duration](duration "cpp/chrono/duration")` (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator<<](hh_mm_ss/operator_ltlt "cpp/chrono/hh mm ss/operator ltlt")
(C++20) | outputs a `hh_mm_ss` into a stream (function template) |
### Helper classes
| | |
| --- | --- |
| [std::formatter<std::chrono::hh\_mm\_ss>](hh_mm_ss/formatter "cpp/chrono/hh mm ss/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `hh_mm_ss` according to the provided format (class template specialization) |
cpp std::chrono::zoned_traits std::chrono::zoned\_traits
==========================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template < class TimeZonePtr >
struct zoned_traits { };
```
| (1) | (since C++20) |
|
```
template <>
struct zoned_traits<const std::chrono::time_zone*>;
```
| (2) | (since C++20) |
The class `zoned_traits` provides a way to customize the behavior of the constructors of `std::chrono::zoned_time` with custom time zone pointer types. In particular, it allows such types to specify the default time zone to use and the mapping of a time zone's name to the corresponding time zone pointer. It is acceptable for custom time zone pointer types to not support either operation, in which case the corresponding constructors of `zoned_time` will not participate in overload resolution.
The primary template is empty. A specialization is provided for `const [std::chrono::time\_zone](http://en.cppreference.com/w/cpp/chrono/time_zone)\*`, the default time zone pointer type.
### Member functions
std::chrono::zoned\_traits<const std::chrono::time\_zone\*>::default\_zone
---------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
static const std::chrono::time_zone* default_zone();
```
| | |
Returns a time zone pointer for the default time zone (UTC).
### Return value
`[std::chrono::locate\_zone](http://en.cppreference.com/w/cpp/chrono/locate_zone)("UTC")`.
std::chrono::zoned\_traits<const std::chrono::time\_zone\*>::locate\_zone
--------------------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
static const std::chrono::time_zone* locate_zone(std::string_view name);
```
| | |
Returns the time zone pointer for the time zone designated by `name`.
### Return value
`[std::chrono::locate\_zone](http://en.cppreference.com/w/cpp/chrono/locate_zone)(name)`.
cpp std::chrono::ambiguous_local_time std::chrono::ambiguous\_local\_time
===================================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class ambiguous_local_time;
```
| | (since C++20) |
Defines a type of object to be thrown as exception to report that an attempt was made to convert a ambiguous `std::chrono::local_time` to a `std::chrono::sys_time` without specifying a `std::chrono::choose` (such as `choose::earliest` or `choose::latest`).
This exception is thrown by `std::chrono::time_zone::to_sys` and functions that call it (such as the constructors of `std::chrono::zoned_time` that takes a `std::chrono::local_time`).
![std-chrono-ambiguous local time-inheritance.svg]()
Inheritance diagram.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs the exception object (public member function) |
| operator= | replaces the exception object (public member function) |
| what | returns the explanatory string (public member function) |
std::chrono::ambiguous\_local\_time::ambiguous\_local\_time
------------------------------------------------------------
| | | |
| --- | --- | --- |
|
```
template< class Duration >
ambiguous_local_time( const std::chrono::local_time<Duration>& tp,
const std::chrono::local_info& i );
```
| (1) | (since C++20) |
|
```
ambiguous_local_time( const ambiguous_local_time& other ) noexcept;
```
| (2) | (since C++20) |
Constructs the exception object.
1) The explanatory string returned by `what()` is equivalent to that produced by `os.str()` after the following code:
```
std::ostringstream os;
os << tp << " is ambiguous. It could be\n"
<< tp << ' ' << i.first.abbrev << " == "
<< tp - i.first.offset << " UTC or\n"
<< tp << ' ' << i.second.abbrev << " == "
<< tp - i.second.offset << " UTC";
```
The behavior is undefined if `i.result != std::chrono::local_info::ambiguous`.
2) Copy constructor. If `*this` and `other` both have dynamic type `std::chrono::ambiguous_local_time` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters
| | | |
| --- | --- | --- |
| tp | - | the time point for which conversion was attempted |
| i | - | a `std::chrono::local_info` describing the result of the conversion attempt |
| other | - | another `ambiguous_local_time` to copy |
### Exceptions
May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")`.
### Notes
Because copying a standard library class derived from `[std::exception](../error/exception "cpp/error/exception")` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string.
std::chrono::ambiguous\_locale\_time::operator=
------------------------------------------------
| | | |
| --- | --- | --- |
|
```
ambiguous_locale_time& operator=( const ambiguous_locale_time& other ) noexcept;
```
| | (since C++20) |
Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::chrono::ambiguous_locale_time` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another exception object to assign with |
### Return value
`*this`.
std::chrono::ambiguous\_locale\_time::what
-------------------------------------------
| | | |
| --- | --- | --- |
|
```
virtual const char* what() const noexcept;
```
| | (since C++20) |
Returns the explanatory string.
### Parameters
(none).
### Return value
Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called.
### Notes
Implementations are allowed but not required to override `what()`.
Inherited from [std::runtime\_error](../error/runtime_error "cpp/error/runtime error")
----------------------------------------------------------------------------------------
Inherited from [std::exception](../error/exception "cpp/error/exception")
---------------------------------------------------------------------------
### Member functions
| | |
| --- | --- |
| [(destructor)](../error/exception/~exception "cpp/error/exception/~exception")
[virtual] | destroys the exception object (virtual public member function of `std::exception`) |
| [what](../error/exception/what "cpp/error/exception/what")
[virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
| programming_docs |
cpp std::chrono::month_day_last std::chrono::month\_day\_last
=============================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class month_day_last;
```
| | (since C++20) |
The class `month_day_last` represents the last day of a specific month, of some yet to be specified year.
`month_day_last` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType").
### Member functions
| | |
| --- | --- |
| [(constructor)](month_day_last/month_day_last "cpp/chrono/month day last/month day last") | constructs a `month_day_last` (public member function) |
| [month](month_day_last/month "cpp/chrono/month day last/month") | accesses the stored [`month`](month "cpp/chrono/month") (public member function) |
| [ok](month_day_last/ok "cpp/chrono/month day last/ok") | checks if the stored [`month`](month "cpp/chrono/month") is valid (public member function) |
### Nonmember functions
| | |
| --- | --- |
| [operator==operator<=>](month_day_last/operator_cmp "cpp/chrono/month day last/operator cmp")
(C++20) | compares two `month_day_last` values (function) |
| [operator<<](month_day_last/operator_ltlt "cpp/chrono/month day last/operator ltlt")
(C++20) | outputs a `month_day_last` into a stream (function template) |
### Helper classes
| | |
| --- | --- |
| [std::formatter<std::chrono::month\_day\_last>](month_day_last/formatter "cpp/chrono/month day last/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_day_last` according to the provided format (class template specialization) |
cpp std::chrono::duration std::chrono::duration
=====================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template<
class Rep,
class Period = std::ratio<1>
> class duration;
```
| | (since C++11) |
Class template `std::chrono::duration` represents a time interval.
It consists of a count of ticks of type `Rep` and a tick period, where the tick period is a compile-time rational [`fraction`](../numeric/ratio/ratio "cpp/numeric/ratio/ratio") representing the time in seconds from one tick to the next.
The only data stored in a `duration` is a tick count of type `Rep`. If `Rep` is floating point, then the `duration` can represent fractions of ticks. `Period` is included as part of the duration's type, and is only used when converting between different durations.
### Member types
| Member type | Definition |
| --- | --- |
| `rep` | `Rep`, an arithmetic type representing the number of ticks |
| `period` | `Period` (until C++17)`typename Period::type` (since C++17), a `[std::ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` representing the tick period (i.e. the number of second's fractions per tick) |
### Member functions
| | |
| --- | --- |
| [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function) |
| [operator=](duration/operator= "cpp/chrono/duration/operator=") | assigns the contents (public member function) |
| [count](duration/count "cpp/chrono/duration/count") | returns the count of ticks (public member function) |
| [zero](duration/zero "cpp/chrono/duration/zero")
[static] | returns the special duration value zero (public static member function) |
| [min](duration/min "cpp/chrono/duration/min")
[static] | returns the special duration value min (public static member function) |
| [max](duration/max "cpp/chrono/duration/max")
[static] | returns the special duration value max (public static member function) |
| [operator+operator-](duration/operator_arith "cpp/chrono/duration/operator arith") | implements unary + and unary - (public member function) |
| [operator++operator++(int)operator--operator--(int)](duration/operator_arith2 "cpp/chrono/duration/operator arith2") | increments or decrements the tick count (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=](duration/operator_arith3 "cpp/chrono/duration/operator arith3") | implements compound assignment between two durations (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator+operator-operator\*operator/operator%](duration/operator_arith4 "cpp/chrono/duration/operator arith4")
(C++11) | implements arithmetic operations with durations as arguments (function template) |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](duration/operator_cmp "cpp/chrono/duration/operator cmp")
(C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares two durations (function template) |
| [duration\_cast](duration/duration_cast "cpp/chrono/duration/duration cast")
(C++11) | converts a duration to another, with a different tick interval (function template) |
| [floor(std::chrono::duration)](duration/floor "cpp/chrono/duration/floor")
(C++17) | converts a duration to another, rounding down (function template) |
| [ceil(std::chrono::duration)](duration/ceil "cpp/chrono/duration/ceil")
(C++17) | converts a duration to another, rounding up (function template) |
| [round(std::chrono::duration)](duration/round "cpp/chrono/duration/round")
(C++17) | converts a duration to another, rounding to nearest, ties to even (function template) |
| [abs(std::chrono::duration)](duration/abs "cpp/chrono/duration/abs")
(C++17) | obtains the absolute value of the duration (function template) |
| [operator<<](duration/operator_ltlt "cpp/chrono/duration/operator ltlt")
(C++20) | performs stream output on a `duration` (function template) |
| [from\_stream](duration/from_stream "cpp/chrono/duration/from stream")
(C++20) | parses a `duration` from a stream according to the provided format (function template) |
### Helper types
| Type | Definition |
| --- | --- |
| `std::chrono::nanoseconds` | `duration</\*signed integer type of at least 64 bits\*/, [std::nano](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)>` |
| `std::chrono::microseconds` | `duration</\*signed integer type of at least 55 bits\*/, [std::micro](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)>` |
| `std::chrono::milliseconds` | `duration</\*signed integer type of at least 45 bits\*/, [std::milli](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)>` |
| `std::chrono::seconds` | `duration</*signed integer type of at least 35 bits*/>` |
| `std::chrono::minutes` | `duration</\*signed integer type of at least 29 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<60>>` |
| `std::chrono::hours` | `duration</\*signed integer type of at least 23 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<3600>>` |
| `std::chrono::days` (since C++20) | `duration</\*signed integer type of at least 25 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<86400>>` |
| `std::chrono::weeks` (since C++20) | `duration</\*signed integer type of at least 22 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<604800>>` |
| `std::chrono::months` (since C++20) | `duration</\*signed integer type of at least 20 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<2629746>>` |
| `std::chrono::years` (since C++20) | `duration</\*signed integer type of at least 17 bits\*/, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<31556952>>` |
Note: each of the predefined duration types up to `hours` covers a range of at least ±292 years.
| | |
| --- | --- |
| Each of the predefined duration types `days`, `weeks`, `months` and `years` covers a range of at least ±40000 years. `years` is equal to 365.2425 `days` (the average length of a Gregorian year). `months` is equal to 30.436875 `days` (exactly 1/12 of `years`). | (since C++20) |
### Helper classes
| | |
| --- | --- |
| [std::common\_type<std::chrono::duration>](duration/common_type "cpp/chrono/duration/common type")
(C++11) | specializes the `[std::common\_type](../types/common_type "cpp/types/common type")` trait (class template specialization) |
| [treat\_as\_floating\_point](treat_as_floating_point "cpp/chrono/treat as floating point")
(C++11) | indicates that a duration is convertible to duration with different tick period (class template) |
| [duration\_values](duration_values "cpp/chrono/duration values")
(C++11) | constructs zero, min, and max values of a tick count of given type (class template) |
| [std::formatter<std::chrono::duration>](duration/formatter "cpp/chrono/duration/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `duration` according to the provided format (class template specialization) |
### Literals
| Defined in inline namespace `std::literals::chrono_literals` |
| --- |
| [operator""h](operator%22%22h "cpp/chrono/operator\"\"h")
(C++14) | A `std::chrono::duration` literal representing hours (function) |
| [operator""min](operator%22%22min "cpp/chrono/operator\"\"min")
(C++14) | A `std::chrono::duration` literal representing minutes (function) |
| [operator""s](operator%22%22s "cpp/chrono/operator\"\"s")
(C++14) | A `std::chrono::duration` literal representing seconds (function) |
| [operator""ms](operator%22%22ms "cpp/chrono/operator\"\"ms")
(C++14) | A `std::chrono::duration` literal representing milliseconds (function) |
| [operator""us](operator%22%22us "cpp/chrono/operator\"\"us")
(C++14) | A `std::chrono::duration` literal representing microseconds (function) |
| [operator""ns](operator%22%22ns "cpp/chrono/operator\"\"ns")
(C++14) | A `std::chrono::duration` literal representing nanoseconds (function) |
| | |
| --- | --- |
| Note: the literal suffixes `d` and `y` do not refer to `days` and `years` but to [`day`](day "cpp/chrono/day") and [`year`](year "cpp/chrono/year"), respectively. | (since C++20) |
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Comment |
| --- | --- |
| [`__cpp_lib_chrono_udls`](../feature_test#Library_features "cpp/feature test") | for user defined literals |
### Notes
The actual time interval (in seconds) that is held by a duration object `d` is roughly equal to `d.count() * D::period::num / D::period::den`, where `D` is of type `chrono::duration<>` and `d` is an object of such type.
### Example
This example shows how to define several custom duration types and convert between types:
```
#include <iostream>
#include <chrono>
using namespace std::chrono_literals;
template<typename T1, typename T2>
using mul = std::ratio_multiply<T1, T2>;
int main()
{
using shakes = std::chrono::duration<int, mul<std::deca, std::nano>>;
using jiffies = std::chrono::duration<int, std::centi>;
using microfortnights = std::chrono::duration<float,
mul<mul<std::ratio<2>, std::chrono::weeks::period>, std::micro>>;
using nanocenturies = std::chrono::duration<float,
mul<mul<std::hecto, std::chrono::years::period>, std::nano>>;
using fps_24 = std::chrono::duration<double, std::ratio<1,24>>;
std::cout << "1 second is:\n";
// integer scale conversion with no precision loss: no cast
std::cout << std::chrono::microseconds(1s).count() << " microseconds\n"
<< shakes(1s).count() << " shakes\n"
<< jiffies(1s).count() << " jiffies\n";
// integer scale conversion with precision loss: requires a cast
std::cout << std::chrono::duration_cast<std::chrono::minutes>(1s).count()
<< " minutes\n";
// floating-point scale conversion: no cast
std::cout << microfortnights(1s).count() << " microfortnights\n"
<< nanocenturies(1s).count() << " nanocenturies\n"
<< fps_24(1s).count() << " frames at 24fps\n";
}
```
Output:
```
1 second is:
1000000 microseconds
100000000 shakes
100 jiffies
0 minutes
0.82672 microfortnights
0.316887 nanocenturies
24 frames at 24fps
```
cpp std::chrono::weekday_indexed std::chrono::weekday\_indexed
=============================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class weekday_indexed;
```
| | (since C++20) |
The class `weekday_indexed` combines a [`weekday`](weekday "cpp/chrono/weekday"), representing a day of the week in the [Gregorian calendar](https://en.wikipedia.org/wiki/proleptic_Gregorian_calendar "enwiki:proleptic Gregorian calendar"), with a small index `*n*` in the range [1, 5]. It represents the first, second, third, fourth, or fifth weekday of some month.
`weekday_indexed` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType").
### Member functions
| | |
| --- | --- |
| [(constructor)](weekday_indexed/weekday_indexed "cpp/chrono/weekday indexed/weekday indexed") | constructs a `weekday_indexed` (public member function) |
| [weekday](weekday_indexed/weekday "cpp/chrono/weekday indexed/weekday") | access the stored [`weekday`](weekday "cpp/chrono/weekday") (public member function) |
| [index](weekday_indexed/index "cpp/chrono/weekday indexed/index") | access the stored index (public member function) |
| [ok](weekday_indexed/ok "cpp/chrono/weekday indexed/ok") | checks if the weekday and index are both valid (public member function) |
### Nonmember functions
| | |
| --- | --- |
| [operator==](weekday_indexed/operator_cmp "cpp/chrono/weekday indexed/operator cmp")
(C++20) | compares two `weekday_indexed` values (function) |
| [operator<<](weekday_indexed/operator_ltlt "cpp/chrono/weekday indexed/operator ltlt")
(C++20) | outputs a `weekday_indexed` into a stream (function template) |
### Helper classes
| | |
| --- | --- |
| [std::formatter<std::chrono::weekday\_indexed>](weekday_indexed/formatter "cpp/chrono/weekday indexed/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday_indexed` according to the provided format (class template specialization) |
### Example
```
#include <iostream>
#include <chrono>
int main()
{
using namespace std::chrono;
constexpr weekday_indexed wi = Friday[2];
// Indexed weekday can be used at any place where chrono::day can be used:
constexpr year_month_weekday ymwd = 2021y / August / wi;
static_assert( ymwd == August / wi / 2021y and
ymwd == wi / August / 2021y );
// std::cout << ymwd << '\n';
constexpr year_month_day ymd{ymwd}; // a conversion
static_assert(ymd == 2021y / 8 / 13);
// std::cout << ymd << '\n';
}
```
Possible output:
```
2021/Aug/Fri[2]
2021-08-13
```
cpp std::chrono::zoned_time std::chrono::zoned\_time
========================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template <
class Duration,
class TimeZonePtr = const std::chrono::time_zone*
> class zoned_time;
```
| | (since C++20) |
|
```
using zoned_seconds = std::chrono::zoned_time<std::chrono::seconds>;
```
| | (since C++20) |
The class `zoned_time` represents a logical pairing of a time zone and a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` whose resolution is `Duration`.
An invariant of `zoned_time` is that it always refers to a valid time zone and represents an existing and unambiguous time point in that time zone. Consistent with this invariant, `zoned_time` has no move constructor or move assignment operator; attempts to move a `zoned_time` will perform a copy.
The program is ill-formed if `Duration` is not a specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`.
The template parameter `TimeZonePtr` allows users to supply their own time zone pointer types and further customize the behavior of `zoned_time` via `std::chrono::zoned_traits`. Custom time zone types need not support all the operations supported by `std::chrono::time_zone`, only those used by the functions actually called on the `zoned_time`.
`TimeZonePtr` must be [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). Move-only `TimeZonePtr`s are allowed but difficult to use, as the `zoned_time` will be immovable and it is not possible to access the stored `TimeZonePtr`.
### Member types
| Member type | Definition |
| --- | --- |
| `duration` | `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<Duration, [std::chrono::seconds](http://en.cppreference.com/w/cpp/chrono/duration)>` |
### Member functions
| | |
| --- | --- |
| [(constructor)](zoned_time/zoned_time "cpp/chrono/zoned time/zoned time") | constructs a `zoned_time` (public member function) |
| [operator=](zoned_time/operator= "cpp/chrono/zoned time/operator=") | assigns value to a `zoned_time` (public member function) |
| [get\_time\_zone](zoned_time/get_time_zone "cpp/chrono/zoned time/get time zone") | obtains a copy of the time zone pointer (public member function) |
| [operator local\_timeget\_local\_time](zoned_time/get_local_time "cpp/chrono/zoned time/get local time") | obtains the stored time point as a `local_time` (public member function) |
| [operator sys\_timeget\_sys\_time](zoned_time/get_sys_time "cpp/chrono/zoned time/get sys time") | obtains the stored time point as a `sys_time` (public member function) |
| [get\_info](zoned_time/get_info "cpp/chrono/zoned time/get info") | obtain information about the time zone at the stored time point (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==](zoned_time/operator_cmp "cpp/chrono/zoned time/operator cmp")
(C++20) | compares two `zoned_time` values (function template) |
| [operator<<](zoned_time/operator_ltlt "cpp/chrono/zoned time/operator ltlt")
(C++20) | outputs a `zoned_time` into a stream (function template) |
### Helper classes
| | |
| --- | --- |
| [std::formatter<std::chrono::zoned\_time>](zoned_time/formatter "cpp/chrono/zoned time/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `zoned_time` according to the provided format (class template specialization) |
### [Deduction guides](zoned_time/deduction_guides "cpp/chrono/zoned time/deduction guides")
### Example
```
#include <chrono>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <string_view>
int main()
{
constexpr std::string_view locations[] = {
"Africa/Casablanca", "America/Argentina/Buenos_Aires",
"America/Barbados", "America/Indiana/Petersburg",
"America/Tarasco_Bar", "Antarctica/Casey",
"Antarctica/Vostok", "Asia/Magadan",
"Asia/Manila", "Asia/Shanghai",
"Asia/Tokyo", "Atlantic/Bermuda",
"Australia/Darwin", "Europe/Isle_of_Man",
"Europe/Laputa", "Indian/Christmas",
"Indian/Cocos", "Pacific/Galapagos",
};
constexpr auto width = std::ranges::max_element(locations, {},
[](const auto& s) { return s.length(); })->length();
for (const auto location : locations) {
try {
// may throw if `location` is not in the time zone database
const std::chrono::zoned_time zt{location, std::chrono::system_clock::now()};
std::cout << std::setw(width) << location << " - Zoned Time: " << zt << '\n';
} catch (std::chrono::nonexistent_local_time& ex) {
std::cout << "Error: " << ex.what() << '\n';
}
}
}
```
Possible output:
```
Africa/Casablanca - Zoned Time: 2021-09-16 10:26:54.837665555 +01
America/Argentina/Buenos_Aires - Zoned Time: 2021-09-16 06:26:55.090150136 -03
America/Barbados - Zoned Time: 2021-09-16 05:26:55.090419331 AST
America/Indiana/Petersburg - Zoned Time: 2021-09-16 05:26:55.090465623 EDT
Error: America/Tarasco_Bar not found in timezone database
Antarctica/Casey - Zoned Time: 2021-09-16 20:26:55.123070973 +11
Antarctica/Vostok - Zoned Time: 2021-09-16 15:26:55.123151218 +06
Asia/Magadan - Zoned Time: 2021-09-16 20:26:55.123208852 +11
Asia/Manila - Zoned Time: 2021-09-16 17:26:55.123434512 PST
Asia/Shanghai - Zoned Time: 2021-09-16 17:26:55.123520538 CST
Asia/Tokyo - Zoned Time: 2021-09-16 18:26:55.123626199 JST
Atlantic/Bermuda - Zoned Time: 2021-09-16 06:26:55.123713854 ADT
Australia/Darwin - Zoned Time: 2021-09-16 18:56:55.155857464 ACST
Europe/Isle_of_Man - Zoned Time: 2021-09-16 10:26:55.155909304 BST
Error: Europe/Laputa not found in timezone database
Indian/Christmas - Zoned Time: 2021-09-16 16:26:55.215065303 +07
Indian/Cocos - Zoned Time: 2021-09-16 15:56:55.215137548 +0630
Pacific/Galapagos - Zoned Time: 2021-09-16 03:26:55.215201447 -06
```
| programming_docs |
cpp std::chrono::high_resolution_clock std::chrono::high\_resolution\_clock
====================================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class high_resolution_clock;
```
| | (since C++11) |
Class `std::chrono::high_resolution_clock` represents the clock with the smallest tick period provided by the implementation. It may be an alias of `[std::chrono::system\_clock](system_clock "cpp/chrono/system clock")` or `[std::chrono::steady\_clock](steady_clock "cpp/chrono/steady clock")`, or a third, independent clock.
`std::chrono::high_resolution_clock` meets the requirements of [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock").
### Member types
| Member type | Definition |
| --- | --- |
| `rep` | arithmetic type representing the number of ticks in the clock's duration |
| `period` | a `[std::ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` type representing the tick period of the clock, in seconds |
| `duration` | `[std::chrono::duration](http://en.cppreference.com/w/cpp/chrono/duration)<rep, period>` |
| `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::high\_resolution\_clock>` |
### Member constants
| | |
| --- | --- |
| constexpr bool is\_steady
[static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](high_resolution_clock/now "cpp/chrono/high resolution clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) |
### Member functions
| | |
| --- | --- |
| [now](high_resolution_clock/now "cpp/chrono/high resolution clock/now")
[static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current value of the clock (public static member function) |
### Notes
The `high_resolution_clock` is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for `[std::chrono::steady\_clock](steady_clock "cpp/chrono/steady clock")` or `[std::chrono::system\_clock](system_clock "cpp/chrono/system clock")`, but which one it is depends on the library or configuration. When it is a `system_clock`, it is not monotonic (e.g., the time can go backwards). For example, for gcc's libstdc++ it is `system_clock`, for MSVC it is `steady_clock`, and for clang's libc++ it depends on configuration.
Generally one should just use `[std::chrono::steady\_clock](steady_clock "cpp/chrono/steady clock")` or `[std::chrono::system\_clock](system_clock "cpp/chrono/system clock")` directly instead of `std::chrono::high_resolution_clock`: use `steady_clock` for duration measurements, and `system_clock` for wall-clock time.
### See also
| | |
| --- | --- |
| [system\_clock](system_clock "cpp/chrono/system clock")
(C++11) | wall clock time from the system-wide realtime clock (class) |
| [steady\_clock](steady_clock "cpp/chrono/steady clock")
(C++11) | monotonic clock that will never be adjusted (class) |
cpp std::chrono::year_month_day_last std::chrono::year\_month\_day\_last
===================================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class year_month_day_last;
```
| | (since C++20) |
The class `year_month_day_last` represents the last day of a specific year and month. It is a field-based time point, with a resolution of `std::chrono::days`, subject to the limit that it can only represent the last day of a month.
`std::chrono::years`- and `std::chrono::months`-oriented arithmetic are supported directly. An implicit conversion to `std::chrono::sys_days` allows `std::chrono::days`-oriented arithmetic to be performed efficiently.
`year_month_day_last` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType").
### Member functions
| | |
| --- | --- |
| [(constructor)](year_month_day_last/year_month_day_last "cpp/chrono/year month day last/year month day last") | constructs a `year_month_day_last` object (public member function) |
| [operator+=operator-=](year_month_day_last/operator_arith "cpp/chrono/year month day last/operator arith") | modifies the time point by some number of months or years (public member function) |
| [yearmonthdaymonth\_day\_last](year_month_day_last/accessors "cpp/chrono/year month day last/accessors") | accesses the fields of this object (public member function) |
| [operator sys\_daysoperator local\_days](year_month_day_last/operator_days "cpp/chrono/year month day last/operator days") | converts to a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` (public member function) |
| [ok](year_month_day_last/ok "cpp/chrono/year month day last/ok") | checks whether this object represents a valid date (public member function) |
### Nonmember functions
| | |
| --- | --- |
| [operator==operator<=>](year_month_day_last/operator_cmp "cpp/chrono/year month day last/operator cmp")
(C++20) | compares two `year_month_day_last` values (function) |
| [operator+operator-](year_month_day_last/operator_arith_2 "cpp/chrono/year month day last/operator arith 2")
(C++20) | adds or subtracts a `year_month_day_last` and some number of years or months (function) |
| [operator<<](year_month_day_last/operator_ltlt "cpp/chrono/year month day last/operator ltlt")
(C++20) | outputs a `year_month_day_last` into a stream (function template) |
### Helper classes
| | |
| --- | --- |
| [std::formatter<std::chrono::year\_month\_day\_last>](year_month_day_last/formatter "cpp/chrono/year month day last/formatter")
(C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day_last` according to the provided format (class template specialization) |
### Example
```
#include <iostream>
#include <chrono>
// until online compiler supports streaming the year_month_day_last:
std::ostream& operator<< (std::ostream& os, std::chrono::year_month_day_last ymdl) {
return os << static_cast<int>(ymdl.year()) << '/'
<< static_cast<unsigned>(ymdl.month()) << '/'
<< static_cast<unsigned>(ymdl.day());
}
int main()
{
const auto ymd = std::chrono::year_month_day{
std::chrono::floor<std::chrono::days>(
std::chrono::system_clock::now()
)
};
const std::chrono::year_month_day_last ymdl{
ymd.year(), ymd.month() / std::chrono::last
};
std::cout << "The date of the last day of this month is: " << ymdl << '\n';
// The `last` object can be places wherever it is legal to place a `day`:
using namespace std::chrono;
constexpr std::chrono::year_month_day_last
ymdl1 = 2023y / February / last,
ymdl2 = last / February / 2023y,
ymdl3 = February / last / 2023y;
static_assert( ymdl1 == ymdl2 and ymdl2 == ymdl3 );
}
```
Possible output:
```
The date of the last day of this month is: 2021/11/30
```
### See also
| | |
| --- | --- |
| [year\_month\_day](year_month_day "cpp/chrono/year month day")
(C++20) | represents a specific [`year`](year "cpp/chrono/year"), [`month`](month "cpp/chrono/month"), and [`day`](day "cpp/chrono/day") (class) |
cpp std::chrono::get_tzdb_list, std::chrono::get_tzdb, std::chrono::remote_version, std::chrono::reload_tzdb std::chrono::get\_tzdb\_list, std::chrono::get\_tzdb, std::chrono::remote\_version, std::chrono::reload\_tzdb
=============================================================================================================
| | | |
| --- | --- | --- |
|
```
std::chrono::tzdb_list& get_tzdb_list();
```
| (1) | (since C++20) |
|
```
const std::chrono::tzdb& get_tzdb();
```
| (2) | (since C++20) |
|
```
std::string remote_version();
```
| (3) | (since C++20) |
|
```
const std::chrono::tzdb& reload_tzdb();
```
| (4) | (since C++20) |
These functions provide access to the program-wide time zone database.
1) Returns a reference to the global `std::chrono::tzdb_list` singleton. If this is the first access to the database, initialize the database. After the initialization, the database will hold a single initialized `std::chrono::tzdb` object. This function is thread-safe: concurrent calls to this function from multiple threads do not introduce a data race.
2) Returns a reference to the first `std::chrono::tzdb` object held by the `tzdb_list` singleton. Equivalent to `std::chrono::get_tzdb_list().front()`.
3) Returns a string containing the latest remote database version.
4) If `remote_version() != get_tzdb().version`, pushes a new `tzdb` object representing the remote database to the front of the `tzdb_list` singleton referenced by `get_tzdb_list()`. Otherwise there are no effects. No references, pointers or iterators are invalidated. Calling this function concurrently with `get_tzdb_list().front()` or `get_tzdb_list().erase_after()` does not introduce a data race. ### Exceptions
1) `[std::runtime\_error](../error/runtime_error "cpp/error/runtime error")` if for any reason a reference to a `tzdb_list` containing one or more valid `tzdb` cannot be returned. ### Return value
1) A reference to the global `std::chrono::tzdb_list` singleton.
2) `std::chrono::get_tzdb_list().front()`.
3) A string containing the latest remote database version.
4) `std::chrono::get_tzdb_list().front()` (after any update made by this function).
cpp std::chrono::clock_time_conversion std::chrono::clock\_time\_conversion
====================================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
template<class Dest, class Source> struct clock_time_conversion { };
```
| | (since C++20) |
`std::chrono::clock_time_conversion` is a trait that specifies how to convert a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` of the `Source` clock to that of the `Dest` clock. It does so by providing an const-callable `operator()` that accepts an argument of type `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<Source, Duration>` and returns a `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<Dest, OtherDuration>` that represents an equivalent point in time. The duration of the returned time point is computed from the source duration in a manner that varies for each specialization. `clock_time_conversion` is normally only used indirectly, via `std::chrono::clock_cast`.
A program may specialize `clock_time_conversion` if at least one of the template parameters is a user-defined clock type.
The primary template is an empty struct. The standard defines the following specializations:
| | | |
| --- | --- | --- |
|
```
template<class Clock> struct clock_time_conversion<Clock, Clock>;
```
| (1) | (since C++20) |
|
```
template<> struct clock_time_conversion<std::chrono::system_clock, std::chrono::system_clock>;
```
| (2) | (since C++20) |
|
```
template<> struct clock_time_conversion<std::chrono::utc_clock, std::chrono::utc_clock>;
```
| (3) | (since C++20) |
|
```
template<> struct clock_time_conversion<std::chrono::system_clock, std::chrono::utc_clock>;
```
| (4) | (since C++20) |
|
```
template<> struct clock_time_conversion<std::chrono::utc_clock, std::chrono::system_clock>;
```
| (5) | (since C++20) |
|
```
template<class Clock> struct clock_time_conversion<Clock, std::chrono::system_clock>;
```
| (6) | (since C++20) |
|
```
template<class Clock> struct clock_time_conversion<std::chrono::system_clock, Clock>;
```
| (7) | (since C++20) |
|
```
template<class Clock> struct clock_time_conversion<Clock, std::chrono::utc_clock>;
```
| (8) | (since C++20) |
|
```
template<class Clock> struct clock_time_conversion<std::chrono::utc_clock, Clock>;
```
| (9) | (since C++20) |
1-3) Identity conversion: `operator()` returns a copy of the argument.
4-5) Conversions between `std::chrono::sys_time` and `std::chrono::utc_time`: `operator()` calls `std::chrono::utc_clock::to_sys` and `std::chrono::utc_clock::from_sys`, respectively.
6-7) Conversions to and from `std::chrono::sys_time` when `Clock` supports `from_sys` and `to_sys`: `operator()` calls `Clock::to_sys` and `Clock::from_sys`, respectively.
8-9) Conversions to and from `std::chrono::utc_time` when `Clock` supports `from_utc` and `to_utc`: `operator()` calls `Clock::to_utc` and `Clock::from_utc`, respectively. ### Member functions
Each specialization has an implicitly-declared default constructor, copy constructor, move constructor, copy assignment operator, move assignment operator, and destructor.
std::chrono::clock\_time\_conversion::operator()
-------------------------------------------------
| | | |
| --- | --- | --- |
|
```
template <class Duration>
std::chrono::time_point<Clock, Duration>
operator()(const std::chrono::time_point<Clock, Duration>& t) const;
```
| (1) | (member of specialization (1)) |
|
```
template <class Duration>
std::chrono::sys_time<Duration>
operator()(const std::chrono::sys_time<Duration> & t) const;
```
| (2) | (member of specialization (2)) |
|
```
template <class Duration>
std::chrono::utc_time<Duration>
operator()(const std::chrono::utc_time<Duration>& t) const;
```
| (3) | (member of specialization (3)) |
|
```
template <class Duration>
std::chrono::sys_time<Duration>
operator()(const std::chrono::utc_time<Duration>& t) const;
```
| (4) | (member of specialization (4)) |
|
```
template <class Duration>
std::chrono::utc_time<Duration>
operator()(const std::chrono::sys_time<Duration>& t) const;
```
| (5) | (member of specialization (5)) |
|
```
template <class Duration>
auto operator()(const std::chrono::sys_time<Duration>& t) const
-> decltype(Clock::from_sys(t));
```
| (6) | (member of specialization (6)) |
|
```
template <class Duration>
auto operator()(const std::chrono::time_point<SourceClock, Duration>& t) const
-> decltype(Clock::to_sys(t));
```
| (7) | (member of specialization (7)) |
|
```
template <class Duration>
auto operator()(const std::chrono::utc_time<Duration>& t) const
-> decltype(Clock::from_utc(t));
```
| (8) | (member of specialization (8)) |
|
```
template <class Duration>
auto operator()(const std::chrono::time_point<Clock, Duration>& t) const
-> decltype(Clock::to_utc(t));
```
| (9) | (member of specialization (9)) |
Converts the argument `[std::chrono::time\_point](time_point "cpp/chrono/time point")` to the destination clock.
1-3) Identity conversion. Returns `t` unchanged.
4) Returns `[std::chrono::utc\_clock::to\_sys](http://en.cppreference.com/w/cpp/chrono/utc_clock/to_sys)(t)`.
5) Returns `[std::chrono::utc\_clock::from\_sys](http://en.cppreference.com/w/cpp/chrono/utc_clock/from_sys)(t)`.
6) Returns `Clock::from_sys(t)`. This overload participates in overload resolution only if the expression `Clock::from_sys(t)` is well-formed. The program is ill-formed if `Clock::from_sys(t)` does not return `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<Clock, Duration>` where `Duration` is some valid specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`.
7) Returns `Clock::to_sys(t)`. This overload participates in overload resolution only if the expression `Clock::to_sys(t)` is well-formed. The program is ill-formed if `Clock::to_sys(t)` does not return `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<Duration>` where `Duration` is some valid specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`.
8) Returns `Clock::from_utc(t)`. This overload participates in overload resolution only if the expression `Clock::from_utc(t)` is well-formed. The program is ill-formed if `Clock::from_utc(t)` does not return `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<Clock, Duration>` where `Duration` is some valid specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`.
9) Returns `Clock::to_utc(t)`. This overload participates in overload resolution only if the expression `Clock::to_utc(t)` is well-formed. The program is ill-formed if `Clock::to_utc(t)` does not return `[std::chrono::utc\_time](http://en.cppreference.com/w/cpp/chrono/utc_clock)<Duration>` where `Duration` is some valid specialization of `[std::chrono::duration](duration "cpp/chrono/duration")`. ### Parameters
| | | |
| --- | --- | --- |
| t | - | time point to convert |
### Return value
The result of the conversion as described above:
1-3) `t`.
4) `[std::chrono::utc\_clock::to\_sys](http://en.cppreference.com/w/cpp/chrono/utc_clock/to_sys)(t)`.
5) `[std::chrono::utc\_clock::from\_sys](http://en.cppreference.com/w/cpp/chrono/utc_clock/from_sys)(t)`.
6) `Clock::from_sys(t)`.
7) `Clock::to_sys(t)`.
8) `Clock::from_utc(t)`.
9) `Clock::to_utc(t)`.
### See also
| | |
| --- | --- |
| [clock\_cast](clock_cast "cpp/chrono/clock cast")
(C++20) | convert time points of one clock to another (function template) |
cpp C Date and time utilities C Date and time utilities
=========================
### Functions
| Defined in header `[<ctime>](../header/ctime "cpp/header/ctime")` |
| --- |
| Time manipulation |
| [difftime](c/difftime "cpp/chrono/c/difftime") | computes the difference between times (function) |
| [time](c/time "cpp/chrono/c/time") | returns the current time of the system as time since epoch (function) |
| [clock](c/clock "cpp/chrono/c/clock") | returns raw processor clock time since the program is started (function) |
| [timespec\_get](c/timespec_get "cpp/chrono/c/timespec get")
(C++17) | returns the calendar time in seconds and nanoseconds based on a given time base (function) |
| Format conversions |
| [asctime](c/asctime "cpp/chrono/c/asctime") | converts a `[std::tm](c/tm "cpp/chrono/c/tm")` object to a textual representation (function) |
| [ctime](c/ctime "cpp/chrono/c/ctime") | converts a `[std::time\_t](c/time_t "cpp/chrono/c/time t")` object to a textual representation (function) |
| [strftime](c/strftime "cpp/chrono/c/strftime") | converts a `[std::tm](c/tm "cpp/chrono/c/tm")` object to custom textual representation (function) |
| [wcsftime](c/wcsftime "cpp/chrono/c/wcsftime") | converts a `[std::tm](c/tm "cpp/chrono/c/tm")` object to custom wide string textual representation (function) |
| [gmtime](c/gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) |
| [localtime](c/localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) |
| [mktime](c/mktime "cpp/chrono/c/mktime") | converts calendar time to time since epoch (function) |
### Constants
| | |
| --- | --- |
| [CLOCKS\_PER\_SEC](c/clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC") | number of processor clock ticks per second (macro constant) |
### Types
| | |
| --- | --- |
| [tm](c/tm "cpp/chrono/c/tm") | calendar time type (class) |
| [time\_t](c/time_t "cpp/chrono/c/time t") | time since epoch type (typedef) |
| [clock\_t](c/clock_t "cpp/chrono/c/clock t") | process running time (typedef) |
| [timespec](c/timespec "cpp/chrono/c/timespec")
(C++17) | time in seconds and nanoseconds (struct) |
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/chrono "c/chrono") for Date and time utilities |
cpp std::chrono::steady_clock std::chrono::steady\_clock
==========================
| Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | |
| --- | --- | --- |
|
```
class steady_clock;
```
| | (since C++11) |
Class `std::chrono::steady_clock` represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward and the time between ticks of this clock is constant. This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.
`std::chrono::steady_clock` meets the requirements of [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock").
### Member types
| Member type | Definition |
| --- | --- |
| `rep` | arithmetic type representing the number of ticks in the clock's duration |
| `period` | a `[std::ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` type representing the tick period of the clock, in seconds |
| `duration` | `[std::chrono::duration](http://en.cppreference.com/w/cpp/chrono/duration)<rep, period>` |
| `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::steady\_clock>` |
### Member constants
| | |
| --- | --- |
| constexpr bool is\_steady
[static] | steady clock flag, always `true` (public static member constant) |
### Member functions
| | |
| --- | --- |
| [now](steady_clock/now "cpp/chrono/steady clock/now")
[static] | returns a time\_point representing the current value of the clock (public static member function) |
### See also
| | |
| --- | --- |
| [system\_clock](system_clock "cpp/chrono/system clock")
(C++11) | wall clock time from the system-wide realtime clock (class) |
| [high\_resolution\_clock](high_resolution_clock "cpp/chrono/high resolution clock")
(C++11) | the clock with the shortest tick period available (class) |
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.