code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cpp std::chrono::utc_clock std::chrono::utc\_clock ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class utc_clock; ``` | | (since C++20) | The clock `std::chrono::utc_clock` is a [Clock](../named_req/clock "cpp/named req/Clock") that represents Coordinated Universal Time (UTC). It measures time since 00:00:00 UTC, Thursday, 1 January 1970, including leap seconds. `utc_clock` meets the [Clock](../named_req/clock "cpp/named req/Clock") requirements. It does not meet the [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock") requirements unless the implementation can guarantee that [`now()`](utc_clock/now "cpp/chrono/utc clock/now") does not throw an exception. ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using utc_time = std::chrono::time_point<std::chrono::utc_clock, Duration>; ``` | | (since C++20) | | ``` using utc_seconds = utc_time<std::chrono::seconds>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::utc\_time)](utc_clock/operator_ltlt "cpp/chrono/utc clock/operator ltlt") (C++20) | performs stream output on a utc\_time (function template) | | [from\_stream(std::chrono::utc\_time)](utc_clock/from_stream "cpp/chrono/utc clock/from stream") (C++20) | parses a utc\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::utc\_time>](utc_clock/formatter "cpp/chrono/utc clock/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `utc_time` according to the provided format (class template specialization) | ### Member types | Member type | Definition | | --- | --- | | `rep` | signed 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>`, capable of representing negative durations | | `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::utc\_clock>` | ### Member constants | | | | --- | --- | | constexpr bool is\_steady [static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](utc_clock/now "cpp/chrono/utc clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) | ### Member functions | | | | --- | --- | | [now](utc_clock/now "cpp/chrono/utc clock/now") [static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current point in time (public static member function) | | [to\_sys](utc_clock/to_sys "cpp/chrono/utc clock/to sys") [static] | converts `utc_time` to `sys_time` (public static member function) | | [from\_sys](utc_clock/from_sys "cpp/chrono/utc clock/from sys") [static] | converts `sys_time` to `utc_time` (public static member function) | ### Non-member functions | | | | --- | --- | | [get\_leap\_second\_info](utc_clock/get_leap_second_info "cpp/chrono/utc clock/get leap second info") (C++20) | obtains leap second insertion information from a `utc_time` object (function template) | ### Helper classes | | | | --- | --- | | [leap\_second\_info](utc_clock/leap_second_info "cpp/chrono/utc clock/leap second info") (C++20) | leap second insertion information (class) | ### Notes The official UTC epoch is 1 January 1972. `utc_clock` uses 1 January 1970 instead to be consistent with `[std::chrono::system\_clock](system_clock "cpp/chrono/system clock")`. cpp std::chrono::year_month_day std::chrono::year\_month\_day ============================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class year_month_day; ``` | | (since C++20) | The class `year_month_day` represents a specific year, month, and day. It is a field-based time point, with a resolution of `std::chrono::days`. `std::chrono::years`- and `std::chrono::months`-oriented arithmetic are supported directly. An implicit conversion to and from `std::chrono::sys_days` allows `std::chrono::days`-oriented arithmetic to be performed efficiently. `year_month_day` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](year_month_day/year_month_day "cpp/chrono/year month day/year month day") | constructs a `year_month_day` (public member function) | | [operator+=operator-=](year_month_day/operator_arith "cpp/chrono/year month day/operator arith") | modifies the time point by some number of months or years (public member function) | | [yearmonthday](year_month_day/accessors "cpp/chrono/year month day/accessors") | accesses the year, month, and day stored in this object (public member function) | | [operator sys\_daysoperator local\_days](year_month_day/operator_days "cpp/chrono/year month day/operator days") | converts to a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` (public member function) | | [ok](year_month_day/ok "cpp/chrono/year month day/ok") | checks if the `year_month_day` represents a valid date (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](year_month_day/operator_cmp "cpp/chrono/year month day/operator cmp") (C++20) | compares two `year_month_day` values (function) | | [operator+operator-](year_month_day/operator_arith_2 "cpp/chrono/year month day/operator arith 2") (C++20) | adds or subtracts a `year_month_day` and some number of years or months (function) | | [operator<<](year_month_day/operator_ltlt "cpp/chrono/year month day/operator ltlt") (C++20) | outputs a `year_month_day` into a stream (function template) | | [from\_stream](year_month_day/from_stream "cpp/chrono/year month day/from stream") (C++20) | parses a `year_month_day` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::year\_month\_day>](year_month_day/formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day` according to the provided format (class template specialization) | ### Example ``` #include <chrono> #include <iostream> int main() { const std::chrono::time_point now{std::chrono::system_clock::now()}; const std::chrono::year_month_day ymd{std::chrono::floor<std::chrono::days>(now)}; std::cout << "Current Year: " << static_cast<int>(ymd.year()) << ", Month: " << static_cast<unsigned>(ymd.month()) << ", Day: " << static_cast<unsigned>(ymd.day()) << '\n'; } ``` Possible output: ``` Current Year: 2021, Month: 9, Day: 5 ``` cpp std::literals::chrono_literals::operator""d std::literals::chrono\_literals::operator""d ============================================ | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::day operator ""d(unsigned long long d) noexcept; ``` | (1) | (since C++20) | Forms a `std::chrono::day` literal representing a day of the month in the calendar. ### Parameters | | | | | --- | --- | --- | | d | - | the day value | ### Return value A `std::chrono::day` storing `d`. If `d > 255`, the stored value is unspecified. ### Possible implementation | | | --- | | ``` constexpr std::chrono::day operator ""d(unsigned long long d) noexcept { return std::chrono::day(d); } ``` | ### Notes This operator is declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to this operator can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::literals::chrono_literals; std::cout << static_cast<unsigned>(42d) << ' ' << static_cast<unsigned>(256d) << ' ' // unspecified << static_cast<unsigned>(298d) << '\n'; // unspecified } ``` Possible output: ``` 42 0 42 ``` ### See also | | | | --- | --- | | [(constructor)](day/day "cpp/chrono/day/day") | constructs a `day` (public member function of `std::chrono::day`) | | [operator unsigned](day/operator_unsigned "cpp/chrono/day/operator unsigned") | retrieves the stored day value (public member function of `std::chrono::day`) | cpp std::chrono::sys_info std::chrono::sys\_info ====================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct sys_info; ``` | | (since C++20) | The class `sys_info` describes time zone information associated with a time zone at a particular point in time (represented as either a `std::chrono::sys_time` or a `std::chrono::local_time`). This is a low-level data structure typically not used directly by user code. ### Member objects | Member object | Type | | --- | --- | | `begin`, `end` | `std::chrono::sys_seconds` | | `offset` | `[std::chrono::seconds](duration "cpp/chrono/duration")` | | `save` | `[std::chrono::minutes](duration "cpp/chrono/duration")` | | `abbrev` | `[std::string](../string/basic_string "cpp/string/basic string")` | The `begin` and `end` data members indicate the range - `[begin, end)` - in which the `offset` and `abbrev` are in effect for the time zone associated with this `sys_info`. The `offset` and `abbrev` data member indicate the UTC offset and time zone abbreviation, respectively, in effect for the associated time zone and `[std::chrono::time\_point](time_point "cpp/chrono/time point")`. Note that time zone abbreviations are not unique. The `save` data member, if nonzero, indicates that the time zone is on daylight saving time at the specified time point. In this case, `offset - save` is a suggestion of what offset this time zone might use if it were off daylight saving time. However, this information is not authoritative: the only way to ascertain the actual offset is to query the time zone with a time point that is actually off daylight savings time (i.e. returns a `sys_info` such that `save == 0min`). ### Nonmember functions | | | | --- | --- | | [operator<<](sys_info/operator_ltlt "cpp/chrono/sys info/operator ltlt") (C++20) | outputs a `sys_info` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::sys\_info>](sys_info/formatter "cpp/chrono/sys info/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `sys_info` according to the provided format (class template specialization) | cpp std::chrono::current_zone std::chrono::current\_zone ========================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` const std::chrono::time_zone* current_zone(); ``` | | (since C++20) | Convenience function for obtaining local time zone from the time zone database. Equivalent to `[std::chrono::get\_tzdb](http://en.cppreference.com/w/cpp/chrono/tzdb_functions)().current\_zone()`. ### Exceptions `[std::runtime\_error](../error/runtime_error "cpp/error/runtime error")` if this is the first reference to the time zone database and the time zone database cannot be initialized. ### Notes A call to this function that is the first reference to the time zone database will cause it to be initialized. ### Example ``` #include <chrono> #include <iostream> int main() { const std::chrono::zoned_time cur_time{ std::chrono::current_zone(), std::chrono::system_clock::now() }; std::cout << cur_time << '\n'; } ``` Possible output: ``` 2021-09-13 19:46:42.249182012 MAGT ``` ### See also | | | | --- | --- | | [current\_zone](tzdb/current_zone "cpp/chrono/tzdb/current zone") | return the local time zone (public member function of `std::chrono::tzdb`) | | [get\_tzdbget\_tzdb\_listreload\_tzdbremote\_version](tzdb_functions "cpp/chrono/tzdb functions") (C++20) | accesses and controls the global time zone database information (function) | cpp std::chrono::day std::chrono::day ================ | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class day; ``` | | (since C++20) | The class `day` represents a day in a month. Its normal range is [1, 31], but it may hold any number in [0, 255]. `day` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](day/day "cpp/chrono/day/day") | constructs a `day` (public member function) | | [operator++operator++(int)operator--operator--(int)](day/operator_inc_dec "cpp/chrono/day/operator inc dec") | increments or decrements the day (public member function) | | [operator+=operator-=](day/operator_arith "cpp/chrono/day/operator arith") | adds or subtracts a number of days (public member function) | | [operator unsigned](day/operator_unsigned "cpp/chrono/day/operator unsigned") | retrieves the stored day value (public member function) | | [ok](day/ok "cpp/chrono/day/ok") | checks if the stored day value is in the normal range (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](day/operator_cmp "cpp/chrono/day/operator cmp") (C++20) | compares two `day` values (function) | | [operator+operator-](day/operator_arith_2 "cpp/chrono/day/operator arith 2") (C++20) | adds or subtracts a number of days and a `day`, or find the difference between two `day`s (function) | | [operator<<](day/operator_ltlt "cpp/chrono/day/operator ltlt") (C++20) | outputs a `day` into a stream (function template) | | [from\_stream](day/from_stream "cpp/chrono/day/from stream") (C++20) | parses a `day` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::day>](day/formatter "cpp/chrono/day/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `day` according to the provided format (class template specialization) | ### Literals | Defined in inline namespace `std::literals::chrono_literals` | | --- | | [operator""d](operator%22%22d "cpp/chrono/operator\"\"d") (C++20) | A `std::chrono::day` literal representing a day of a month (function) | cpp std::literals::chrono_literals::operator""h std::literals::chrono\_literals::operator""h ============================================ | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr chrono::hours operator "" h(unsigned long long hrs); ``` | (1) | (since C++14) | | ``` constexpr chrono::duration</*unspecified*/, std::ratio<3600,1>> operator "" h(long double hrs); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing hours. 1) integer literal, returns exactly `[std::chrono::hours](http://en.cppreference.com/w/cpp/chrono/duration)(hrs)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::hours](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | hrs | - | the number of hours | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::hours operator ""h(unsigned long long h) { return std::chrono::hours(h); } constexpr std::chrono::duration<long double, ratio<3600,1>> operator ""h(long double h) { return std::chrono::duration<long double, std::ratio<3600,1>>(h); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; auto day = 24h; auto halfhour = 0.5h; std::cout << "one day is " << day.count() << " hours\n" << "half an hour is " << halfhour.count() << " hours\n"; } ``` Output: ``` one day is 24 hours half an hour is 0.5 hours ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | cpp std::chrono::weekday_last std::chrono::weekday\_last ========================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class weekday_last; ``` | | (since C++20) | The class `weekday_last` represents the last weekday of some month. `weekday_last` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](weekday_last/weekday_last "cpp/chrono/weekday last/weekday last") | constructs a `weekday_last` object (public member function) | | [weekday](weekday_last/weekday "cpp/chrono/weekday last/weekday") | accesses the stored [`weekday`](weekday "cpp/chrono/weekday") (public member function) | | [ok](weekday_last/ok "cpp/chrono/weekday last/ok") | checks if the stored [`weekday`](weekday "cpp/chrono/weekday") is valid (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](weekday_last/operator_cmp "cpp/chrono/weekday last/operator cmp") (C++20) | compares two `weekday_last` values (function) | | [operator<<](weekday_last/operator_ltlt "cpp/chrono/weekday last/operator ltlt") (C++20) | outputs a `weekday_last` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::weekday\_last>](weekday_last/formatter "cpp/chrono/weekday last/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday_last` according to the provided format (class template specialization) |
programming_docs
cpp std::chrono::gps_clock std::chrono::gps\_clock ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class gps_clock; ``` | | (since C++20) | The clock `std::chrono::gps_clock` is a [Clock](../named_req/clock "cpp/named req/Clock") that represents Global Positioning System (GPS) time. It measures time since 00:00:00, 6 January 1980 UTC. Leap seconds are not inserted into GPS. Thus, every time a leap second is inserted into UTC, UTC falls another second behind GPS. As of December 2017, UTC is 18 seconds behind GPS, reflecting the 18 leap seconds inserted between 1980 and 2017. Thus, 2018-01-01 00:00:00 UTC is equivalent to 2018-01-01 00:00:18 GPS. GPS is a constant 19 seconds behind [TAI](tai_clock "cpp/chrono/tai clock"). `gps_clock` meets the [Clock](../named_req/clock "cpp/named req/Clock") requirements. It does not meet the [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock") requirements unless the implementation can guarantee that [`now()`](gps_clock/now "cpp/chrono/gps clock/now") does not throw an exception. ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using gps_time = std::chrono::time_point<std::chrono::gps_clock, Duration>; ``` | | (since C++20) | | ``` using gps_seconds = gps_time<std::chrono::seconds>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::gps\_time)](gps_clock/operator_ltlt "cpp/chrono/gps clock/operator ltlt") (C++20) | performs stream output on a gps\_time (function template) | | [from\_stream(std::chrono::gps\_time)](gps_clock/from_stream "cpp/chrono/gps clock/from stream") (C++20) | parses a gps\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::gps\_time>](gps_clock/formatter "cpp/chrono/gps clock/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `gps_time` according to the provided format (class template specialization) | ### Member types | Member type | Definition | | --- | --- | | `rep` | signed 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>`, capable of representing negative durations | | `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::gps\_clock>` | ### Member constants | | | | --- | --- | | constexpr bool is\_steady [static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](gps_clock/now "cpp/chrono/gps clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) | ### Member functions | | | | --- | --- | | [now](gps_clock/now "cpp/chrono/gps clock/now") [static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current point in time (public static member function) | | [to\_utc](gps_clock/to_utc "cpp/chrono/gps clock/to utc") [static] | converts a `gps_time` to `utc_time` (public static member function) | | [from\_utc](gps_clock/from_utc "cpp/chrono/gps clock/from utc") [static] | converts a `utc_time` to `gps_time` (public static member function) | cpp std::chrono::tzdb std::chrono::tzdb ================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct tzdb; ``` | | (since C++20) | The class `tzdb` represents a copy of the [IANA time zone database](https://www.iana.org/time-zones). Users cannot construct a `tzdb` and can only obtain read-only access to one via the free functions `std::chrono::get_tzdb_list` and `std::chrono::get_tzdb`. ### Member objects | Member object | Description | | --- | --- | | `version` | A `[std::string](../string/basic_string "cpp/string/basic string")` that contains the version of the database | | `zones` | A sorted `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<[std::chrono::time\_zone](http://en.cppreference.com/w/cpp/chrono/time_zone)>` containing description of time zones | | `links` | A sorted `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<[std::chrono::time\_zone\_link](http://en.cppreference.com/w/cpp/chrono/time_zone_link)>` containing description of alternative names of time zones (links) | | `leap_seconds` | A sorted `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<[std::chrono::leap\_second](http://en.cppreference.com/w/cpp/chrono/leap_second)>` containing description of leap seconds | ### Member functions | | | | --- | --- | | [locate\_zone](tzdb/locate_zone "cpp/chrono/tzdb/locate zone") | locate a time zone with the given name (public member function) | | [current\_zone](tzdb/current_zone "cpp/chrono/tzdb/current zone") | return the local time zone (public member function) | cpp std::chrono::clock_cast std::chrono::clock\_cast ======================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class Dest, class Source, class Duration> auto clock_cast(const std::chrono::time_point<Source, Duration>& t); ``` | | (since C++20) | Converts the time point `t` of a clock `Source` to an equivalent time point of the clock `Dest`, using `[std::chrono::system\_clock](system_clock "cpp/chrono/system clock")` and/or `std::chrono::utc_clock` as intermediaries if necessary. * If the expression `[std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<Dest, Source>{}(t)` is well-formed, returns the result of that expression. * Otherwise, if at least one of the following two expressions are well-formed, then + If both expressions are well-formed, the conversion is ambiguous, and the program is ill-formed. + Otherwise, exactly one of the two expressions is well-formed; the result of that expression is returned. 1) `[std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<Dest, [std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<[std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock), Source>{}(t))` 2) `[std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<Dest, [std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<[std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock), Source>{}(t))` * Otherwise, if at least one of the following two expressions are well-formed, then + If both expressions are well-formed, the conversion is ambiguous, and the program is ill-formed. + Otherwise, exactly one of the two expressions is well-formed; the result of that expression is returned. 1) `[std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<Dest, [std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<[std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock), [std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion). <[std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock), Source>{}(t)))` 2) `[std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<Dest, [std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion)<[std::chrono::system\_clock](http://en.cppreference.com/w/cpp/chrono/system_clock), [std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock)>{}( [std::chrono::clock\_time\_conversion](http://en.cppreference.com/w/cpp/chrono/clock_time_conversion). <[std::chrono::utc\_clock](http://en.cppreference.com/w/cpp/chrono/utc_clock), Source>{}(t)))` * Otherwise, this function does not participate in overload resolution. ### Return value The result of the conversion, determined as described above. ### Example ### See also | | | | --- | --- | | [clock\_time\_conversion](clock_time_conversion "cpp/chrono/clock time conversion") (C++20) | traits class defining how to convert time points of one clock to another (class template) | cpp std::chrono::tai_clock std::chrono::tai\_clock ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class tai_clock; ``` | | (since C++20) | The clock `std::chrono::tai_clock` is a [Clock](../named_req/clock "cpp/named req/Clock") that represents International Atomic Time (TAI). It measures time since 00:00:00, 1 January 1958, and is offset 10 seconds ahead of UTC at that date (i.e., its epoch, 1958-01-01 00:00:00 TAI, is 1957-12-31 23:59:50 UTC). Leap seconds are not inserted into TAI. Thus, every time a leap second is inserted into UTC, UTC falls another second behind TAI. As of December 2017, UTC is 37 seconds behind TAI, reflecting the 10-second initial offset and the 27 leap seconds inserted between 1958 and 2017. Thus, 2018-01-01 00:00:00 UTC is equivalent to 2018-01-01 00:00:37 TAI. `tai_clock` meets the [Clock](../named_req/clock "cpp/named req/Clock") requirements. It does not meet the [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock") requirements unless the implementation can guarantee that [`now()`](tai_clock/now "cpp/chrono/tai clock/now") does not throw an exception. ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using tai_time = std::chrono::time_point<std::chrono::tai_clock, Duration>; ``` | | (since C++20) | | ``` using tai_seconds = tai_time<std::chrono::seconds>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::tai\_time)](tai_clock/operator_ltlt "cpp/chrono/tai clock/operator ltlt") (C++20) | performs stream output on a tai\_time (function template) | | [from\_stream(std::chrono::tai\_time)](tai_clock/from_stream "cpp/chrono/tai clock/from stream") (C++20) | parses a tai\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::tai\_time>](tai_clock/formatter "cpp/chrono/tai clock/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `tai_time` according to the provided format (class template specialization) | ### Member types | Member type | Definition | | --- | --- | | `rep` | signed 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>`, capable of representing negative durations | | `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::tai\_clock>` | ### Member constants | | | | --- | --- | | constexpr bool is\_steady [static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](tai_clock/now "cpp/chrono/tai clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) | ### Member functions | | | | --- | --- | | [now](tai_clock/now "cpp/chrono/tai clock/now") [static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current point in time (public static member function) | | [to\_utc](tai_clock/to_utc "cpp/chrono/tai clock/to utc") [static] | converts `tai_time` to `utc_time` (public static member function) | | [from\_utc](tai_clock/from_utc "cpp/chrono/tai clock/from utc") [static] | converts `utc_time` to `tai_time` (public static member function) | cpp std::chrono::year_month_weekday_last std::chrono::year\_month\_weekday\_last ======================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class year_month_weekday_last; ``` | | (since C++20) | The class `year_month_weekday_last` represents the last weekday of a specific year and month. It is a field-based time point, with a resolution of `std::chrono::days`, except that it is limited to pointing to the last weekday of a year and 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_weekday_last` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](year_month_weekday_last/year_month_weekday_last "cpp/chrono/year month weekday last/year month weekday last") | constructs a `year_month_weekday_last` (public member function) | | [operator+=operator-=](year_month_weekday_last/operator_arith "cpp/chrono/year month weekday last/operator arith") | modifies the time point by some number of months or years (public member function) | | [yearmonthweekdayweekday\_last](year_month_weekday_last/accessors "cpp/chrono/year month weekday last/accessors") | accesses the fields of this object (public member function) | | [operator sys\_daysoperator local\_days](year_month_weekday_last/operator_days "cpp/chrono/year month weekday last/operator days") | converts to a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` (public member function) | | [ok](year_month_weekday_last/ok "cpp/chrono/year month weekday last/ok") | checks whether this object represents a valid date (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](year_month_weekday_last/operator_cmp "cpp/chrono/year month weekday last/operator cmp") (C++20) | compares two `year_month_weekday_last` values (function) | | [operator+operator-](year_month_weekday_last/operator_arith_2 "cpp/chrono/year month weekday last/operator arith 2") (C++20) | adds or subtracts a `year_month_weekday_last` and some number of years or months (function) | | [operator<<](year_month_weekday_last/operator_ltlt "cpp/chrono/year month weekday last/operator ltlt") (C++20) | outputs a `year_month_weekday_last` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::year\_month\_weekday\_last>](year_month_weekday_last/formatter "cpp/chrono/year month weekday last/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_weekday_last` according to the provided format (class template specialization) | cpp std::chrono::treat_as_floating_point std::chrono::treat\_as\_floating\_point ======================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class Rep> struct treat_as_floating_point : std::is_floating_point<Rep> {}; ``` | | (since C++11) | The `std::chrono::treat_as_floating_point` trait helps determine if a duration can be converted to another duration with a different tick period. Implicit conversions between two durations normally depends on the tick period of the durations. However, implicit conversions can happen regardless of tick period if `std::chrono::treat_as_floating_point<Rep>::value == true`. ### Helper variable template | | | | | --- | --- | --- | | ``` template< class Rep > inline constexpr bool treat_as_floating_point_v = treat_as_floating_point<Rep>::value; ``` | | (since C++17) | ### Specializations `std::chrono::treat_as_floating_point` may be specialized for program-defined types. ### Example ``` #include <iostream> #include <chrono> #include <thread> void timed_piece_of_code() { std::chrono::milliseconds simulated_work(2); std::this_thread::sleep_for(simulated_work); } int main() { auto start = std::chrono::high_resolution_clock::now(); std::cout << "Running some timed piece of code..." << '\n'; timed_piece_of_code(); auto stop = std::chrono::high_resolution_clock::now(); // A floating point milliseconds type using FpMilliseconds = std::chrono::duration<float, std::chrono::milliseconds::period>; static_assert(std::chrono::treat_as_floating_point<FpMilliseconds::rep>::value, "Rep required to be floating point"); // Note that implicit conversion is not allowed here auto i_ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); // Note that implicit conversion is allowed here auto f_ms = FpMilliseconds(stop - start); std::cout << "Timing stats: " << '\n'; std::cout << " Time in milliseconds, using default rep: " << i_ms.count() << '\n'; std::cout << " Time in milliseconds, using floating point rep: " << f_ms.count() << '\n'; } ``` Possible output: ``` Running some timed piece of code... Timing stats: Time in milliseconds, using default rep: 2 Time in milliseconds, using floating point rep: 2.57307 ``` ### See also | | | --- | | | cpp std::literals::chrono_literals::operator""s std::literals::chrono\_literals::operator""s ============================================ | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr chrono::seconds operator "" s(unsigned long long secs); ``` | (1) | (since C++14) | | ``` constexpr chrono::duration</*unspecified*/> operator "" s(long double secs); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing seconds. 1) integer literal, returns exactly `[std::chrono::seconds](http://en.cppreference.com/w/cpp/chrono/duration)(secs)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::seconds](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | secs | - | the number of seconds | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::seconds operator ""s(unsigned long long s) { return std::chrono::seconds(s); } constexpr std::chrono::duration<long double> operator ""s(long double s) { return std::chrono::duration<long double>(s); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. `[std::string](../string/basic_string "cpp/string/basic string")` also defines `operator""s`, to represent literal objects of type `std::string`, but it is a string literal: `10s` is ten seconds, but `"10"s` is a two-character string. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; std::chrono::seconds halfmin = 30s; std::cout << "Half a minute is " << halfmin.count() << " seconds.\n" "A minute and a second is " << (1min + 1s).count() << " seconds.\n"; std::chrono::duration moment = 0.1s; std::cout << "A moment is " << moment.count() << " seconds.\n" "And thrice as much is " << (moment + 0.2s).count() << " seconds.\n"; } ``` Output: ``` Half a minute is 30 seconds. A minute and a second is 61 seconds. A moment is 0.1 seconds. And thrice as much is 0.3 seconds. ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) |
programming_docs
cpp std::chrono::year std::chrono::year ================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class year; ``` | | (since C++20) | The class `year` represents a year in the [proleptic Gregorian calendar](https://en.wikipedia.org/wiki/proleptic_Gregorian_calendar "enwiki:proleptic Gregorian calendar"). Its range is [-32767, 32767]. `year` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](year/year "cpp/chrono/year/year") | constructs a `year` (public member function) | | [operator++operator++(int)operator--operator--(int)](year/operator_inc_dec "cpp/chrono/year/operator inc dec") | increments or decrements the year (public member function) | | [operator+=operator-=](year/operator_arith "cpp/chrono/year/operator arith") | adds or subtracts a number of years from a `year` (public member function) | | [operator+operator-](year/operator_sign "cpp/chrono/year/operator sign") | applies unary operators to `year` (public member function) | | [is\_leap](year/is_leap "cpp/chrono/year/is leap") | determines if the year is a leap year (public member function) | | [operator int](year/operator_int "cpp/chrono/year/operator int") | retrieve the year value (public member function) | | [ok](year/ok "cpp/chrono/year/ok") | checks if the stored year value is valid (public member function) | | [min](year/min "cpp/chrono/year/min") [static] | returns the smallest possible year value (public static member function) | | [max](year/max "cpp/chrono/year/max") [static] | returns the largest possible `year` (public static member function) | ### Non-member functions | | | | --- | --- | | [operator==operator<=>](year/operator_cmp "cpp/chrono/year/operator cmp") (C++20) | compares two `year` values (function) | | [operator+operator-](year/operator_arith_2 "cpp/chrono/year/operator arith 2") (C++20) | performs arithmetic on `year`s (function) | | [operator<<](year/operator_ltlt "cpp/chrono/year/operator ltlt") (C++20) | outputs a `year` into a stream (function template) | | [from\_stream](year/from_stream "cpp/chrono/year/from stream") (C++20) | parses a `year` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::year>](year/formatter "cpp/chrono/year/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year` according to the provided format (class template specialization) | ### Literals | Defined in inline namespace `std::literals::chrono_literals` | | --- | | [operator""y](operator%22%22y "cpp/chrono/operator\"\"y") (C++20) | A `std::chrono::year` literal representing a particular year (function) | cpp std::chrono::choose std::chrono::choose =================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` enum class choose { earliest, latest }; ``` | | (since C++20) | The scoped enumeration `choose` can be passed to certain member functions of `std::chrono::time_zone` and `std::chrono::zoned_time` to control how ambiguous or nonexistent local times should be resolved. Passing `choose::earliest` causes the earlier time point to be returned, while passing `choose::latest` causes the later time point to be returned. (For nonexistent local times, these two time points are identical.). If a `choose` is not passed and an ambiguous or nonexistent local time is encountered, a `std::chrono::ambiguous_local_time` or `std::chrono::nonexistent_local_time` exception (as applicable) will be thrown. ### See also | | | | --- | --- | | [(constructor)](zoned_time/zoned_time "cpp/chrono/zoned time/zoned time") | constructs a `zoned_time` (public member function of `std::chrono::zoned_time<Duration,TimeZonePtr>`) | | [to\_sys](time_zone/to_sys "cpp/chrono/time zone/to sys") | converts a `local_time` in this time zone to a `sys_time` (public member function of `std::chrono::time_zone`) | cpp std::chrono::tzdb_list std::chrono::tzdb\_list ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class tzdb_list; ``` | | (since C++20) | `tzdb_list` is a singleton list of `std::chrono::tzdb`s, each of which represents a copy of the IANA time zone database. Users cannot construct a `tzdb_list` and can only obtain access to one via the `std::chrono::get_tzdb_list` free function. ### Member types | Member type | Definition | | --- | --- | | `const_iterator` | constant [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") whose value type is `std::chrono::tzdb` | ### Member functions | | | | --- | --- | | (constructor) (deleted) | copy constructor is defined as deleted (public member function) | | operator= (deleted) | copy assignment operator is defined as deleted (public member function) | | [front](tzdb_list/front "cpp/chrono/tzdb list/front") | access the first element (public member function) | | [erase\_after](tzdb_list/erase_after "cpp/chrono/tzdb list/erase after") | erases an element after an element (public member function) | | [begincbegin](tzdb_list/begin "cpp/chrono/tzdb list/begin") | returns an iterator to the beginning of the list (public member function) | | [endcend](tzdb_list/end "cpp/chrono/tzdb list/end") | returns an iterator past the end of the list (public member function) | cpp std::chrono::month_weekday std::chrono::month\_weekday =========================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class month_weekday; ``` | | (since C++20) | The class `month_weekday` represents the n-th weekday of a specific month, of some yet to be specified year. `month_weekday` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](month_weekday/month_weekday "cpp/chrono/month weekday/month weekday") | constructs a `month_weekday` (public member function) | | [monthweekday\_indexed](month_weekday/accessors "cpp/chrono/month weekday/accessors") | retrieves the stored [`month`](month "cpp/chrono/month") and [`weekday_indexed`](weekday_indexed "cpp/chrono/weekday indexed") values (public member function) | | [ok](month_weekday/ok "cpp/chrono/month weekday/ok") | checks whether the contained [`month`](month "cpp/chrono/month") and [`weekday_indexed`](weekday_indexed "cpp/chrono/weekday indexed") are valid (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](month_weekday/operator_cmp "cpp/chrono/month weekday/operator cmp") (C++20) | compares two `month_weekday` values (function) | | [operator<<](month_weekday/operator_ltlt "cpp/chrono/month weekday/operator ltlt") (C++20) | outputs a `month_weekday` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::month\_weekday>](month_weekday/formatter "cpp/chrono/month weekday/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_weekday` according to the provided format (class template specialization) | cpp std::chrono::year_month_weekday std::chrono::year\_month\_weekday ================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class year_month_weekday; ``` | | (since C++20) | The class `year_month_weekday` represents the n-th weekday of a specific year and month. It is a field-based time point, with a resolution of `std::chrono::days`. `std::chrono::years`- and `std::chrono::months`-oriented arithmetic are supported directly. An implicit conversion to and from `std::chrono::sys_days` allows `std::chrono::days`-oriented arithmetic to be performed efficiently. `year_month_weekday` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](year_month_weekday/year_month_weekday "cpp/chrono/year month weekday/year month weekday") | constructs a `year_month_weekday` (public member function) | | [operator+=operator-=](year_month_weekday/operator_arith "cpp/chrono/year month weekday/operator arith") | modifies the time point by some number of months or years (public member function) | | [yearmonthweekdayindexweekday\_indexed](year_month_weekday/accessors "cpp/chrono/year month weekday/accessors") | accesses the fields of this object (public member function) | | [operator sys\_daysoperator local\_days](year_month_weekday/operator_days "cpp/chrono/year month weekday/operator days") | converts to a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` (public member function) | | [ok](year_month_weekday/ok "cpp/chrono/year month weekday/ok") | checks whether this object represents a valid date (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](year_month_weekday/operator_cmp "cpp/chrono/year month weekday/operator cmp") (C++20) | compares two `year_month_weekday` values (function) | | [operator+operator-](year_month_weekday/operator_arith_2 "cpp/chrono/year month weekday/operator arith 2") (C++20) | adds or subtracts a `year_month_weekday` and some number of years or months (function) | | [operator<<](year_month_weekday/operator_ltlt "cpp/chrono/year month weekday/operator ltlt") (C++20) | outputs a `year_month_weekday` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::year\_month\_weekday>](year_month_weekday/formatter "cpp/chrono/year month weekday/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_weekday` according to the provided format (class template specialization) | cpp std::chrono::time_zone_link std::chrono::time\_zone\_link ============================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class time_zone_link; ``` | | (since C++20) | The class `time_zone_link` represents an alternative name for a time zone. Users cannot construct `time_zone_link` objects. The library implementation creates `time_zone_link` objects when it initializes the time zone database and provides `const` access to these objects. `time_zone_link` is not copyable but does have a defaulted move constructor and a defaulted move assignment operator. However, as users have only `const` access to `time_zone_link` objects, these functions cannot be called in user code without invoking [undefined behavior](../language/ub "cpp/language/ub"). ### Member functions | | | | --- | --- | | [nametarget](time_zone_link/accessors "cpp/chrono/time zone link/accessors") | accesses the name and target of this `time_zone_link` (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](time_zone_link/operator_cmp "cpp/chrono/time zone link/operator cmp") (C++20) | compares two `time_zone_link` objects (function) | cpp std::literals::chrono_literals::operator""min std::literals::chrono\_literals::operator""min ============================================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr chrono::minutes operator "" min( unsigned long long mins ); ``` | (1) | (since C++14) | | ``` constexpr chrono::duration</*unspecified*/, ratio<60,1>> operator "" min( long double mins ); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing minutes. 1) integer literal, returns exactly `[std::chrono::minutes](http://en.cppreference.com/w/cpp/chrono/duration)(mins)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::minutes](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | mins | - | the number of minutes | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::minutes operator ""min(unsigned long long m) { return std::chrono::minutes(m); } constexpr std::chrono::duration<long double, std::ratio<60,1>> operator ""min(long double m) { return std::chrono::duration<long double, ratio<60,1>> (m); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; auto lesson = 45min; auto halfmin = 0.5min; std::cout << "one lesson is " << lesson.count() << " minutes\n" << "half a minute is " << halfmin.count() << " minutes\n"; } ``` Output: ``` one lesson is 45 minutes half a minute is 0.5 minutes ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | cpp std::literals::chrono_literals::operator""us std::literals::chrono\_literals::operator""us ============================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::microseconds operator "" us(unsigned long long us); ``` | (1) | (since C++14) | | ``` constexpr std::chrono::duration</*unspecified*/, std::micro> operator "" us(long double us); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing microseconds. 1) integer literal, returns exactly `[std::chrono::microseconds](http://en.cppreference.com/w/cpp/chrono/duration)(us)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::microseconds](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | us | - | the number of microseconds | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::microseconds operator ""us(unsigned long long us) { return std::chrono::microseconds(us); } constexpr std::chrono::duration<long double, std::micro> operator ""us(long double us) { return std::chrono::duration<long double, std::micro>(us); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; auto d1 = 250us; std::chrono::microseconds d2 = 1ms; std::cout << "250us = " << d1.count() << " microseconds\n" << "1ms = " << d2.count() << " microseconds\n"; } ``` Output: ``` 250us = 250 microseconds 1ms = 1000 microseconds ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | cpp std::literals::chrono_literals::operator""ns std::literals::chrono\_literals::operator""ns ============================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::nanoseconds operator "" ns(unsigned long long nsec); ``` | (1) | (since C++14) | | ``` constexpr std::chrono::duration</*unspecified*/, std::nano> operator "" ns(long double nsec); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing nanoseconds. 1) integer literal, returns exactly `[std::chrono::nanoseconds](http://en.cppreference.com/w/cpp/chrono/duration)(nsec)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::nanoseconds](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | nsec | - | the number of nanoseconds | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::nanoseconds operator ""ns(unsigned long long ns) { return std::chrono::nanoseconds(ns); } constexpr std::chrono::duration<long double, std::nano> operator ""ns(long double ns) { return std::chrono::duration<long double, std::nano>(ns); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; auto d1 = 250ns; std::chrono::nanoseconds d2 = 1us; std::cout << "250ns = " << d1.count() << " nanoseconds\n" << "1us = " << d2.count() << " nanoseconds\n"; } ``` Output: ``` 250ns = 250 nanoseconds 1us = 1000 nanoseconds ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | cpp std::chrono::month_weekday_last std::chrono::month\_weekday\_last ================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class month_weekday_last; ``` | | (since C++20) | The class `month_weekday_last` represents the last weekday of a specific month, of some yet to be specified year. `month_weekday_last` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](month_weekday_last/month_weekday_last "cpp/chrono/month weekday last/month weekday last") | constructs a `month_weekday_last` (public member function) | | [monthweekday\_last](month_weekday_last/accessors "cpp/chrono/month weekday last/accessors") | retrieves the stored [`month`](month "cpp/chrono/month") and [`weekday_last`](weekday_last "cpp/chrono/weekday last") values (public member function) | | [ok](month_weekday_last/ok "cpp/chrono/month weekday last/ok") | checks whether the contained [`month`](month "cpp/chrono/month") and [`weekday_last`](weekday_last "cpp/chrono/weekday last") are valid (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](month_weekday_last/operator_cmp "cpp/chrono/month weekday last/operator cmp") (C++20) | compares two `month_weekday_last` values (function) | | [operator<<](month_weekday_last/operator_ltlt "cpp/chrono/month weekday last/operator ltlt") (C++20) | outputs a `month_weekday_last` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::month\_weekday\_last>](month_weekday_last/formatter "cpp/chrono/month weekday last/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_weekday_last` according to the provided format (class template specialization) |
programming_docs
cpp std::chrono::weekday std::chrono::weekday ==================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class weekday; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Sunday{0}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Monday{1}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Tuesday{2}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Wednesday{3}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Thursday{4}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Friday{5}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::weekday Saturday{6}; ``` | | (since C++20) | The class `weekday` represent a day of the week in the Gregorian calendar. Its normal range is [0, 6], for Sunday through Saturday, but it can hold any value in the range [0, 255]. Seven named constants are predefined in the `std::chrono` namespace for the seven days of the week. `weekday` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](weekday/weekday "cpp/chrono/weekday/weekday") | constructs a `weekday` (public member function) | | [operator++operator++(int)operator--operator--(int)](weekday/operator_inc_dec "cpp/chrono/weekday/operator inc dec") | increments or decrements the weekday (public member function) | | [operator+=operator-=](weekday/operator_arith "cpp/chrono/weekday/operator arith") | adds or subtracts a number of days (public member function) | | [c\_encodingiso\_encoding](weekday/encoding "cpp/chrono/weekday/encoding") | retrieves the stored weekday valueretrieves ISO 8601 weekday value (public member function) | | [ok](weekday/ok "cpp/chrono/weekday/ok") | checks if the stored weekday value is valid (public member function) | | [operator[]](weekday/operator_at "cpp/chrono/weekday/operator at") | convenience syntax for constructing a [`weekday_indexed`](weekday_indexed "cpp/chrono/weekday indexed") or [`weekday_last`](weekday_last "cpp/chrono/weekday last") from this `weekday` (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==](weekday/operator_cmp "cpp/chrono/weekday/operator cmp") (C++20) | compares two `weekday` values (function) | | [operator+operator-](weekday/operator_arith_2 "cpp/chrono/weekday/operator arith 2") (C++20) | performs arithmetic on `weekday`s (function) | | [operator<<](weekday/operator_ltlt "cpp/chrono/weekday/operator ltlt") (C++20) | outputs a `weekday` into a stream (function template) | | [from\_stream](weekday/from_stream "cpp/chrono/weekday/from stream") (C++20) | parses a `weekday` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::weekday>](weekday/formatter "cpp/chrono/weekday/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday` according to the provided format (class template specialization) | cpp std::chrono::locate_zone std::chrono::locate\_zone ========================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` const std::chrono::time_zone* locate_zone(std::string_view tz_name); ``` | | (since C++20) | Convenience function for locating a time zone in the time zone database. Equivalent to `[std::chrono::get\_tzdb](http://en.cppreference.com/w/cpp/chrono/tzdb_functions)().locate\_zone(tz_name)`. ### Exceptions `[std::runtime\_error](../error/runtime_error "cpp/error/runtime error")` if the specified time zone cannot be found, or if this is the first reference to the time zone database and the time zone database cannot be initialized. ### Notes A call to this function that is the first reference to the time zone database will cause it to be initialized. ### See also | | | | --- | --- | | [locate\_zone](tzdb/locate_zone "cpp/chrono/tzdb/locate zone") | locate a time zone with the given name (public member function of `std::chrono::tzdb`) | | [get\_tzdbget\_tzdb\_listreload\_tzdbremote\_version](tzdb_functions "cpp/chrono/tzdb functions") (C++20) | accesses and controls the global time zone database information (function) | cpp std::chrono::is_clock std::chrono::is\_clock ====================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class T > struct is_clock; ``` | | (since C++20) | If `T` satisfies the [Clock](../named_req/clock "cpp/named req/Clock") requirements, provides the member constant `value` equal `true`. For any other type, `value` is `false`. For the purpose of this trait, the extent to which an implementation determines that a type cannot meet the [Clock](../named_req/clock "cpp/named req/Clock") requirements is unspecified, except that a minimum `T` shall not qualify as a [Clock](../named_req/clock "cpp/named req/Clock") unless it meets all of the following conditions: * The *qualified-id*s `T::rep`, `T::period`, `T::duration`, and `T::time_point` are all valid and each denotes a type; * The expressions `T::is_steady` and `T::now()` are each well-formed when treated as an unevaluated operand. The behavior of a program that adds specializations for `is_clock` or `is_clock_v` is undefined. ### Template parameters | | | | | --- | --- | --- | | T | - | a type to check | ### Helper variable template | | | | | --- | --- | --- | | ``` template< class T > inline constexpr bool is_clock_v = is_clock<T>::value; ``` | | (since C++20) | Inherited from [std::integral\_constant](../types/integral_constant "cpp/types/integral constant") ---------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `true` if `T` satisfies the [Clock](../named_req/clock "cpp/named req/Clock") requirements , `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> struct is_clock : std::false_type {}; template<class T> requires requires { typename T::rep; typename T::period; typename T::duration; typename T::time_point; T::is_steady; T::now(); } struct is_clock<T> : std::true_type {}; ``` | cpp std::literals::chrono_literals::operator""y std::literals::chrono\_literals::operator""y ============================================ | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::year operator ""y( unsigned long long y ) noexcept; ``` | (1) | (since C++20) | Forms a `std::chrono::year` literal representing a year in the proleptic Gregorian calendar. ### Parameters | | | | | --- | --- | --- | | y | - | the year value | ### Return value A `std::chrono::year` initialized from `int(y)`. If `y` is not in the range `[-32767, 32767]`, the stored value is unspecified. ### Possible implementation | | | --- | | ``` constexpr std::chrono::year operator ""y(unsigned long long y) noexcept { return std::chrono::year(static_cast<int>(y)); } ``` | ### Notes This operator is declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to this operator can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::literals; std::cout << int(2020y) << ' ' << int(-220y) << ' ' << int(3000y) << ' ' << int(32768y) << ' ' // unspecified << int(65578y) << '\n'; // unspecified } ``` Possible output: ``` 2020 -220 3000 -32768 42 ``` ### See also | | | | --- | --- | | [(constructor)](year/year "cpp/chrono/year/year") | constructs a `year` (public member function of `std::chrono::year`) | cpp std::chrono::year_month std::chrono::year\_month ======================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class year_month; ``` | | (since C++20) | The class `year_month` represents a specific month of a specific year, but with an unspecified day. It is a field-based time point, with a resolution of `std::chrono::months`. `year_month` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](year_month/year_month "cpp/chrono/year month/year month") | constructs a `year_month` (public member function) | | [yearmonth](year_month/accessors "cpp/chrono/year month/accessors") | accesses the stored year and month (public member function) | | [operator+=operator-=](year_month/operator_arith "cpp/chrono/year month/operator arith") | modifies the `year_month` by some number of months or years (public member function) | | [ok](year_month/ok "cpp/chrono/year month/ok") | checks if this `year_month` is valid (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](year_month/operator_cmp "cpp/chrono/year month/operator cmp") (C++20) | compares two `year_month` values (function) | | [operator+operator-](year_month/operator_arith_2 "cpp/chrono/year month/operator arith 2") (C++20) | performs arithmetic on `year_month` (function) | | [operator<<](year_month/operator_ltlt "cpp/chrono/year month/operator ltlt") (C++20) | outputs a `year_month` into a stream (function template) | | [from\_stream](year_month/from_stream "cpp/chrono/year month/from stream") (C++20) | parses a `year_month` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::year\_month>](year_month/formatter "cpp/chrono/year month/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month` according to the provided format (class template specialization) | cpp std::chrono::system_clock std::chrono::system\_clock ========================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class system_clock; ``` | | (since C++11) | Class `std::chrono::system_clock` represents the system-wide real time wall clock. It may not be monotonic: on most systems, the system time can be adjusted at any moment. It is the only C++ clock that has the ability to map its time points to C-style time. `std::chrono::system_clock` meets the requirements of [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock"). | | | | --- | --- | | The epoch of `system_clock` is unspecified, but most implementations use Unix Time (i.e., time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds). | (until C++20) | | `system_clock` measures Unix Time (i.e., time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds). | (since C++20) | ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using sys_time = std::chrono::time_point<std::chrono::system_clock, Duration>; ``` | | (since C++20) | | ``` using sys_seconds = sys_time<std::chrono::seconds>; ``` | | (since C++20) | | ``` using sys_days = sys_time<std::chrono::days>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::sys\_time)](system_clock/operator_ltlt "cpp/chrono/system clock/operator ltlt") (C++20) | performs stream output on a sys\_time (function template) | | [from\_stream(std::chrono::sys\_time)](system_clock/from_stream "cpp/chrono/system clock/from stream") (C++20) | parses a sys\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::sys\_time>](system_clock/formatter "cpp/chrono/system clock/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `sys_time` according to the provided format (class template specialization) | ### Member types | Member type | Definition | | --- | --- | | `rep` | signed 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>`, capable of representing negative durations | | `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::system\_clock>` | ### Member constants | | | | --- | --- | | constexpr bool is\_steady [static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](system_clock/now "cpp/chrono/system clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) | ### Member functions | | | | --- | --- | | [now](system_clock/now "cpp/chrono/system clock/now") [static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current point in time (public static member function) | | [to\_time\_t](system_clock/to_time_t "cpp/chrono/system clock/to time t") [static] | converts a system clock time point to `[std::time\_t](c/time_t "cpp/chrono/c/time t")` (public static member function) | | [from\_time\_t](system_clock/from_time_t "cpp/chrono/system clock/from time t") [static] | converts `[std::time\_t](c/time_t "cpp/chrono/c/time t")` to a system clock time point (public static member function) | ### Notes The `system_clock`'s time value can be internally adjusted at any time by the operating system, for example due to NTP synchronization or the user changing the system's clock. Daylight Savings Time and time zone changes, however, do not affect it since it is based on the [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) time-zone. ### See also | | | | --- | --- | | [steady\_clock](steady_clock "cpp/chrono/steady clock") (C++11) | monotonic clock that will never be adjusted (class) | | [high\_resolution\_clock](high_resolution_clock "cpp/chrono/high resolution clock") (C++11) | the clock with the shortest tick period available (class) | cpp std::chrono::is_am, std::chrono::is_pm, std::chrono::make12, std::chrono::make24 std::chrono::is\_am, std::chrono::is\_pm, std::chrono::make12, std::chrono::make24 ================================================================================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool is_am( const std::chrono::hours& h ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool is_pm( const std::chrono::hours& h ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::hours make12( const std::chrono::hours& h ) noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::hours make24( const std::chrono::hours& h, bool is_pm ) noexcept; ``` | (4) | (since C++20) | These functions aid in translating between a 12-hour format time of day, and a 24-hour format time of day. 1) Detects whether the 24-hour format time is a.m. (*ante meridiem*, before midday). 2) Detects whether the 24-hour format time is p.m. (*post meridiem*, after midday). 3) Returns the 12-hour equivalent of a 24-hour format time. 4) Returns the 24-hour equivalent of a 12-hour format time `h`, where `is_pm` determines whether the time is p.m. ### Parameters | | | | | --- | --- | --- | | h | - | 12-hour or 24-hour format time to detect | | is\_pm | - | whether the 12-hour format time is p.m. | ### Return value 1) `0h <= h && h <= 11h`. 2) `12h <= h && h <= 23h`. 3) If `h` is in range `[0h, 23h]`, returns the 12-hour equivalent in range `[1h, 12h]`. Otherwise, the return value is unspecified. 4) If `h` is in range `[1h, 12h]`, returns the 24-hour equivalent in range `[0h, 11h]` if `is_pm` is `false`, or in range `[12h, 23h]` otherwise. Otherwise, the return value is unspecified. ### Example ``` #include <iostream> #include <iomanip> #include <utility> #include <chrono> int main() { using namespace std::chrono; static_assert( is_am(10h) && is_am(11h) && !is_am(12h) && !is_am(23h) && !is_pm(10h) && !is_pm(11h) && is_pm(12h) && is_pm(23h) ); std::cout << "make12():\n"; for (const hours hh : { 0h, 1h, 11h, 12h, 13h, 23h }) { const hours am{make12(hh)}; std::cout << std::setw(2) << hh.count() << "h == " << std::setw(2) << am.count() << (is_am(hh) ? "h a.m.\n" : "h p.m.\n"); } std::cout << "\nmake24():\n"; using p = std::pair<hours, bool>; for (const auto& [hh, pm] : { p{1h, 0}, p{12h, 0}, p{1h, 1}, p{12h, 1} }) { std::cout << std::setw(2) << hh.count() << (pm ? "h p.m." : "h a.m.") << " == " << std::setw(2) << make24(hh, pm).count() << "h\n"; } } ``` Output: ``` make12(): 0h == 12h a.m. 1h == 1h a.m. 11h == 11h a.m. 12h == 12h p.m. 13h == 1h p.m. 23h == 11h p.m. make24(): 1h a.m. == 1h 12h a.m. == 0h 1h p.m. == 13h 12h p.m. == 12h ``` cpp std::chrono::parse std::chrono::parse ================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Parsable > /* unspecified */ parse( const CharT* fmt, Parsable& tp ); ``` | (1) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const std::basic_string<CharT, Traits, Alloc>& fmt, Parsable& tp ); ``` | (2) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const CharT* fmt, Parsable& tp, std::basic_string<CharT, Traits, Alloc>& abbrev ); ``` | (3) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const std::basic_string<CharT, Traits, Alloc>& fmt, Parsable& tp, std::basic_string<CharT, Traits, Alloc>& abbrev ); ``` | (4) | (since C++20) | | ``` template< class CharT, class Parsable > /* unspecified */ parse( const CharT* fmt, Parsable& tp, std::chrono::minutes& offset ); ``` | (5) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const std::basic_string<CharT, Traits, Alloc>& fmt, Parsable& tp, std::chrono::minutes& offset ); ``` | (6) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const CharT* fmt, Parsable& tp, std::basic_string<CharT, Traits, Alloc>& abbrev, std::chrono::minutes& offset ); ``` | (7) | (since C++20) | | ``` template< class CharT, class Traits, class Alloc, class Parsable > /* unspecified */ parse( const std::basic_string<CharT, Traits, Alloc>& fmt, Parsable& tp, std::basic_string<CharT, Traits, Alloc>& abbrev, std::chrono::minutes& offset ); ``` | (8) | (since C++20) | Returns an object `manip` of unspecified type such that, given a `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>` object `is`, the expression `is >> manip` calls `from_stream` (unqualified, to enable [argument-dependent lookup](../language/adl "cpp/language/adl")) as follows: 1) `from_stream(is, fmt, tp)` 2) `from_stream(is, fmt.c_str(), tp)` 3) `from_stream(is, fmt, tp, [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(abbrev))` 4) `from_stream(is, fmt.c\_str(), tp, [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(abbrev))` 5) `from_stream(is, fmt, tp, static\_cast<[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT, Traits, Alloc>\*>(nullptr), &offset)` 6) `from_stream(is, fmt.c\_str(), tp, static\_cast<[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT, Traits, Alloc>\*>(nullptr), &offset)` 7) `from_stream(is, fmt, tp, [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(abbrev), &offset)` 8) `from_stream(is, fmt.c\_str(), tp, [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(abbrev), &offset)`. The expression `is >> manip` is an lvalue of type `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>` with the value `is`. These overloads participate in overload resolution only if the corresponding `from_stream` expression is well-formed. Implementations are recommended to make it difficult to use potentially dangling references to the format string, e.g., by making return types non-movable and preventing `operator>>` from accepting lvalues of return types. ### Parameters | | | | | --- | --- | --- | | fmt | - | a format string (see below) | | tp | - | object to hold the parse result | | abbrev | - | string to hold the time zone abbreviation or name corresponding to the `%Z` specifier | | offset | - | duration to represent the offset from UTC corresponding to the `%z` specifier | ### Format string The format string consists of zero or more conversion specifiers and ordinary characters. Each ordinary character, excluding whitespace characters and the terminating null character, matches one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. Each whitespace character matches zero or more whitespace characters in the input stream. Each unmodified conversion specifier begins with a `%` character followed by a character that determines the behavior of the specifier. Some conversion specifiers have a modified form in which an `E` or `O` modifier character is inserted after the `%` character. Some conversion specifiers have a modified form in which a width parameter given as a positive decimal integer (shown as *`N`* below) is inserted after the `%` character. Each conversion specifier causes the matched characters to be interpreted as parts of date and time types according to the table below. A character sequence in the format string that begins with a `%` but does not match one of the conversion specifiers below is interpreted as ordinary characters. If `from_stream` fails to parse everything specified by the format string, or if insufficient information is parsed to specify a complete result, or if parsing discloses contradictory information, `is.setstate([std::ios\_base::failbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate))` is called. The following conversion specifiers are available: | Conversion specifier | Explanation | | --- | --- | | `%%` | Matches a literal `%` character. | | `%n` | Matches one whitespace character. | | `%t` | Matches zero or one whitespace character. | | Year | | `%C` `%*N*C` `%EC` | Parses the century as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%EC` interprets the locale's alternative representation of the century. | | `%y` `%*N*y` `%Ey` `%Oy` | Parses the last two decimal digits of the year. If the century is not otherwise specified (e.g. with %C), values in the range [69, 99] are presumed to refer to the years 1969 to 1999, and values in the range [00, 68] are presumed to refer to the years 2000 to 2068. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified commands `%Ey` and `%Oy` interpret the locale's alternative representation. | | `%Y` `%*N*Y` `%EY` | Parses the year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 4. Leading zeroes are permitted but not required. The modified command `%EY` interprets the locale's alternative representation. | | Month | | `%b``%B``%h` | Parses the locale's full or abbreviated case-insensitive month name. | | `%m` `%*N*m``%Om` | Parses the month as a decimal number (January is `1`). The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%Om` interprets the locale's alternative representation. | | Day | | `%d``%*N*d``%Od``%e` `%*N*e``%Oe` | Parses the day of month as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified commands `%Od` and `%Oe` interpret the locale's alternative representation. | | Day of the week | | `%a``%A` | Parses the locale's full or abbreviated case-insensitive weekday name. | | `%u``%*N*u` | Parses the ISO weekday as a decimal number (1-7), where Monday is `1`. The width *N* specifies the maximum number of characters to read. The default width is 1. Leading zeroes are permitted but not required. | | `%w``%*N*w``%Ow` | Parses the weekday as a decimal number (0-6), where Sunday is `0`. The width *N* specifies the maximum number of characters to read. The default width is 1. Leading zeroes are permitted but not required. The modified command `%Ow` interprets the locale's alternative representation. | | ISO 8601 week-based year | | In ISO 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 | | `%g``%*N*g` | Parses the last two decimal digits of the ISO 8601 week-based year. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. | | `%G``%*N*G` | Parses the ISO 8601 week-based year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 4. Leading zeroes are permitted but not required. | | `%V``%*N*V` | Parses the ISO 8601 week of the year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. | | Week/day of the year | | `%j``%*N*j` | Parses the day of the year as a decimal number (January 1 is `1`). The width *N* specifies the maximum number of characters to read. The default width is 3. Leading zeroes are permitted but not required. | | `%U``%*N*U``%OU` | Parses the week number of the year as a decimal number. The first Sunday of the year is the first day of week 01. Days of the same year prior to that are in week 00. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OU` interprets the locale's alternative representation. | | `%W``%*N*W``%OW` | Parses the week number of the year as a decimal number. The first Monday of the year is the first day of week 01. Days of the same year prior to that are in week 00. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OW` interprets the locale's alternative representation. | | Date | | `%D` | Equivalent to `"%m/%d/%y"`. | | `%F``%*N*F` | Equivalent to `"%Y-%m-%d"`. If the width is specified, it is only applied to the `%Y`. | | `%x``%Ex` | Parses the locale's date representation. The modified command `%Ex` interprets the locale's alternate date representation. | | Time of day | | `%H``%*N*H``%OH` | Parses the hour (24-hour clock) as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OH` interprets the locale's alternative representation. | | `%I``%*N*I``%OI` | Parses the hour (12-hour clock) as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OI` interprets the locale's alternative representation. | | `%M``%*N*M``%OM` | Parses the minute as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OM` interprets the locale's alternative representation. | | `%S``%*N*S``%OS` | Parses the second as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OS` interprets the locale's alternative representation. | | `%p` | Parses the locale's equivalent of the AM/PM designations associated with a 12-hour clock. | | `%R` | Equivalent to `"%H:%M"`. | | `%T` | Equivalent to `"%H:%M:%S"`. | | `%r` | Parses the locale's 12-hour clock time. | | `%X``%EX` | Parses the locale's time representation. The modified command `%EX` interprets the locale's alternate time representation. | | Miscellaneous | | `%c``%Ec` | Parses the locale's date and time representation. The modified command `%Ec` interprets the locale's alternative date and time representation. | | `%z``%Ez``%Oz` | Parses the offset from UTC in the format `[+|-]hh[mm]`. For example `-0430` refers to 4 hours 30 minutes behind UTC and `04` refers to 4 hours ahead of UTC. The modified commands `%Ez` and `%Oz` parses the format `[+|-]h[h][:mm]` (i.e., requiring a `:` between the hours and minutes and making the leading zero for hour optional). | | `%Z` | Parses the time zone abbreviation or name, taken as the longest sequence of characters that only contains the characters `A` through `Z`, `a` through `z`, `0` through `9`, `-`, `+`, `_`, and `/`. | ### 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 3554](https://cplusplus.github.io/LWG/issue3554) | C++20 | overloads for plain null-terminated character type sequences were missing | added | ### See also | | | | --- | --- | | [from\_stream(std::chrono::sys\_time)](system_clock/from_stream "cpp/chrono/system clock/from stream") (C++20) | parses a sys\_time from a stream according to the provided format (function template) | | [from\_stream(std::chrono::utc\_time)](utc_clock/from_stream "cpp/chrono/utc clock/from stream") (C++20) | parses a utc\_time from a stream according to the provided format (function template) | | [from\_stream(std::chrono::tai\_time)](tai_clock/from_stream "cpp/chrono/tai clock/from stream") (C++20) | parses a tai\_time from a stream according to the provided format (function template) | | [from\_stream(std::chrono::gps\_time)](gps_clock/from_stream "cpp/chrono/gps clock/from stream") (C++20) | parses a gps\_time from a stream according to the provided format (function template) | | [from\_stream(std::chrono::file\_time)](file_clock/from_stream "cpp/chrono/file clock/from stream") (C++20) | parses a file\_time from a stream according to the provided format (function template) | | [from\_stream(std::chrono::local\_time)](local_t/from_stream "cpp/chrono/local t/from stream") (C++20) | parses a local\_time from a stream according to the provided format (function template) | | [from\_stream](year/from_stream "cpp/chrono/year/from stream") (C++20) | parses a `year` from a stream according to the provided format (function template) | | [from\_stream](month/from_stream "cpp/chrono/month/from stream") (C++20) | parses a `month` from a stream according to the provided format (function template) | | [from\_stream](day/from_stream "cpp/chrono/day/from stream") (C++20) | parses a `day` from a stream according to the provided format (function template) | | [from\_stream](weekday/from_stream "cpp/chrono/weekday/from stream") (C++20) | parses a `weekday` from a stream according to the provided format (function template) | | [from\_stream](month_day/from_stream "cpp/chrono/month day/from stream") (C++20) | parses a `month_day` from a stream according to the provided format (function template) | | [from\_stream](year_month/from_stream "cpp/chrono/year month/from stream") (C++20) | parses a `year_month` from a stream according to the provided format (function template) | | [from\_stream](year_month_day/from_stream "cpp/chrono/year month day/from stream") (C++20) | parses a `year_month_day` from a stream according to the provided format (function 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::chrono::local_info std::chrono::local\_info ======================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct local_info; ``` | | (since C++20) | The class `local_info` describes the result of converting a `std::chrono::local_time` to a `std::chrono::sys_time`. * If the result of the conversion is unique, then `result == local_info::unique`, `first` is filled out with the correct `std::chrono::sys_info`, and `second` is zero-initialized. * If the `local_time` is nonexistent, then `result == local_info::nonexistent`, `first` is filled out with the `std::chrono::sys_info` that ends just prior to the `local_time`, and `second` is filled out with the `std::chrono::sys_info` that begins just after the `local_time`. * If the `local_time` is ambiguous, then `result == local_info::ambiguous`, `first` is filled out with the `std::chrono::sys_info` that ends just after the `local_time`, and `second` is filled with the `std::chrono::sys_info` that starts just before the `local_time`. This is a low-level data structure; typical conversions from `local_time` to `sys_time` will use it implicitly rather than explicitly. ### Member constants | Name | Value | | --- | --- | | constexpr int unique [static] | 0 (public static member constant) | | constexpr int nonexistent [static] | 1 (public static member constant) | | constexpr int ambiguous [static] | 2 (public static member constant) | ### Member objects | Member object | Type | | --- | --- | | `result` | `int` | | `first`, `second` | `std::chrono::sys_info` | ### Nonmember functions | | | | --- | --- | | [operator<<](local_info/operator_ltlt "cpp/chrono/local info/operator ltlt") (C++20) | outputs a `local_info` into a stream (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::local\_info>](local_info/formatter "cpp/chrono/local info/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `local_info` according to the provided format (class template specialization) | cpp std::chrono::month_day std::chrono::month\_day ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class month_day; ``` | | (since C++20) | The class `month_day` represents a specific day of a specific month, of some yet to be specified year. `month_day` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](month_day/month_day "cpp/chrono/month day/month day") | constructs a `month_day` (public member function) | | [monthday](month_day/accessors "cpp/chrono/month day/accessors") | retrieve the stored [`month`](month "cpp/chrono/month") and [`day`](day "cpp/chrono/day") values (public member function) | | [ok](month_day/ok "cpp/chrono/month day/ok") | checks if the `month_day` is valid (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](month_day/operator_cmp "cpp/chrono/month day/operator cmp") (C++20) | compares two `month_day` values (function) | | [operator<<](month_day/operator_ltlt "cpp/chrono/month day/operator ltlt") (C++20) | outputs a `month_day` into a stream (function template) | | [from\_stream](month_day/from_stream "cpp/chrono/month day/from stream") (C++20) | parses a `month_day` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::month\_day>](month_day/formatter "cpp/chrono/month day/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_day` according to the provided format (class template specialization) | cpp std::chrono::time_point std::chrono::time\_point ======================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class Clock, class Duration = typename Clock::duration > class time_point; ``` | | (since C++11) | Class template `std::chrono::time_point` represents a point in time. It is implemented as if it stores a value of type `Duration` indicating the time interval from the start of the `Clock`'s epoch. | | | | --- | --- | | `Clock` must meet the requirements for [Clock](../named_req/clock "cpp/named req/Clock") or be `std::chrono::local_t` (since C++20). | (until C++23) | ### Member types | Member type | Definition | | --- | --- | | `clock` | `Clock`, the clock on which this time point is measured | | `duration` | `Duration`, a `[std::chrono::duration](duration "cpp/chrono/duration")` type used to measure the time since epoch | | `rep` | `Rep`, an arithmetic type representing the number of ticks of the duration | | `period` | `Period`, a `[std::ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` type representing the tick period of the duration | ### Member functions | | | | --- | --- | | [(constructor)](time_point/time_point "cpp/chrono/time point/time point") | constructs a new time point (public member function) | | [time\_since\_epoch](time_point/time_since_epoch "cpp/chrono/time point/time since epoch") | returns the time point as duration since the start of its clock (public member function) | | [operator+=operator-=](time_point/operator_arith "cpp/chrono/time point/operator arith") | modifies the time point by the given duration (public member function) | | [operator++operator++(int)operator--operator--(int)](time_point/operator_inc_dec "cpp/chrono/time point/operator inc dec") (C++20) | increments or decrements the duration (public member function) | | [min](time_point/min "cpp/chrono/time point/min") [static] | returns the time point corresponding to the smallest duration (public static member function) | | [max](time_point/max "cpp/chrono/time point/max") [static] | returns the time point corresponding to the largest duration (public static member function) | ### Non-member functions | | | | --- | --- | | [operator+operator-](time_point/operator_arith2 "cpp/chrono/time point/operator arith2") (C++11) | performs add and subtract operations involving a time point (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](time_point/operator_cmp "cpp/chrono/time point/operator cmp") (C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares two time points (function template) | | [time\_point\_cast](time_point/time_point_cast "cpp/chrono/time point/time point cast") (C++11) | converts a time point to another time point on the same clock, with a different duration (function template) | | [floor(std::chrono::time\_point)](time_point/floor "cpp/chrono/time point/floor") (C++17) | converts a time\_point to another, rounding down (function template) | | [ceil(std::chrono::time\_point)](time_point/ceil "cpp/chrono/time point/ceil") (C++17) | converts a time\_point to another, rounding up (function template) | | [round(std::chrono::time\_point)](time_point/round "cpp/chrono/time point/round") (C++17) | converts a time\_point to another, rounding to nearest, ties to even (function template) | ### Helper classes | | | | --- | --- | | [std::common\_type<std::chrono::time\_point>](time_point/common_type "cpp/chrono/time point/common type") (C++11) | specializes the `[std::common\_type](../types/common_type "cpp/types/common type")` trait (class template specialization) | ### Example ``` #include <algorithm> #include <iostream> #include <iomanip> #include <ctime> #include <chrono> void slow_motion() { static int a[] {1,2,3,4,5,6,7,8,9,10,11,12}; while (std::ranges::next_permutation(a).found) { } // generates 12! permutations } int main() { using namespace std::literals; // enables the usage of 24h, 1ms, 1s instead of // e.g. std::chrono::hours(24), accordingly const std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); const std::time_t t_c = std::chrono::system_clock::to_time_t(now - 24h); std::cout << "24 hours ago, the time was " << std::put_time(std::localtime(&t_c), "%F %T.\n") << std::flush; const std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now(); slow_motion(); const auto end = std::chrono::steady_clock::now(); std::cout << "Slow calculations took " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "µs ≈ " << (end - start) / 1ms << "ms ≈ " // almost equivalent form of the above, but << (end - start) / 1s << "s.\n"; // using milliseconds and seconds accordingly } ``` Possible output: ``` 24 hours ago, the time was 2021-02-15 18:28:52. Slow calculations took 2090448µs ≈ 2090ms ≈ 2s. ``` ### See also | | | | --- | --- | | [duration](duration "cpp/chrono/duration") (C++11) | a time interval (class template) | cpp std::chrono::operator/ (calendar) std::chrono::operator/ (calendar) ================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | `year_month` | | | | ``` constexpr auto operator/( const std::chrono::year& y, const std::chrono::month& m ) noexcept -> std::chrono::year_month; ``` | (1) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year& y, int m ) noexcept -> std::chrono::year_month; ``` | (2) | (since C++20) | | `month_day` | | | | ``` constexpr auto operator/( const std::chrono::month& m, const std::chrono::day& d ) noexcept -> std::chrono::month_day; ``` | (3) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month& m, int d ) noexcept -> std::chrono::month_day; ``` | (4) | (since C++20) | | ``` constexpr auto operator/( int m, const std::chrono::day& d ) noexcept -> std::chrono::month_day; ``` | (5) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::day& d, const std::chrono::month& m ) noexcept -> std::chrono::month_day; ``` | (6) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::day& d, int m ) noexcept -> std::chrono::month_day; ``` | (7) | (since C++20) | | `month_day_last` | | | | ``` constexpr auto operator/( const std::chrono::month& m, std::chrono::last_spec ) noexcept -> std::chrono::month_day_last; ``` | (8) | (since C++20) | | ``` constexpr auto operator/( int m, std::chrono::last_spec ) noexcept -> std::chrono::month_day_last; ``` | (9) | (since C++20) | | ``` constexpr auto operator/( std::chrono::last_spec, const std::chrono::month& m ) noexcept -> std::chrono::month_day_last; ``` | (10) | (since C++20) | | ``` constexpr auto operator/( std::chrono::last_spec, int m ) noexcept -> std::chrono::month_day_last; ``` | (11) | (since C++20) | | `month_weekday` | | | | ``` constexpr auto operator/( const std::chrono::month& m, const std::chrono::weekday_indexed& wdi ) noexcept -> std::chrono::month_weekday; ``` | (12) | (since C++20) | | ``` constexpr auto operator/( int m, const std::chrono::weekday_indexed& wdi ) noexcept -> std::chrono::month_weekday; ``` | (13) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::weekday_indexed& wdi, const std::chrono::month& m ) noexcept -> std::chrono::month_weekday; ``` | (14) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::weekday_indexed& wdi, int m ) noexcept -> std::chrono::month_weekday; ``` | (15) | (since C++20) | | `month_weekday_last` | | | | ``` constexpr auto operator/( const std::chrono::month& m, const std::chrono::weekday_last& wdl ) noexcept -> std::chrono::month_weekday_last; ``` | (16) | (since C++20) | | ``` constexpr auto operator/( int m, const std::chrono::weekday_last& wdl ) noexcept -> std::chrono::month_weekday_last; ``` | (17) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::weekday_last& wdl, const std::chrono::month& m ) noexcept -> std::chrono::month_weekday_last; ``` | (18) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::weekday_last& wdl, int m ) noexcept -> std::chrono::month_weekday_last; ``` | (19) | (since C++20) | | `year_month_day` | | | | ``` constexpr auto operator/( const std::chrono::year_month& ym, const std::chrono::day& d ) noexcept -> std::chrono::year_month_day; ``` | (20) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year_month& ym, int d ) noexcept -> std::chrono::year_month_day; ``` | (21) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year& y, const std::chrono::month_day& md ) noexcept -> std::chrono::year_month_day; ``` | (22) | (since C++20) | | ``` constexpr auto operator/( int y, const std::chrono::month_day& md ) noexcept -> std::chrono::year_month_day; ``` | (23) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_day& md, const std::chrono::year& y ) noexcept -> std::chrono::year_month_day; ``` | (24) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_day& md, int y ) noexcept -> std::chrono::year_month_day; ``` | (25) | (since C++20) | | `year_month_day_last` | | | | ``` constexpr auto operator/( const std::chrono::year_month& ym, std::chrono::last_spec ) noexcept -> std::chrono::year_month_day_last; ``` | (26) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year& y, const std::chrono::month_day_last& mdl ) noexcept -> std::chrono::year_month_day_last; ``` | (27) | (since C++20) | | ``` constexpr auto operator/( int y, const std::chrono::month_day_last& mdl ) noexcept -> std::chrono::year_month_day_last; ``` | (28) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_day_last& mdl, const std::chrono::year& y ) noexcept -> std::chrono::year_month_day_last; ``` | (29) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_day_last& mdl, int y ) noexcept -> std::chrono::year_month_day_last; ``` | (30) | (since C++20) | | `year_month_weekday` | | | | ``` constexpr auto operator/( const std::chrono::year_month& ym, const std::chrono::weekday_indexed& wdi ) noexcept -> std::chrono::year_month_weekday; ``` | (31) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year& y, const std::chrono::month_weekday& mwd ) noexcept -> std::chrono::year_month_weekday; ``` | (32) | (since C++20) | | ``` constexpr auto operator/( int y, const std::chrono::month_weekday& mwd ) noexcept -> std::chrono::year_month_weekday; ``` | (33) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_weekday& mwd, const std::chrono::year& y ) noexcept -> std::chrono::year_month_weekday; ``` | (34) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_weekday& mwd, int y ) noexcept -> std::chrono::year_month_weekday; ``` | (35) | (since C++20) | | `year_month_weekday_last` | | | | ``` constexpr auto operator/( const std::chrono::year_month& ym, const std::chrono::weekday_last& wdl ) noexcept -> std::chrono::year_month_weekday_last; ``` | (36) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::year& y, const std::chrono::month_weekday_last& mwdl ) noexcept -> std::chrono::year_month_weekday_last; ``` | (37) | (since C++20) | | ``` constexpr auto operator/( int y, const std::chrono::month_weekday_last& mwdl ) noexcept -> std::chrono::year_month_weekday_last; ``` | (38) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_weekday_last& mwdl, const std::chrono::year& y ) noexcept -> std::chrono::year_month_weekday_last; ``` | (39) | (since C++20) | | ``` constexpr auto operator/( const std::chrono::month_weekday_last& mwdl, int y ) noexcept -> std::chrono::year_month_weekday_last; ``` | (40) | (since C++20) | These `operator/` overloads provide a conventional syntax for the creation of [Gregorian calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar "enwiki:Proleptic Gregorian calendar") dates. For creation of a full date, any of the following three orders are accepted: * *`year/month/day`* * *`month/day/year`* * *`day/month/year`*. In each case *`day`* can replaced with one of: * `std::chrono::last`, for the last day of the month; * `*weekday*[*i*]`, for the *i*-th *weekday* of the month; * `*weekday*[std::chrono::last]`, for the last *weekday* of the month. A plain integer is accepted if its meaning is unambiguous from the types of other operands: `2005y/4/5` is allowed, but `5/April/2005` is not. Partial-date types ([`year_month`](year_month "cpp/chrono/year month"), [`month_day`](month_day "cpp/chrono/month day"), etc.) can be created by not applying the second `operator/` in any of the three orders. ### Return value 1) `[std::chrono::year\_month](http://en.cppreference.com/w/cpp/chrono/year_month)(y, m)` 2) `[std::chrono::year\_month](http://en.cppreference.com/w/cpp/chrono/year_month)(y, [std::chrono::month](http://en.cppreference.com/w/cpp/chrono/month)(m))` 3,6) `[std::chrono::month\_day](http://en.cppreference.com/w/cpp/chrono/month_day)(m, d)` 4) `[std::chrono::month\_day](http://en.cppreference.com/w/cpp/chrono/month_day)(m, [std::chrono::day](http://en.cppreference.com/w/cpp/chrono/day)(d))` 5,7) `[std::chrono::month\_day](http://en.cppreference.com/w/cpp/chrono/month_day)([std::chrono::month](http://en.cppreference.com/w/cpp/chrono/month)(m), d)` 8,10) `[std::chrono::month\_day\_last](http://en.cppreference.com/w/cpp/chrono/month_day_last)(m)` 9,11) `[std::chrono::month\_day\_last](http://en.cppreference.com/w/cpp/chrono/month_day_last)([std::chrono::month](http://en.cppreference.com/w/cpp/chrono/month)(m))` 12,14) `[std::chrono::month\_weekday](http://en.cppreference.com/w/cpp/chrono/month_weekday)(m, wdi)` 13,15) `[std::chrono::month\_weekday](http://en.cppreference.com/w/cpp/chrono/month_weekday)([std::chrono::month](http://en.cppreference.com/w/cpp/chrono/month)(m), wdi)` 16,18) `[std::chrono::month\_weekday\_last](http://en.cppreference.com/w/cpp/chrono/month_weekday_last)(m, wdl)` 17,19) `[std::chrono::month\_weekday\_last](http://en.cppreference.com/w/cpp/chrono/month_weekday_last)([std::chrono::month](http://en.cppreference.com/w/cpp/chrono/month)(m), wdl)` 20) `[std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)(ym.year(), ym.month(), d)` 21) `[std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)(ym.year(), ym.month(), [std::chrono::day](http://en.cppreference.com/w/cpp/chrono/day)(d))` 22,24) `[std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)(y, md.month(), md.day())` 23,25) `[std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)([std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(y), md.month(), md.day())` 26) `[std::chrono::year\_month\_day\_last](http://en.cppreference.com/w/cpp/chrono/year_month_day_last)(ym.year(), [std::chrono::month\_day\_last](http://en.cppreference.com/w/cpp/chrono/month_day_last)(ym.month()))` 27,29) `[std::chrono::year\_month\_day\_last](http://en.cppreference.com/w/cpp/chrono/year_month_day_last)(y, mdl)` 28,30) `[std::chrono::year\_month\_day\_last](http://en.cppreference.com/w/cpp/chrono/year_month_day_last)([std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(y), mdl)` 31) `[std::chrono::year\_month\_weekday](http://en.cppreference.com/w/cpp/chrono/year_month_weekday)(ym.year(), ym.month(), wdi)` 32,34) `[std::chrono::year\_month\_weekday](http://en.cppreference.com/w/cpp/chrono/year_month_weekday)(y, mwd.month(), mwd.weekday\_indexed())` 33,35) `[std::chrono::year\_month\_weekday](http://en.cppreference.com/w/cpp/chrono/year_month_weekday)([std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(y), mwd.month(), mwd.weekday\_indexed())` 36) `[std::chrono::year\_month\_weekday\_last](http://en.cppreference.com/w/cpp/chrono/year_month_weekday_last)(ym.year(), ym.month(), wdl)` 37,39) `[std::chrono::year\_month\_weekday\_last](http://en.cppreference.com/w/cpp/chrono/year_month_weekday_last)(y, mwdl.month(), mwdl.weekday\_last())` 38,40) `[std::chrono::year\_month\_weekday\_last](http://en.cppreference.com/w/cpp/chrono/year_month_weekday_last)([std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(y), mwdl.month(), mwdl.weekday\_last())` ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; // standard provides 2021y as option for std::chrono::year(2021) // standard provides 15d as option for std::chrono::day(15) constexpr auto ym {year(2021)/8}; std::cout << (ym == year_month(year(2021), August)) << ' '; constexpr auto md {9/day(15)}; std::cout << (md == month_day(September, day(15))) << ' '; constexpr auto mdl {October/last}; std::cout << (mdl == month_day_last(month(10))) << ' '; constexpr auto mw {11/Monday[3]}; std::cout << (mw == month_weekday(November, Monday[3])) << ' '; constexpr auto mwdl {December/Sunday[last]}; std::cout << (mwdl == month_weekday_last(month(12), weekday_last(Sunday))) << ' '; // Those three year/month/day orders that people actually use on this planet: constexpr auto ymd {year(2021)/January/day(23)}; static_assert(ymd == month{1}/23/2021); static_assert(ymd == day{23}/1/2021); std::cout << (ymd == year_month_day(2021y, month(January), 23d)) << '\n'; } ``` Output: ``` true true true true true true ```
programming_docs
cpp std::chrono::local_t std::chrono::local\_t ===================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct local_t {}; ``` | | (since C++20) | The class `local_t` is a pseudo-clock that is used as the first template argument to `[std::chrono::time\_point](time_point "cpp/chrono/time point")` to indicate that the time point represents local time with respect of a not-yet-specified time zone. `local_time` supports streaming and the full set of time point arithmetic. ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using local_time = std::chrono::time_point<std::chrono::local_t, Duration>; ``` | | (since C++20) | | ``` using local_seconds = local_time<std::chrono::seconds>; ``` | | (since C++20) | | ``` using local_days = local_time<std::chrono::days>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::local\_time)](local_t/operator_ltlt "cpp/chrono/local t/operator ltlt") (C++20) | performs stream output on a local\_time (function template) | | [from\_stream(std::chrono::local\_time)](local_t/from_stream "cpp/chrono/local t/from stream") (C++20) | parses a local\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::local\_time>](local_t/formatter "cpp/chrono/local t/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `local_time` according to the provided format (class template specialization) | cpp std::chrono::file_clock std::chrono::file\_clock ======================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` using file_clock = /* see below */; ``` | | (since C++20) | `std::chrono::file_clock` is an alias for the clock used for `[std::filesystem::file\_time\_type](../filesystem/file_time_type "cpp/filesystem/file time type")`. Its epoch is unspecified. `file_clock` meets the [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock") requirements. ### Time point family | | | | | --- | --- | --- | | Defined in namespace `std::chrono` | | | | ``` template<class Duration> using file_time = std::chrono::time_point<std::chrono::file_clock, Duration>; ``` | | (since C++20) | | | | | --- | --- | | [operator<<(std::chrono::file\_time)](file_clock/operator_ltlt "cpp/chrono/file clock/operator ltlt") (C++20) | performs stream output on a file\_time (function template) | | [from\_stream(std::chrono::file\_time)](file_clock/from_stream "cpp/chrono/file clock/from stream") (C++20) | parses a file\_time from a stream according to the provided format (function template) | | [std::formatter<std::chrono::file\_time>](file_clock/formatter "cpp/chrono/file clock/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `file_time` according to the provided format (class template specialization) | ### Member types | Member type | Definition | | --- | --- | | `rep` | signed 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>`, capable of representing negative durations | | `time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<std::chrono::file\_clock>` | ### Member constants | | | | --- | --- | | constexpr bool is\_steady [static] | `true` if the time between ticks is always constant, i.e. calls to [`now()`](file_clock/now "cpp/chrono/file clock/now") return values that increase monotonically even in case of some external clock adjustment, otherwise `false` (public static member constant) | ### Member functions `file_clock` provides exactly one of the following two pairs of static member functions: * `to_utc` and `from_utc`; or * `to_sys` and `from_sys`. | | | | --- | --- | | [now](file_clock/now "cpp/chrono/file clock/now") [static] | returns a `[std::chrono::time\_point](time_point "cpp/chrono/time point")` representing the current point in time (public static member function) | | [to\_utcfrom\_utc](file_clock/to_from_utc "cpp/chrono/file clock/to from utc") [static] (optional) | converts between `file_time` and `utc_time` (public static member function) | | [to\_sysfrom\_sys](file_clock/to_from_sys "cpp/chrono/file clock/to from sys") [static] (optional) | converts between `file_time` and `sys_time` (public static member function) | cpp std::chrono::nonexistent_local_time std::chrono::nonexistent\_local\_time ===================================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class nonexistent_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 nonexistent `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-nonexistent 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::nonexistent\_local\_time::nonexistent\_local\_time ---------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template< class Duration > nonexistent_local_time( const std::chrono::local_time<Duration>& tp, const std::chrono::local_info& i ); ``` | (1) | (since C++20) | | ``` nonexistent_local_time( const nonexistent_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 in a gap between\n" << std::chrono::local_seconds(i.first.end.time_since_epoch()) + i.first.offset << ' ' << i.first.abbrev << " and\n" << std::chrono::local_seconds(i.second.begin.time_since_epoch()) + i.second.offset << ' ' << i.second.abbrev << " which are both equivalent to\n" << i.first.end << " UTC"; ``` The behavior is undefined if `i.result != std::chrono::local_info::nonexistent`. 2) Copy constructor. If `*this` and `other` both have dynamic type `std::chrono::nonexistent_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 `nonexistent_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` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. std::chrono::nonexistent\_locale\_time::operator= -------------------------------------------------- | | | | | --- | --- | --- | | ``` nonexistent_locale_time& operator=( const nonexistent_locale_time& other ) noexcept; ``` | | (since C++20) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::chrono::nonexistent_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::nonexistent\_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`) | cpp std::chrono::leap_second std::chrono::leap\_second ========================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class leap_second; ``` | | (since C++20) | The class `leap_second` represents the date and time of a leap second insertion. Users cannot construct `leap_second` objects except by copying from existing `leap_second` objects. The library implementation creates `leap_second` objects when it initializes the time zone database and provides `const` access to these objects. `leap_second` has a defaulted copy constructor and a defaulted copy assignment operator. ### Member functions | | | | --- | --- | | [date](leap_second/date "cpp/chrono/leap second/date") | obtains the time of leap second insertion (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<operator<=operator>operator>=operator<=>](leap_second/operator_cmp "cpp/chrono/leap second/operator cmp") (C++20) | compares two `leap_second` values or a `leap_second` value and a `sys_time` (function template) | cpp std::chrono::month std::chrono::month ================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class month; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month January{1}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month February{2}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month March{3}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month April{4}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month May{5}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month June{6}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month July{7}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month August{8}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month September{9}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month October{10}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month November{11}; ``` | | (since C++20) | | ``` inline constexpr std::chrono::month December{12}; ``` | | (since C++20) | The class `month` represents a month in a year. Its normal range is [1, 12], but it may hold any number in [0, 255]. Twelve named constants are predefined in the `std::chrono` namespace for the twelve months of the year. `month` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](month/month "cpp/chrono/month/month") | constructs a `month` (public member function) | | [operator++operator++(int)operator--operator--(int)](month/operator_inc_dec "cpp/chrono/month/operator inc dec") | increments or decrements the month (public member function) | | [operator+=operator-=](month/operator_arith "cpp/chrono/month/operator arith") | adds or subtracts a number of months (public member function) | | [operator unsigned](month/operator_unsigned "cpp/chrono/month/operator unsigned") | retrieves the stored month value (public member function) | | [ok](month/ok "cpp/chrono/month/ok") | checks if the stored month value is in the normal range (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](month/operator_cmp "cpp/chrono/month/operator cmp") (C++20) | compares two `month` values (function) | | [operator+operator-](month/operator_arith_2 "cpp/chrono/month/operator arith 2") (C++20) | performs arithmetic on `month`s (function) | | [operator<<](month/operator_ltlt "cpp/chrono/month/operator ltlt") (C++20) | outputs a `month` into a stream (function template) | | [from\_stream](month/from_stream "cpp/chrono/month/from stream") (C++20) | parses a `month` from a stream according to the provided format (function template) | ### Helper classes | | | | --- | --- | | [std::formatter<std::chrono::month>](month/formatter "cpp/chrono/month/formatter") (C++20) | specialization of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month` according to the provided format (class template specialization) | cpp std::literals::chrono_literals::operator""ms std::literals::chrono\_literals::operator""ms ============================================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::milliseconds operator "" ms(unsigned long long ms); ``` | (1) | (since C++14) | | ``` constexpr std::chrono::duration</*unspecified*/, std::milli> operator "" ms(long double ms); ``` | (2) | (since C++14) | Forms a `[std::chrono::duration](duration "cpp/chrono/duration")` literal representing milliseconds. 1) integer literal, returns exactly `[std::chrono::milliseconds](http://en.cppreference.com/w/cpp/chrono/duration)(ms)` 2) floating-point literal, returns a floating-point duration equivalent to `[std::chrono::milliseconds](duration "cpp/chrono/duration")` ### Parameters | | | | | --- | --- | --- | | ms | - | the number of milliseconds | ### Return value The `[std::chrono::duration](duration "cpp/chrono/duration")` literal. ### Possible implementation | | | --- | | ``` constexpr std::chrono::milliseconds operator ""ms(unsigned long long ms) { return std::chrono::milliseconds(ms); } constexpr std::chrono::duration<long double, std::milli> operator ""ms(long double ms) { return std::chrono::duration<long double, std::milli>(ms); } ``` | ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; auto d1 = 250ms; std::chrono::milliseconds d2 = 1s; std::cout << "250ms = " << d1.count() << " milliseconds\n" << "1s = " << d2.count() << " milliseconds\n"; } ``` Output: ``` 250ms = 250 milliseconds 1s = 1000 milliseconds ``` ### See also | | | | --- | --- | | [(constructor)](duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | cpp std::chrono::last_spec, std::chrono::last std::chrono::last\_spec, std::chrono::last ========================================== | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct last_spec { explicit last_spec() = default; }; ``` | | (since C++20) | | ``` inline constexpr last_spec last{}; ``` | | (since C++20) | `last_spec` is an empty tag type that is used in conjunction with other calendar types to indicate the last thing in a sequence. Depending on context, it may indicate the last day of a month (as in `2018y/February/last`, for last day of February 2018, i.e., 2018-02-28) or the last day of the week in a month (as in `2018/February/Sunday[last]`, for last Sunday of February 2018, i.e., 2018-02-25). ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono; std::cout << std::boolalpha; constexpr auto mdl {June/last}; std::cout << (mdl == month_day_last(month(6))) << ' '; constexpr auto ymwdl {year(2023)/December/Tuesday[last]}; std::cout << (ymwdl == year_month_weekday_last( year(2023), month(12), weekday_last(Tuesday))) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::time_zone std::chrono::time\_zone ======================= | Defined in header `[<chrono>](../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` class time_zone; ``` | | (since C++20) | The class `time_zone` represents all time zone transitions for a specific geographic area. Users cannot construct `time_zone` objects. The library implementation creates `time_zone` objects when it initializes the time zone database and provides `const` access to these objects. `time_zone` is not copyable but does have a defaulted move constructor and a defaulted move assignment operator. However, as users have only `const` access to `time_zone` objects, these functions cannot be called in user code without invoking [undefined behavior](../language/ub "cpp/language/ub"). ### Member functions | | | | --- | --- | | [name](time_zone/name "cpp/chrono/time zone/name") | obtains the name of this `time_zone` (public member function) | | [get\_info](time_zone/get_info "cpp/chrono/time zone/get info") | obtain information associated with a `sys_time` or `local_time` (public member function) | | [to\_sys](time_zone/to_sys "cpp/chrono/time zone/to sys") | converts a `local_time` in this time zone to a `sys_time` (public member function) | | [to\_local](time_zone/to_local "cpp/chrono/time zone/to local") | converts a `sys_time` to a `local_time` in this time zone (public member function) | ### Nonmember functions | | | | --- | --- | | [operator==operator<=>](time_zone/operator_cmp "cpp/chrono/time zone/operator cmp") (C++20) | compares two `time_zone` objects (function) |
programming_docs
cpp std::chrono::operator<<(std::chrono::month) std::chrono::operator<<(std::chrono::month) =========================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::chrono::month& m); ``` | | (since C++20) | If `!m.ok()`, inserts `unsigned(m)` followed by `" is not a valid month"` to `os`. Otherwise, forms a `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` `s` consisting of the abbreviated month name for the month represented by `m`, determined using the locale associated with `os`, and inserts `s` into `os`. Equivalent to. `return os << (m.ok() ? [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L%b}"), m) : [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{} is not a valid month"), unsigned(m)));` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Notes This `operator<<` is primarily intended for debugging use. For control over formatting, use `[std::format](../../utility/format/format "cpp/utility/format/format")`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::month>](formatter "cpp/chrono/month/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month` according to the provided format (class template specialization) | cpp std::chrono::month::operator unsigned std::chrono::month::operator unsigned ===================================== | | | | | --- | --- | --- | | ``` explicit constexpr operator unsigned() const noexcept; ``` | | (since C++20) | Returns the month value stored in `*this`. ### Return value The month value stored in `*this`. ### Example ``` #include <iostream> #include <chrono> int main() { constexpr std::chrono::month m {6}; constexpr unsigned p = static_cast<unsigned>(m); constexpr unsigned q = static_cast<unsigned>(std::chrono::September); std::cout << "The month is: " << p << '\n' << "September is: " << q << '\n'; } ``` Output: ``` The month is: 6 September is: 9 ``` cpp std::chrono::month::operator++, std::chrono::month::operator-- std::chrono::month::operator++, std::chrono::month::operator-- ============================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::month& operator++() noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month operator++(int) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::month& operator--() noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::month operator--(int) noexcept; ``` | (4) | (since C++20) | Adds or subtracts 1 from the month value, reducing the result modulo 12 to an integer in the range [1, 12]. 1-2) Performs `\*this += [std::chrono::months](http://en.cppreference.com/w/cpp/chrono/duration){1};` 3-4) Performs `\*this -= [std::chrono::months](http://en.cppreference.com/w/cpp/chrono/duration){1};` ### Parameters (none). ### Return value 1,3) a reference to this `month` after modification 2,4) a copy of the `month` made before modification ### Notes After a call to one of these functions, `ok()` is always true. ### Example ``` #include <cassert> #include <iostream> #include <chrono> int main() { std::chrono::month m {6}; ++m; assert(m == std::chrono::month(7)); --m; assert(m == std::chrono::month(6)); m = std::chrono::December; m++; // rounds up to January assert(m.ok()); std::cout << unsigned(m) << '\n'; m = std::chrono::January; m--; // rounds down to December assert(m.ok()); std::cout << unsigned(m) << '\n'; } ``` Output: ``` 1 12 ``` ### See also | | | | --- | --- | | [operator+=operator-=](operator_arith "cpp/chrono/month/operator arith") | adds or subtracts a number of months (public member function) | | [operator+operator-](operator_arith_2 "cpp/chrono/month/operator arith 2") (C++20) | performs arithmetic on `month`s (function) | cpp std::chrono::operator==,<=>(std::chrono::month) std::chrono::operator==,<=>(std::chrono::month) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::month& x, const std::chrono::month& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::month& x, const std::chrono::month& y ) noexcept; ``` | (2) | (since C++20) | Compare the two `std::chrono::month` `x` and `y`. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `unsigned(x) == unsigned(y)` 2) `unsigned(x) <=> unsigned(y)` ### Example ``` #include <iostream> #include <chrono> int main() { constexpr std::chrono::month m1{6}; constexpr std::chrono::month m2{8}; std::cout << std::boolalpha << (m1 < m2) << ' ' << (m1 == m1) << ' ' << (m1 <= m2) << ' ' << (m2 > m1) << ' ' << (m2 != m1) << ' ' << (m2 >= m1) << '\n'; } ``` Output: ``` true true true true true true ``` cpp std::chrono::month::ok std::chrono::month::ok ====================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the month value stored in `*this` is in the valid range, i.e., [1, 12]. ### Return value `true` if the month value stored in `*this` is in the range [1, 12]. Otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { for (const unsigned mm : {6u, 0u, 16U}) { std::cout << mm << ": "; const std::chrono::month m{mm}; m.ok() ? std::cout << "month is valid\n" : std::cout << "month is invalid\n"; } } ``` Output: ``` 6: month is valid 0: month is invalid 16: month is invalid ``` cpp std::chrono::month::month std::chrono::month::month ========================= | | | | | --- | --- | --- | | ``` month() = default; ``` | (1) | (since C++20) | | ``` explicit constexpr month( unsigned m ) noexcept; ``` | (2) | (since C++20) | Constructs a `month` object. 1) Default constructor leaves the month value uninitialized. 2) If `m <= 255`, constructs a `month` object holding the month value `m`. Otherwise the value held is unspecified. cpp std::chrono::round(std::chrono::time_point) std::chrono::round(std::chrono::time\_point) ============================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Clock, class Duration> constexpr std::chrono::time_point<Clock, ToDuration> round(const std::chrono::time_point<Clock, Duration>& tp); ``` | | (since C++17) | Returns the nearest time point to `tp` representable in `ToDuration`, rounding to even in halfway cases. The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")` and `std::chrono::treat_as_floating_point_v<typename ToDuration::rep>` is `false`. ### Parameters | | | | | --- | --- | --- | | tp | - | time point to round to nearest | ### Return value `tp` rounded to nearest time point using duration of type `ToDuration`, rounding to even in halfway cases. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Clock, class FromDuration, class = std::enable_if_t<detail::is_duration_v<To> && !std::chrono::treat_as_floating_point_v<typename To::rep>>> constexpr std::chrono::time_point<Clock, To> round( const std::chrono::time_point<Clock, FromDuration>& tp) { return std::chrono::time_point<Clock, To>{ std::chrono::round<To>(tp.time_since_epoch())}; } ``` | ### Example ``` #include <iostream> #include <chrono> #include <string> template <typename TimePoint> std::string to_string(const TimePoint& time_point) { return std::to_string(time_point.time_since_epoch().count()); } int main() { using namespace std::literals::chrono_literals; using Sec = std::chrono::seconds; std::cout << "Time point\t" "Cast\t" "Floor\t" "Round\t" "Ceil\n"; std::cout << "(ms)\t\t" "(s)\t" "(s)\t" "(s)\t" "(s)\n"; for (const auto value_ms: {5432ms, 5678ms}) { std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> time_point_ms(value_ms); std::cout << to_string(time_point_ms) << "\t\t" << to_string(std::chrono::time_point_cast<Sec>(time_point_ms)) << "\t" << to_string(std::chrono::floor <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::round <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::ceil <Sec>(time_point_ms)) << "\n"; } } ``` Output: ``` Time point Cast Floor Round Ceil (ms) (s) (s) (s) (s) 5432 5 5 5 6 5678 5 5 6 6 ``` ### See also | | | | --- | --- | | [time\_point\_cast](time_point_cast "cpp/chrono/time point/time point cast") (C++11) | converts a time point to another time point on the same clock, with a different duration (function template) | | [ceil(std::chrono::time\_point)](ceil "cpp/chrono/time point/ceil") (C++17) | converts a time\_point to another, rounding up (function template) | | [floor(std::chrono::time\_point)](floor "cpp/chrono/time point/floor") (C++17) | converts a time\_point to another, rounding down (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) | | [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](../../numeric/math/round "cpp/numeric/math/round") (C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) | cpp std::chrono::ceil(std::chrono::time_point) std::chrono::ceil(std::chrono::time\_point) =========================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Clock, class Duration> constexpr std::chrono::time_point<Clock, ToDuration> ceil(const std::chrono::time_point<Clock, Duration>& tp); ``` | | (since C++17) | Returns the smallest time point `t` representable in `ToDuration` that is greater or equal to `tp`. The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. ### Parameters | | | | | --- | --- | --- | | tp | - | time point to round up | ### Return value `tp` rounded up to the next time point using duration of type `ToDuration`. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Clock, class FromDuration, class = std::enable_if_t<detail::is_duration_v<To>>> constexpr std::chrono::time_point<Clock, To> ceil(const std::chrono::time_point<Clock, FromDuration>& tp) { return std::chrono::time_point<Clock, To>{ std::chrono::ceil<To>(tp.time_since_epoch())}; } ``` | ### Example ``` #include <iostream> #include <chrono> #include <string> template <typename TimePoint> std::string to_string(const TimePoint& time_point) { return std::to_string(time_point.time_since_epoch().count()); } int main() { using namespace std::literals::chrono_literals; using Sec = std::chrono::seconds; std::cout << "Time point\t" "Cast\t" "Floor\t" "Round\t" "Ceil\n"; std::cout << "(ms)\t\t" "(s)\t" "(s)\t" "(s)\t" "(s)\n"; for (const auto value_ms: {5432ms, 5678ms}) { std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> time_point_ms(value_ms); std::cout << to_string(time_point_ms) << "\t\t" << to_string(std::chrono::time_point_cast<Sec>(time_point_ms)) << "\t" << to_string(std::chrono::floor <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::round <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::ceil <Sec>(time_point_ms)) << "\n"; } } ``` Output: ``` Time point Cast Floor Round Ceil (ms) (s) (s) (s) (s) 5432 5 5 5 6 5678 5 5 6 6 ``` ### See also | | | | --- | --- | | [time\_point\_cast](time_point_cast "cpp/chrono/time point/time point cast") (C++11) | converts a time point to another time point on the same clock, with a different duration (function template) | | [floor(std::chrono::time\_point)](floor "cpp/chrono/time point/floor") (C++17) | converts a time\_point to another, rounding down (function template) | | [round(std::chrono::time\_point)](round "cpp/chrono/time point/round") (C++17) | converts a time\_point to another, rounding to nearest, ties to even (function template) | | [ceil(std::chrono::duration)](../duration/ceil "cpp/chrono/duration/ceil") (C++17) | converts a duration to another, rounding up (function template) | | [ceilceilfceill](../../numeric/math/ceil "cpp/numeric/math/ceil") (C++11)(C++11) | nearest integer not less than the given value (function) | cpp std::chrono::time_point_cast std::chrono::time\_point\_cast ============================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Clock, class Duration> std::chrono::time_point<Clock, ToDuration> time_point_cast(const std::chrono::time_point<Clock, Duration> &t); ``` | | (since C++11) (until C++14) | | ``` template <class ToDuration, class Clock, class Duration> constexpr std::chrono::time_point<Clock, ToDuration> time_point_cast(const std::chrono::time_point<Clock, Duration> &t); ``` | | (since C++14) | Converts a `[std::chrono::time\_point](../time_point "cpp/chrono/time point")` from one duration to another. `time_point_cast` participates in overload resolution only if `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. ### Parameters | | | | | --- | --- | --- | | t | - | `time_point` to convert from | ### Return value `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<Clock, ToDuration>( [std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<ToDuration>(t.time\_since\_epoch()))`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono_literals; using Clock = std::chrono::high_resolution_clock; using Ms = std::chrono::milliseconds; using Sec = std::chrono::seconds; template<class Duration> using TimePoint = std::chrono::time_point<Clock, Duration>; inline void print_ms(const TimePoint<Ms>& time_point) { std::cout << time_point.time_since_epoch().count() << " ms\n"; } int main() { TimePoint<Sec> time_point_sec{4s}; // implicit cast, no precision loss TimePoint<Ms> time_point_ms{time_point_sec}; print_ms(time_point_ms); // 4000 ms time_point_ms = TimePoint<Ms>{5756ms}; print_ms(time_point_ms); // 5756 ms // explicit cast, need when precision loss may happen // 5756 truncated to 5000 time_point_sec = std::chrono::time_point_cast<Sec>(time_point_ms); print_ms(time_point_sec); // 5000 ms } ``` Output: ``` 4000 ms 5756 ms 5000 ms ``` ### See also | | | | --- | --- | | [floor(std::chrono::time\_point)](floor "cpp/chrono/time point/floor") (C++17) | converts a time\_point to another, rounding down (function template) | | [ceil(std::chrono::time\_point)](ceil "cpp/chrono/time point/ceil") (C++17) | converts a time\_point to another, rounding up (function template) | | [round(std::chrono::time\_point)](round "cpp/chrono/time point/round") (C++17) | converts a time\_point to another, rounding to nearest, ties to even (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) | cpp std::chrono::time_point<Clock,Duration>::max std::chrono::time\_point<Clock,Duration>::max ============================================= | | | | | --- | --- | --- | | ``` static constexpr time_point max(); ``` | | (until C++20) | | ``` static constexpr time_point max() noexcept; ``` | | (since C++20) | Returns a `time_point` with the largest possible duration, i.e. `time_point(std::chrono::duration::max())`. ### Parameters (none). ### Return value the largest possible `time_point`. ### Example ``` #include <chrono> #include <vector> #include <iostream> int main() { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::vector<std::chrono::time_point<std::chrono::system_clock>> times { now - std::chrono::hours(24), now - std::chrono::hours(48), now + std::chrono::hours(24), }; std::chrono::time_point<std::chrono::system_clock> earliest = std::chrono::time_point<std::chrono::system_clock>::max(); std::cout << "all times:\n"; for (const auto &time : times) { std::time_t t = std::chrono::system_clock::to_time_t(time); std::cout << std::ctime(&t); if (time < earliest) earliest = time; } std::time_t t = std::chrono::system_clock::to_time_t(earliest); std::cout << "earliest:\n" << std::ctime(&t); } ``` Possible output: ``` all times: Sun Oct 7 19:06:48 2012 Sat Oct 6 19:06:48 2012 Tue Oct 9 19:06:48 2012 earliest: Sat Oct 6 19:06:48 2012 ``` cpp std::chrono::time_point<Clock,Duration>::min std::chrono::time\_point<Clock,Duration>::min ============================================= | | | | | --- | --- | --- | | ``` static constexpr time_point min(); ``` | | (until C++20) | | ``` static constexpr time_point min() noexcept; ``` | | (since C++20) | Returns a `time_point` with the smallest possible duration, i.e. `time_point(std::chrono::duration::min())`. ### Parameters (none). ### Return value the smallest possible `time_point`. ### Example ``` #include <chrono> #include <iomanip> #include <iostream> #include <ratio> #include <string> constexpr auto steady_min = std::chrono::steady_clock::time_point::min(); void animate_frame_at_time_offset(double game_time) { std::cout << std::string(static_cast<int>(game_time) % 10 + 1, '*') << '\n'; } int main() { auto last_frame = steady_min; std::chrono::duration<double, std::micro> game_time {0.0}; for (int n = 0; n < 5; ++n) { const auto current_frame = std::chrono::steady_clock::now(); // initialize timer if first frame ever: if (last_frame == steady_min) last_frame = current_frame; game_time += current_frame - last_frame; std::cout << "Drawing frame at " << std::setprecision(10) << std::setw(8) << game_time.count() << " μs "; animate_frame_at_time_offset(game_time.count()); } } ``` Possible output: ``` Drawing frame at 0 μs * Drawing frame at 134.499 μs ***** Drawing frame at 274.337 μs ***** Drawing frame at 416.571 μs ******* Drawing frame at 561.124 μs ** ```
programming_docs
cpp std::chrono::time_point<Clock,Duration>::operator++, std::chrono::time_point<Clock,Duration>::operator-- std::chrono::time\_point<Clock,Duration>::operator++, std::chrono::time\_point<Clock,Duration>::operator-- ========================================================================================================== | | | | | --- | --- | --- | | ``` constexpr time_point& operator++(); ``` | (1) | (since C++20) | | ``` constexpr time_point operator++(int); ``` | (2) | (since C++20) | | ``` constexpr time_point& operator--(); ``` | (3) | (since C++20) | | ``` constexpr time_point operator--(int); ``` | (4) | (since C++20) | Modifies the point in time `*this` represents by one tick of the `duration`. If `d_` is a member variable holding the duration (i.e., time since epoch) of this `time_point` object, 1) Equivalent to `++d_; return *this;` 2) Equivalent to `return time_point(d_++)` 3) Equivalent to `--d_; return *this;` 4) Equivalent to `return time_point(d_--);` ### Parameters (none). ### Return value 1,3) a reference to this `time_point` after modification 2,4) a copy of the `time_point` made before modification ### Example ### See also | | | | --- | --- | | [operator++operator++(int)operator--operator--(int)](../duration/operator_arith2 "cpp/chrono/duration/operator arith2") | increments or decrements the tick count (public member function of `std::chrono::duration<Rep,Period>`) | | [operator+=operator-=](operator_arith "cpp/chrono/time point/operator arith") | modifies the time point by the given duration (public member function) | | [operator+operator-](operator_arith2 "cpp/chrono/time point/operator arith2") (C++11) | performs add and subtract operations involving a time point (function template) | cpp std::chrono::time_point<Clock,Duration>::time_since_epoch std::chrono::time\_point<Clock,Duration>::time\_since\_epoch ============================================================ | | | | | --- | --- | --- | | ``` duration time_since_epoch() const; ``` | | (since C++11) (until C++14) | | ``` constexpr duration time_since_epoch() const; ``` | | (since C++14) | Returns a `[duration](../duration "cpp/chrono/duration")` representing the amount of time between `*this` and the `clock`'s epoch. ### Parameters (none). ### Return value The amount of time between this `time_point` and the `clock`'s epoch. ### Example ``` #include <iostream> #include <chrono> #include <ctime> int main() { const auto p0 = std::chrono::time_point<std::chrono::system_clock>{}; const auto p1 = std::chrono::system_clock::now(); const auto p2 = p1 - std::chrono::hours(24); std::time_t epoch_time = std::chrono::system_clock::to_time_t(p0); std::cout << "epoch: " << std::ctime(&epoch_time); std::time_t today_time = std::chrono::system_clock::to_time_t(p1); std::cout << "today: " << std::ctime(&today_time); std::cout << "hours since epoch: " << std::chrono::duration_cast<std::chrono::hours>( p1.time_since_epoch()).count() << '\n'; std::cout << "yesterday, hours since epoch: " << std::chrono::duration_cast<std::chrono::hours>( p2.time_since_epoch()).count() << '\n'; } ``` Possible output: ``` epoch: Thu Jan 1 00:00:00 1970 today: Fri Jun 30 10:44:11 2017 hours since epoch: 416338 yesterday, hours since epoch: 416314 ``` cpp std::chrono::time_point<Clock,Duration>::operator+=, operator-= std::chrono::time\_point<Clock,Duration>::operator+=, operator-= ================================================================ | | | | | --- | --- | --- | | | (1) | | | ``` time_point& operator+=( const duration& d ); ``` | (until C++17) | | ``` constexpr time_point& operator+=( const duration& d ); ``` | (since C++17) | | | (2) | | | ``` time_point& operator-=( const duration& d ); ``` | (until C++17) | | ``` constexpr time_point& operator-=( const duration& d ); ``` | (since C++17) | Modifies the time point by the given duration. 1) Applies the offset `d` to `pt`. Effectively, `d` is added to the internally stored duration `d_` as `d_ += d`. 2) Applies the offset `d` to `pt` in negative direction. Effectively, `d` is subtracted from internally stored duration `d_` as `d_ -= d`. ### Parameters | | | | | --- | --- | --- | | d | - | a time offset to apply | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator+operator-](operator_arith2 "cpp/chrono/time point/operator arith2") (C++11) | performs add and subtract operations involving a time point (function template) | cpp std::chrono::floor(std::chrono::time_point) std::chrono::floor(std::chrono::time\_point) ============================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Clock, class Duration> constexpr std::chrono::time_point<Clock, ToDuration> floor(const std::chrono::time_point<Clock, Duration>& tp); ``` | | (since C++17) | Returns the largest time point `t` representable in `ToDuration` that is smaller or equal to `tp`. The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. ### Parameters | | | | | --- | --- | --- | | tp | - | time point to round down | ### Return value `tp` rounded down to the next time point using duration of type `ToDuration`. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Clock, class FromDuration, class = std::enable_if_t<detail::is_duration_v<To>>> constexpr std::chrono::time_point<Clock, To> floor(const std::chrono::time_point<Clock, FromDuration>& tp) { return std::chrono::time_point<Clock, To>{ std::chrono::floor<To>(tp.time_since_epoch())}; } ``` | ### Example ``` #include <iostream> #include <chrono> #include <string> template <typename TimePoint> std::string to_string(const TimePoint& time_point) { return std::to_string(time_point.time_since_epoch().count()); } int main() { using namespace std::literals::chrono_literals; using Sec = std::chrono::seconds; std::cout << "Time point\t" "Cast\t" "Floor\t" "Round\t" "Ceil\n"; std::cout << "(ms)\t\t" "(s)\t" "(s)\t" "(s)\t" "(s)\n"; for (const auto value_ms: {5432ms, 5678ms}) { std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> time_point_ms(value_ms); std::cout << to_string(time_point_ms) << "\t\t" << to_string(std::chrono::time_point_cast<Sec>(time_point_ms)) << "\t" << to_string(std::chrono::floor <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::round <Sec>(time_point_ms)) << "\t" << to_string(std::chrono::ceil <Sec>(time_point_ms)) << "\n"; } } ``` Output: ``` Time point Cast Floor Round Ceil (ms) (s) (s) (s) (s) 5432 5 5 5 6 5678 5 5 6 6 ``` ### See also | | | | --- | --- | | [time\_point\_cast](time_point_cast "cpp/chrono/time point/time point cast") (C++11) | converts a time point to another time point on the same clock, with a different duration (function template) | | [ceil(std::chrono::time\_point)](ceil "cpp/chrono/time point/ceil") (C++17) | converts a time\_point to another, rounding up (function template) | | [round(std::chrono::time\_point)](round "cpp/chrono/time point/round") (C++17) | converts a time\_point to another, rounding to nearest, ties to even (function template) | | [floor(std::chrono::duration)](../duration/floor "cpp/chrono/duration/floor") (C++17) | converts a duration to another, rounding down (function template) | | [floorfloorffloorl](../../numeric/math/floor "cpp/numeric/math/floor") (C++11)(C++11) | nearest integer not greater than the given value (function) | cpp std::chrono::time_point<Clock,Duration>::time_point std::chrono::time\_point<Clock,Duration>::time\_point ===================================================== | | | | | --- | --- | --- | | | (1) | | | ``` time_point(); ``` | (since C++11) (until C++14) | | ``` constexpr time_point(); ``` | (since C++14) | | | (2) | | | ``` explicit time_point( const duration& d ); ``` | (since C++11) (until C++14) | | ``` constexpr explicit time_point( const duration& d ); ``` | (since C++14) | | | (3) | | | ``` template< class Duration2 > time_point( const time_point<Clock,Duration2>& t ); ``` | (since C++11) (until C++14) | | ``` template< class Duration2 > constexpr time_point( const time_point<Clock,Duration2>& t ); ``` | (since C++14) | Constructs a new `time_point` from one of several optional data sources. 1) Default constructor, creates a `time_point` representing the `Clock`'s epoch (i.e., `[time\_since\_epoch()](time_since_epoch "cpp/chrono/time point/time since epoch")` is zero). 2) Constructs a `time_point` at `Clock`'s epoch plus `d`. 3) Constructs a `time_point` by converting `t` to `duration`. This constructor only participates in overload resolution if `Duration2` is implicitly convertible to `duration`. ### Parameters | | | | | --- | --- | --- | | d | - | a `duration` to copy from | | t | - | a `time_point` to convert from | ### Example ``` #include <chrono> #include <iostream> using Clock = std::chrono::high_resolution_clock; using TimePoint = std::chrono::time_point<Clock>; void print_ms(const TimePoint& point) { using Ms = std::chrono::milliseconds; const Clock::duration since_epoch = point.time_since_epoch(); std::cout << std::chrono::duration_cast<Ms>(since_epoch).count() << " ms\n"; } int main() { const TimePoint default_value = TimePoint(); // (1) print_ms(default_value); // 0 ms const Clock::duration duration_4_seconds = std::chrono::seconds(4); const TimePoint time_point_4_seconds(duration_4_seconds); // (2) // 4 seconds from start of epoch print_ms(time_point_4_seconds); // 4000 ms const TimePoint time_point_now = Clock::now(); // (3) print_ms(time_point_now); // 43098276 ms } ``` Possible output: ``` 0 ms 4000 ms 43098276 ms ``` ### See also | | | | --- | --- | | [(constructor)](../duration/duration "cpp/chrono/duration/duration") | constructs new duration (public member function of `std::chrono::duration<Rep,Period>`) | | [duration\_cast](../duration/duration_cast "cpp/chrono/duration/duration cast") (C++11) | converts a duration to another, with a different tick interval (function template) | cpp operator==,!=,<,<=,>,>=,<=>(std::chrono::time_point) operator==,!=,<,<=,>,>=,<=>(std::chrono::time\_point) ===================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | | (1) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator==( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator==( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) | | | (2) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator!=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator!=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) (until C++20) | | | (3) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator<( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator<( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) | | | (4) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator<=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator<=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) | | | (5) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator>( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator>( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) | | | (6) | | | ``` template< class Clock, class Dur1, class Dur2 > bool operator>=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++11) (until C++14) | | ``` template< class Clock, class Dur1, class Dur2 > constexpr bool operator>=( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (since C++14) | | ``` template<class Clock, class Dur1, std::three_way_comparable_with<Dur1> Dur2> constexpr auto operator<=>( const std::chrono::time_point<Clock,Dur1>& lhs, const std::chrono::time_point<Clock,Dur2>& rhs ); ``` | (7) | (since C++20) | Compares two time points. The comparison is done by comparing the results `[time\_since\_epoch()](time_since_epoch "cpp/chrono/time point/time since epoch")` for the time points. 1-2) Checks if the time points `lhs` and `rhs` refer to the same time point for the given clock. 3-6) Compares the time points `lhs` and `rhs`. 7) Compares the time points `lhs` and `rhs`. The return type is deduced from `lhs.time_since_epoch() <=> rhs.time_since_epoch()`, and hence the three-way comparison result type of `Dur1` and `Dur2`. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | time points to compare | ### Return value 1) `true` if the `lhs` and `rhs` refer to the same time point, `false` otherwise. 2) `true` if the `lhs` and `rhs` refer to different time points, `false` otherwise. 3) `true` if the `lhs` refers to time point *before* `rhs`, `false` otherwise. 4) `true` if the `lhs` refers to time point *before* `rhs`, or to the same time point as `rhs`, `false` otherwise. 5) `true` if the `lhs` refers to time point *after* `rhs`, `false` otherwise. 6) `true` if the `lhs` refers to time point *after* `rhs`, or to the same time point as `rhs`, `false` otherwise. 7) `lhs.time_since_epoch() <=> rhs.time_since_epoch()`. ### Exceptions May throw implementation-defined exceptions. ### Notes Two-way comparison operators of `time_point` were not `constexpr` in C++11, this was corrected in C++14. cpp std::common_type(std::chrono::time_point) std::common\_type(std::chrono::time\_point) =========================================== | | | | | --- | --- | --- | | ``` template <class Clock, class Duration1, class Duration2> struct common_type<std::chrono::time_point<Clock, Duration1>, std::chrono::time_point<Clock, Duration2>> { typedef std::chrono::time_point< Clock, typename std::common_type<Duration1, Duration2>::type> type; }; ``` | | (since C++11) | Exposes the type named `type`, which is the common type of two `[std::chrono::time\_point](../time_point "cpp/chrono/time point")`s. ### Notes The common type of two `[std::chrono::time\_point](../time_point "cpp/chrono/time point")` types is a `[std::chrono::time\_point](../time_point "cpp/chrono/time point")` with the same clock as the two types and the `[std::common\_type](../../types/common_type "cpp/types/common type")` of their durations. ### Example ### See also | | | | --- | --- | | [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) | | [common\_type](../../types/common_type "cpp/types/common type") (C++11) | determines the common type of a group of types (class template) | cpp Deduction guides for std::chrono::zoned_time Deduction guides for `std::chrono::zoned_time` ============================================== | | | | | --- | --- | --- | | ``` zoned_time() -> zoned_time<std::chrono::seconds>; ``` | (1) | (since C++20) | | ``` template< class Duration > zoned_time(std::chrono::sys_time<Duration>) -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>>; ``` | (2) | (since C++20) | | ``` template< class TimeZonePtrOrName > zoned_time(TimeZonePtrOrName&&) -> zoned_time<std::chrono::seconds, /* see below */>; ``` | (3) | (since C++20) | | ``` template< class TimeZonePtrOrName, class Duration > zoned_time(TimeZonePtrOrName&&, std::chrono::sys_time<Duration>) -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, /* see below */>; ``` | (4) | (since C++20) | | ``` template< class TimeZonePtrOrName, class Duration > zoned_time(TimeZonePtrOrName&&, std::chrono::local_time<Duration>, std::chrono::choose = std::chrono::choose::earliest) -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, /* see below */>; ``` | (5) | (since C++20) | | ``` template< class TimeZonePtrOrName, class Duration, class TimeZonePtr2 > zoned_time(TimeZonePtrOrName&&, std::chrono::zoned_time<Duration, TimeZonePtr2>, std::chrono::choose = std::chrono::choose::earliest) -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, /* see below */>; ``` | (6) | (since C++20) | Six deduction guides are provided for `zoned_time`. They normalize `Duration` to a minimum resolution of `[std::chrono::seconds](../duration "cpp/chrono/duration")`, and provide correct handling for time zone names specified using types convertible to `[std::string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)`. 3-6) If `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<TimeZonePtrOrName, [std::string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)>` is `true`, the deduced second template argument is `const [std::chrono::time\_zone](http://en.cppreference.com/w/cpp/chrono/time_zone)\*`. Otherwise it is `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<TimeZonePtrOrName>`. cpp std::chrono::zoned_time<Duration,TimeZonePtr>::operator sys_time<duration>, std::chrono::zoned_time<Duration,TimeZonePtr>::get_sys_time std::chrono::zoned\_time<Duration,TimeZonePtr>::operator sys\_time<duration>, std::chrono::zoned\_time<Duration,TimeZonePtr>::get\_sys\_time ============================================================================================================================================ | | | | | --- | --- | --- | | ``` operator std::chrono::sys_time<duration>() const; ``` | | (since C++20) | | ``` std::chrono::sys_time<duration> get_sys_time() const; ``` | | (since C++20) | Obtains a `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<duration>` representing the same point in time as this `zoned_time` object. ### Return value A `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<duration>` representing the same point in time as `*this`.
programming_docs
cpp std::chrono::zoned_time<Duration,TimeZonePtr>::zoned_time std::chrono::zoned\_time<Duration,TimeZonePtr>::zoned\_time =========================================================== | | | | | --- | --- | --- | | ``` zoned_time(); ``` | (1) | (since C++20) | | ``` zoned_time( const std::chrono::sys_time<Duration>& st ); ``` | (2) | (since C++20) | | ``` zoned_time( const zoned_time& other) = default; ``` | (3) | (since C++20) | | ``` template< class Duration2 > zoned_time( const std::chrono::zoned_time<Duration2, TimeZonePtr>& other ); ``` | (4) | (since C++20) | | ``` explicit zoned_time( TimeZonePtr z ); ``` | (5) | (since C++20) | | ``` explicit zoned_time( std::string_view name ); ``` | (6) | (since C++20) | | ``` zoned_time( TimeZonePtr z, const std::chrono::sys_time<Duration>& st ); ``` | (7) | (since C++20) | | ``` zoned_time( std::string_view name, const std::chrono::sys_time<Duration>& st ); ``` | (8) | (since C++20) | | ``` zoned_time( TimeZonePtr z, const std::chrono::local_time<Duration>& tp ); ``` | (9) | (since C++20) | | ``` zoned_time( std::string_view name, const std::chrono::local_time<Duration>& tp ); ``` | (10) | (since C++20) | | ``` zoned_time( TimeZonePtr z, const std::chrono::local_time<Duration>& tp, std::chrono::choose c ); ``` | (11) | (since C++20) | | ``` zoned_time( std::string_view name, const std::chrono::local_time<Duration>& tp, std::chrono::choose c ); ``` | (12) | (since C++20) | | ``` template< class Duration2, class TimeZonePtr2 > zoned_time( TimeZonePtr z, const std::chrono::zoned_time<Duration2, TimeZonePtr2>& zt ); ``` | (13) | (since C++20) | | ``` template< class Duration2, class TimeZonePtr2 > zoned_time( TimeZonePtr z, const std::chrono::zoned_time<Duration2, TimeZonePtr2>& zt, std::chrono::choose ); ``` | (14) | (since C++20) | | ``` template< class Duration2, class TimeZonePtr2 > zoned_time( std::string_view name, const std::chrono::zoned_time<Duration2, TimeZonePtr2>& zt ); ``` | (15) | (since C++20) | | ``` template< class Duration2, class TimeZonePtr2 > zoned_time( std::string_view name, const std::chrono::zoned_time<Duration2, TimeZonePtr2>& zt, std::chrono::choose ); ``` | (16) | (since C++20) | Constructs a `zoned_time` object, initializing the stored time zone pointer and time point according to the following table, where `traits` is `[std::chrono::zoned\_traits](http://en.cppreference.com/w/cpp/chrono/zoned_traits)<TimeZonePtr>`: | Overload | Time zone pointer (denoted `zone`) | Time point (a `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<duration>`) | Notes | | --- | --- | --- | --- | | (1) | `traits::default_zone()` | default constructed | (a) | | (2) | `st` | | (3) | `other.get_time_zone()` | `other.get_sys_time()` | (b) | | (4) | `other.get_time_zone()` | `other.get_sys_time()` | (e) | | (5) | `std::move(z)` | default constructed | | | (6) | `traits::locate_zone(name)` | (c) | | (7) | `std::move(z)` | `st` | | | (8) | `traits::locate_zone(name)` | (c) | | (9) | `std::move(z)` | `zone->to_sys(tp)` | (d) | | (10) | `traits::locate_zone(name)` | (c,d) | | (11) | `std::move(z)` | `zone->to_sys(tp, c)` | (d) | | (12) | `traits::locate_zone(name)` | (c,d) | | (13-14) | `std::move(z)` | `zt.get_sys_time()` | (e) | | (15-16) | `traits::locate_zone(name)` | (c,e) | a) Constructors specified to call `traits::default_zone()` (1-2) do not participate in overload resolution if that expression is not well-formed. b) The defaulted copy constructor (3) is defined as deleted if `[std::is\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<TimeZonePtr>` is false. c) Constructors with a `[std::string\_view](../../string/basic_string_view "cpp/string/basic string view")` parameter `name` (6,8,10,12,15-16) do not participate in overload resolution if `traits::locate_zone(name)` is not well-formed or if that expression is not convertible to `TimeZonePtr`. d) Constructors specified to call `zone->to_sys` (9-12) do not participate in overload resolution if that call expression is not well-formed or if the result is not convertible to `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<duration>`. e) Constructors with a template parameter `Duration2` (4,13-16) do not participate in overload resolution if `Duration2` is not convertible to `Duration`. The behavior is undefined if the time zone pointer (initialized as described above) does not refer to a time zone. ### Notes `zoned_time` does not have a move constructor and attempting to move one will perform a copy instead using the defaulted copy constructor (3). Thus, when `TimeZonePtr` is a move-only type, `zoned_time` is immovable: it can be neither moved nor copied. The constructors (14,16) accept a `std::chrono::choose` parameter, but that parameter has no effect. ### Example ``` #include <chrono> #include <iostream> #include <string_view> int main() { using std::chrono_literals::operator""y; using std::operator""sv; const auto now = std::chrono::floor<std::chrono::minutes>(std::chrono::system_clock::now()); { std::cout << std::chrono::zoned_time{} << " : default\n"; } { constexpr std::string_view location {"America/Phoenix"sv}; std::cout << std::chrono::zoned_time{ location } << " : " << location << '\n'; } { const std::chrono::time_zone* TimeZonePtr = std::chrono::locate_zone("UTC"); std::cout << std::chrono::zoned_time{ TimeZonePtr } << " : UTC time zone\n"; } { constexpr auto location{"Europe/Rome"sv}; std::cout << std::chrono::zoned_time{ location, std::chrono::local_days{2021y/12/31} } << " : " << location << '\n'; } { constexpr auto location {"Europe/Rome"sv}; constexpr auto some_date = std::chrono::sys_time<std::chrono::days>{2021y/12/31}; std::cout << std::chrono::zoned_time{ location, some_date } << " : " << location << '\n'; } { constexpr auto location {"Europe/Rome"sv}; std::cout << std::chrono::zoned_time{ location, now } << " : " << location << '\n'; } { constexpr auto NewYork {"America/New_York"sv}; constexpr auto Tokyo {"Asia/Tokyo"sv}; const std::chrono::zoned_time tz_Tokyo {Tokyo, now}; const std::chrono::zoned_time tz_NewYork {NewYork, now}; std::cout << std::chrono::zoned_time{ Tokyo, tz_NewYork } << " : " << Tokyo << '\n'; std::cout << std::chrono::zoned_time{ NewYork, tz_Tokyo } << " : " << NewYork << '\n'; } } ``` Possible output: ``` 1970-01-01 00:00:00 UTC : default 1969-12-31 17:00:00 MST : America/Phoenix 1970-01-01 00:00:00 UTC : UTC time zone 2021-12-31 00:00:00 CET : Europe/Rome 2021-12-31 01:00:00 CET : Europe/Rome 2021-09-20 23:04:00 CEST : Europe/Rome 2021-09-21 06:04:00 JST : Asia/Tokyo 2021-09-20 17:04:00 EDT : America/New_York ``` cpp std::chrono::operator<<(std::chrono::zoned_time) std::chrono::operator<<(std::chrono::zoned\_time) ================================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits, class Duration, class TimeZonePtr> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::zoned_time<Duration, TimeZonePtr>& tp ); ``` | | (since C++20) | Outputs `tp` to the stream `os`, as if by `[std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), fmt, tp)`, where `fmt` is `"{:L%F %T %Z}"` if `CharT` is `char`, or `L"{:L%F %T %Z}"` if `CharT` is `wchar_t`. ### Parameters | | | | | --- | --- | --- | | os | - | output stream | | tp | - | `zoned_time` to output | ### Return value `os`. ### 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 | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::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) | cpp std::chrono::zoned_time<Duration,TimeZonePtr>::operator= std::chrono::zoned\_time<Duration,TimeZonePtr>::operator= ========================================================= | | | | | --- | --- | --- | | ``` zoned_time& operator=(const zoned_time& other) = default; ``` | (1) | (since C++20) | | ``` zoned_time& operator=(const std::chrono::sys_time<Duration>& other); ``` | (2) | (since C++20) | | ``` zoned_time& operator=(const std::chrono::local_time<Duration>& other); ``` | (3) | (since C++20) | Assign the value of `other` to `*this`. 1) Defaulted copy assignment operator. Copy-assigns both the stored time point and the stored time zone pointer. `zoned_time` has no move assignment operator; a move is a copy. 2) Assigns `other` to the stored time point. The time zone pointer is unchanged. After this call, `get_sys_time() == other`. 3) Converts `other` to a `std::chrono::sys_time` as if by `zone->to_sys(other)` (where `zone` is the non-static data member holding the stored time zone pointer) and assigns the result to the stored time point. The time zone pointer is unchanged. After this call, `get_local_time() == other`. ### Return value `*this`. cpp std::chrono::zoned_time<Duration,TimeZonePtr>::get_info std::chrono::zoned\_time<Duration,TimeZonePtr>::get\_info ========================================================= | | | | | --- | --- | --- | | ``` std::chrono::sys_info get_info() const; ``` | | (since C++20) | Obtains the `std::chrono::sys_info` containing information about the time zone at the time point stored in `*this`. ### Return value `zone->get_info(tp)`, where `zone` is the non-static data member holding the time zone pointer, and `tp` is the non-static data member holding the stored time point (as a `[std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<duration>`). cpp std::chrono::zoned_time<Duration,TimeZonePtr>::get_time_zone std::chrono::zoned\_time<Duration,TimeZonePtr>::get\_time\_zone =============================================================== | | | | | --- | --- | --- | | ``` TimeZonePtr get_time_zone() const; ``` | | (since C++20) | Retrieves the stored time zone pointer. ### Return value A copy of the stored time zone pointer. ### Notes There's no way to access the time zone pointer when `TimeZonePtr` is a move-only type. cpp std::chrono::operator==(std::chrono::zoned_time) std::chrono::operator==(std::chrono::zoned\_time) ================================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class Duration1, class Duration2, class TimeZonePtr> bool operator==(const std::chrono::zoned_time<Duration1, TimeZonePtr>& x, const std::chrono::zoned_time<Duration2, TimeZonePtr>& y); ``` | | (since C++20) | Compares the two `zoned_time` values `x` and `y`. Two `zoned_time` objects compare equal if their time points and time zone pointers both compare equal according to `operator==`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.get_time_zone() == y.get_time_zone() && x.get_sys_time() == y.get_sys_time()`, except that the comparisons are performed on the nonstatic data members of `x` and `y` directly and no copying is performed. cpp std::chrono::operator<<(std::chrono::year_month) std::chrono::operator<<(std::chrono::year\_month) ================================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year_month& ym ); ``` | | (since C++20) | Outputs a textual representation of `ym` into the stream `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{}/{:L}"), ym.year(), ym.month())`. where `STATICALLY_WIDEN<CharT>("{}/{:L}")` is `"{}/{:L}"` if `CharT` is `char`, and `L"{}/{:L}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year\_month>](formatter "cpp/chrono/year month/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month` according to the provided format (class template specialization) | cpp std::chrono::year_month::year, std::chrono::year_month::month std::chrono::year\_month::year, std::chrono::year\_month::month =============================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::year year() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month month() const noexcept; ``` | (2) | (since C++20) | Retrieves the year and month values stored in this `year_month` object. ### Return values 1) Returns the stored `std::chrono::year` value. 2) Returns the stored `std::chrono::month` value. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto ym {std::chrono::year(2021)/std::chrono::July}; std::cout << (ym.year() == std::chrono::year(2021)) << ' '; std::cout << (ym.month() == std::chrono::month(7)) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::year_month::operator+=, std::chrono::year_month::operator-= std::chrono::year\_month::operator+=, std::chrono::year\_month::operator-= ========================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month& operator+=( const std::chrono::years& dy ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year_month& operator+=( const std::chrono::months& dm ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year_month& operator-=( const std::chrono::years& dy ) const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year_month& operator-=( const std::chrono::months& dm ) const noexcept; ``` | (4) | (since C++20) | Modifies the time point `*this` represents by the duration `dy` or `dm`. 1) Equivalent to `*this = *this + dy;` 2) Equivalent to `*this = *this + dm;` 3) Equivalent to `*this = *this - dy;` 4) Equivalent to `*this = *this - dm;` For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (1,3) are preferred if the call would otherwise be ambiguous. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ym {std::chrono::day(1)/7/2023}; ym -= std::chrono::years {2}; std::cout << (ym.month() == std::chrono::July) << ' ' << (ym.year() == std::chrono::year(2021)) << ' '; ym += std::chrono::months {7}; std::cout << (ym.month() == std::chrono::month(2)) << ' ' << (ym.year() == std::chrono::year(2022)) << '\n'; } ``` Output: ``` true true true true ``` ### See also | | | | --- | --- | | [operator+operator-](operator_arith_2 "cpp/chrono/year month/operator arith 2") (C++20) | performs arithmetic on `year_month` (function) | cpp std::chrono::year_month::year_month std::chrono::year\_month::year\_month ===================================== | | | | | --- | --- | --- | | ``` year_month() = default; ``` | (1) | (since C++20) | | ``` constexpr year_month(const std::chrono::year& y, const std::chrono::month& m) noexcept; ``` | (2) | (since C++20) | Constructs a `year_month` object. 1) Default constructor leaves the year and month uninitialized. 2) Constructs a `year_month` object storing the year `y` and the month `m`. ### Notes A more convenient way to construct a `year_month` is with `operator/`, e.g., `2007y/[std::chrono::April](http://en.cppreference.com/w/cpp/chrono/month)`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::operator==,<=>(std::chrono::year_month) std::chrono::operator==,<=>(std::chrono::year\_month) ===================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::year_month& x, const std::chrono::year_month& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::year_month& x, const std::chrono::year_month& y ) noexcept; ``` | (2) | (since C++20) | Compares the two `year_month` values `x` and `y`. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `x.year() == y.year() && x.month() == y.month()` 2) `x.year() <=> y.year() != 0 ? x.year() <=> y.year() : x.month() <=> y.month()` ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono; constexpr year_month ym1 {year(2021), month(7)}; constexpr year_month ym2 {year(2021)/7}; std::cout << std::boolalpha << (ym1 == ym2) << '\n'; static_assert( (2020y/1 < 2020y/2) && (2020y/2 == 2020y/2) && (2020y/3 <= 2021y/3) && (2023y/1 > 2020y/2) && (3020y/2 != 2020y/2) && (2020y/3 >= 2020y/3) ); } ``` Output: ``` true ``` cpp std::chrono::year_month::ok std::chrono::year\_month::ok ============================ | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the year and month values stored in this object are valid. ### Return value `year().ok() && month().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr std::chrono::year_month ym1 {std::chrono::year(2020), std::chrono::July}; std::cout << (ym1.ok()) << ' '; constexpr std::chrono::year_month ym2 {std::chrono::year(2020)/16}; std::cout << (ym2.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::time_zone::to_sys std::chrono::time\_zone::to\_sys ================================ | | | | | --- | --- | --- | | ``` template< class Duration > auto to_sys( const std::chrono::local_time<Duration>& tp ) const -> std::chrono::sys_time<std::common_type_t<Duration, std::chrono::seconds>>; ``` | | (since C++20) | | ``` template< class Duration > auto to_sys( const std::chrono::local_time<Duration>& tp, std::chrono::choose z ) const -> std::chrono::sys_time<std::common_type_t<Duration, std::chrono::seconds>>; ``` | | (since C++20) | Converts the `local_time` `tp` in this time zone to the corresponding `sys_time`. 1) Throws an exception if the conversion is ambiguous or if `tp` represents a nonexistent time. 2) Resolves ambiguity according to the value of `z`: * If `z == std::chrono::choose::earliest`, returns the earlier `sys_time`. * If `z == std::chrono::choose::latest`, returns the later `sys_time` If `tp` represents a nonexistent time between two UTC `time_point`s, those two `time_point`s will be the same, and that `time_point` will be returned. ### Return value The UTC equivalent of `tp` according to the rules of this time zone. ### Exceptions 1) Throws: * `[std::chrono::ambiguous\_local\_time](http://en.cppreference.com/w/cpp/chrono/ambiguous_local_time)` if the conversion is ambiguous, * `[std::chrono::nonexistent\_local\_time](http://en.cppreference.com/w/cpp/chrono/nonexistent_local_time)` if `tp` represents a nonexistent time. ### Notes The precision of the result is at least `[std::chrono::seconds](../duration "cpp/chrono/duration")`, and will be finer if the argument has finer precision. Ambiguous and nonexistent local times can occur as a result of time zone transitions (such as daylight saving time). For example, `"2016-03-13 02:30:00"` does not exist in the `"America/New_York"` time zone, while `"2016-11-06 01:30:00"` in that time zone can correspond to two UTC time points: `2016-11-06 05:30:00 UTC` and `2016-11-06 06:30:00 UTC`.
programming_docs
cpp std::chrono::time_zone::to_local std::chrono::time\_zone::to\_local ================================== | | | | | --- | --- | --- | | ``` template< class Duration > auto to_local( const std::chrono::sys_time<Duration>& tp ) const -> std::chrono::local_time<std::common_type_t<Duration, std::chrono::seconds>>; ``` | | (since C++20) | Converts the `sys_time` `tp` to the corresponding `local_time` in this time zone. ### Return value The `local_time` associated with `tp` and this time zone. ### Notes The precision of the result is at least `[std::chrono::seconds](../duration "cpp/chrono/duration")`, and will be finer if the argument has finer precision. cpp std::chrono::time_zone::name std::chrono::time\_zone::name ============================= | | | | | --- | --- | --- | | ``` std::string_view name() const noexcept; ``` | | (since C++20) | Obtains the name of this time zone. ### Return value The name of this time zone (e.g., `"America/New_York"`). cpp std::chrono::time_zone::get_info std::chrono::time\_zone::get\_info ================================== | | | | | --- | --- | --- | | ``` template< class Duration > std::chrono::sys_info get_info( const std::chrono::sys_time<Duration>& tp ) const; ``` | | (since C++20) | | ``` template< class Duration > std::chrono::local_info get_info( const std::chrono::local_time<Duration>& tp ) const; ``` | | (since C++20) | Obtains information about this time zone at the time point `tp`. ### Return value 1) A `std::chrono::sys_info` structure `i` containing the time zone information in effect for this time zone at the time point `tp`. `tp` will be in the range `[i.begin, i.end)`. 2) A `std::chrono::local_info` structure containing information about the local time `tp` in this time zone. cpp std::chrono::operator==,<=>(std::chrono::time_zone) std::chrono::operator==,<=>(std::chrono::time\_zone) ==================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` bool operator==( const std::chrono::time_zone& x, const std::chrono::time_zone& y ) noexcept; ``` | (1) | (since C++20) | | ``` std::strong_ordering operator<=>( const std::chrono::time_zone& x, const std::chrono::time_zone& y ) noexcept; ``` | (2) | (since C++20) | Compares the two `time_zone` values `x` and `y` by name. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `x.name() == y.name()`. 2) `x.name() <=> y.name()`. cpp std::chrono::operator<<(std::chrono::year_month_day) std::chrono::operator<<(std::chrono::year\_month\_day) ====================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year_month_day& ymd ); ``` | | (since C++20) | Outputs a textual representation of `ymd` into the stream `os`. This first forms a `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT> s` consisting of a textual representation of the date in the format `yyyy-mm-dd` (same as the one output by [`formatter`](formatter "cpp/chrono/year month day/formatter") with the %F specifier). Then, if `!ymd.ok()`, appends `" is not a valid date"` to `s`. Inserts `s` into `os`. Equivalent to. `return os << (ymd.ok() ? [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:%F}"), ymd) : [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:%F} is not a valid date"), ymd));` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year\_month\_day>](formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day` according to the provided format (class template specialization) | cpp std::chrono::year_month_day::year_month_day std::chrono::year\_month\_day::year\_month\_day =============================================== | | | | | --- | --- | --- | | ``` year_month_day() = default; ``` | (1) | (since C++20) | | ``` constexpr year_month_day( const std::chrono::year& y, const std::chrono::month& m, const std::chrono::day& d ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr year_month_day( const std::chrono::year_month_day_last& ymdl ) noexcept; ``` | (3) | (since C++20) | | ``` constexpr year_month_day( const std::chrono::sys_days& dp ) noexcept; ``` | (4) | (since C++20) | | ``` explicit constexpr year_month_day( const std::chrono::local_days& dp ) noexcept; ``` | (5) | (since C++20) | Constructs a `year_month_day` object. 1) Default constructor leaves the date uninitialized. 2) Constructs a `year_month_day` object that stores the year `y`, month `m` and day `d`. 3) Constructs a `year_month_day` object that stores the year `ymdl.year()`, month `ymdl.month()` and day `ymdl.day()`. 4) Constructs a `year_month_day` object that represent the same date as the one represented by `dp`. 5) Constructs a `year_month_day` object that represent the same date as the one represented by `dp`, as if by `year_month_day(sys_days(dp.time_since_epoch()))`. Constructors (3-4) define implicit conversions from `std::chrono::year_month_day_last` and `std::chrono::sys_days`, respectively. For any `year_month_day` object `ymd` representing a valid date (`ymd.ok() == true`), converting `ymd` to `sys_days` and back yields the same value. ### Notes A `year_month_day` can also be created by combining one of the partial-date types `std::chrono::year_month` and `std::chrono::month_day` with the missing component (day and year, respectively) using `operator/`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::year_month_day::year, std::chrono::year_month_day::month, std::chrono::year_month_day::day std::chrono::year\_month\_day::year, std::chrono::year\_month\_day::month, std::chrono::year\_month\_day::day ============================================================================================================= | | | | | --- | --- | --- | | ``` constexpr std::chrono::year year() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month month() const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::day day() const noexcept; ``` | (3) | (since C++20) | Retrieves the year, month and day values stored in this `year_month_day` object. ### Return values 1) Returns the stored `std::chrono::year` value. 2) Returns the stored `std::chrono::month` value. 3) Returns the stored `std::chrono::day` value. ### Example ``` #include <chrono> int main() { constexpr std::chrono::year_month_day ymd {std::chrono::July/1/2021}; static_assert(ymd.year() == std::chrono::year(2021)); static_assert(ymd.month() == std::chrono::month(7)); static_assert(ymd.day() == std::chrono::day(1)); } ``` cpp std::chrono::operator+, std::chrono::operator- (std::chrono::year_month_day) std::chrono::operator+, std::chrono::operator- (std::chrono::year\_month\_day) ============================================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month_day operator+( const std::chrono::year_month_day& ymd, const std::chrono::months& dm ) noexcept; ``` | | (since C++20) | | ``` constexpr std::chrono::year_month_day operator+( const std::chrono::months& dm, const std::chrono::year_month_day& ymd ) noexcept; ``` | | (since C++20) | | ``` constexpr std::chrono::year_month_day operator+( const std::chrono::year_month_day& ymd, const std::chrono::years& dy ) noexcept; ``` | | (since C++20) | | ``` constexpr std::chrono::year_month_day operator+( const std::chrono::years& dy, const std::chrono::year_month_day& ymd ) noexcept; ``` | | (since C++20) | | ``` constexpr std::chrono::year_month_day operator-( const std::chrono::year_month_day& ymd, const std::chrono::months& dm ) noexcept; ``` | | (since C++20) | | ``` constexpr std::chrono::year_month_day operator-( const std::chrono::year_month_day& ymd, const std::chrono::years& dy ) noexcept; ``` | | (since C++20) | 1-2) Adds `dm.count()` months to the date represented by `ymd`. The result has the same `day()` as `ymd` and the same `year()` and `month()` as `[std::chrono::year\_month](http://en.cppreference.com/w/cpp/chrono/year_month)(ymd.year(), ymd.month()) + dm`. 3-4) Adds `dy.count()` years to the date represented by `ymd`. The result is equivalent to `[std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)(ymd.year() + dy, ymd.month(), ymd.day()`. 5) Subtracts `dm.count()` months from the date represented by `ymd`. Equivalent to `ymd + -dm`. 6) Subtracts `dy.count()` years from the date represented by `ymd`. Equivalent to `ymd + -dy`. For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (3,4,6) are preferred if the call would otherwise be ambiguous. ### Notes Even if `ymd.ok()` is true, the resulting `year_month_day` may not represent a valid date if `ymd.day()` is 29, 30, or 31. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ymd {std::chrono::day(1)/std::chrono::July/2021}; ymd = ymd + std::chrono::months(4); std::cout << (ymd.month() == std::chrono::November) << ' ' << (ymd.year() == std::chrono::year(2021)) << ' '; ymd = ymd - std::chrono::years(10); std::cout << (ymd.month() == std::chrono::month(11)) << ' ' << (ymd.year() == std::chrono::year(2011)) << ' '; } ``` Output: ``` true true true true ``` cpp std::chrono::year_month_day::operator+=, std::chrono::year_month_day::operator-= std::chrono::year\_month\_day::operator+=, std::chrono::year\_month\_day::operator-= ==================================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month_day& operator+=( const std::chrono::years& dy ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year_month_day& operator+=( const std::chrono::months& dm ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year_month_day& operator-=( const std::chrono::years& dy ) const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year_month_day& operator-=( const std::chrono::months& dm ) const noexcept; ``` | (4) | (since C++20) | Modifies the time point `*this` represents by the duration `dy` or `dm`. 1) Equivalent to `*this = *this + dy;` 2) Equivalent to `*this = *this + dm;` 3) Equivalent to `*this = *this - dy;` 4) Equivalent to `*this = *this - dm;` For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (1,3) are preferred if the call would otherwise be ambiguous. ### Example ``` #include <iostream> #include <cassert> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto monthsInYear {12}; auto ymd {std::chrono::day(1)/std::chrono::July/2020}; ymd -= std::chrono::years(10); std::cout << (ymd.month() == std::chrono::July) << ' ' // true << (ymd.year() == std::chrono::year(2010)) << ' '; // true ymd += std::chrono::months(10 * monthsInYear + 11); std::cout << (ymd.month() == std::chrono::month(6)) << ' ' // true << (ymd.year() == std::chrono::year(2021)) << ' '; // true // Handling the ymd += months "overflow" case. ymd = std::chrono::May/31/2021; // ok std::cout << ymd.ok() << ' '; // true ymd += std::chrono::months{1}; // bad date: June has only 30 days std::cout << ymd.ok() << ' '; // false assert(ymd == std::chrono::June/31/2021); // Snap to the last day of the month, June 30: const auto ymd1 = ymd.year()/ymd.month()/std::chrono::last; std::cout << ymd1.ok() << ' '; // true assert(ymd1 == std::chrono::June/30/2021); // Overflow into the next month, July 1 (via converting to/from sys_days): const std::chrono::year_month_day ymd2 = std::chrono::sys_days{ymd}; std::cout << ymd2.ok() << ' '; // true assert(ymd2 == std::chrono::July/1/2021); } ``` Output: ``` true true true true true false true true ``` ### See also | | | | --- | --- | | [operator+operator-](operator_arith_2 "cpp/chrono/year month day/operator arith 2") (C++20) | adds or subtracts a `year_month_day` and some number of years or months (function) | cpp std::chrono::operator==,<=>(std::chrono::year_month_day) std::chrono::operator==,<=>(std::chrono::year\_month\_day) ========================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::year_month_day& x, const std::chrono::year_month_day& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::year_month_day& x, const std::chrono::year_month_day& y ) noexcept; ``` | (2) | (since C++20) | Compares the two `year_month_day` values `x` and `y`. This is a lexicographical comparison: the `year()` is compared first, then `month()`, then `day()`. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `x.year() == y.year() && x.month() == y.month() && x.day() == y.day()` 2) If `x.year() <=> y.year != 0`, `x.year() <=> y.year`; otherwise if `x.month() <=> y.month() != 0`, `x.month() <=> y.month()`; otherwise `x.day() <=> y.day()` ### Notes If both `x` and `y` represent valid dates (`x.ok() && y.ok() == true`), the result of the lexicographical comparison is consistent with the calendar order. ### Example ``` #include <iostream> #include <chrono> int main() { constexpr auto ymd1 {std::chrono::day(1)/7/2021}; constexpr auto ymd2 {std::chrono::year(2021)/7/1}; std::cout << std::boolalpha << (ymd1 == ymd2) << '\n'; static_assert(ymd1 <= ymd2); } ``` Output: ``` true ``` cpp std::chrono::year_month_day::ok std::chrono::year\_month\_day::ok ================================= | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if this `year_month_day` object represents a valid calendar date. ### Return value `true` if this `year_month_day` object represents a valid calendar date, that is, the stored year, month, and day values are all valid and the stored day value is within the number of days in the given year and month. Otherwise `false`. ### Possible implementation | | | --- | | ``` constexpr bool std::chrono::year_month_day::ok() const noexcept { return year().ok() && month().ok() && day().ok() && day() <= (year()/month()/std::chrono::last).day(); } ``` | ### Example ``` #include <chrono> int main() { constexpr auto ymd1 {std::chrono::day(1)/std::chrono::July/2020}; static_assert(ymd1.ok()); constexpr auto ymd2 {std::chrono::year(2020)/7/42}; static_assert(not ymd2.ok()); constexpr auto ymd3 {std::chrono::February/29/2020}; // ok, leap year static_assert(ymd3.ok()); constexpr auto ymd4 = ymd3 + std::chrono::years{1}; // bad, not a leap year static_assert(ymd4 == std::chrono::February/29/2021 and not ymd4.ok()); // to fix the bad date we may want to snap to the last day of the month: if constexpr (!ymd4.ok()) { constexpr auto ymd = ymd4.year()/ymd4.month()/std::chrono::last; static_assert(ymd == std::chrono::February/28/2021 and ymd.ok()); } // or we may want to overflow to the next month: if constexpr (!ymd4.ok()) { constexpr auto st = std::chrono::sys_time<std::chrono::days>{ymd4}; constexpr auto ymd = std::chrono::year_month_day{st}; static_assert(ymd == std::chrono::March/1/2021 and ymd.ok()); } } ``` cpp std::chrono::operator<<(std::chrono::year_month_weekday) std::chrono::operator<<(std::chrono::year\_month\_weekday) ========================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year_month_weekday& ymwd ); ``` | | (since C++20) | Outputs a textual representation of `ymwd` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{}/{:L}/{:L}"), ymwd.year(), ymwd.month(), ymwd.weekday\_indexed());` where `STATICALLY_WIDEN<CharT>("{}/{:L}/{:L}")` is `"{}/{:L}/{:L}"` if `CharT` is `char`, and `L"{}/{:L}/{:L}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year\_month\_day>](../year_month_day/formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day` according to the provided format (class template specialization) | cpp std::chrono::year_month_weekday::year_month_weekday std::chrono::year\_month\_weekday::year\_month\_weekday ======================================================= | | | | | --- | --- | --- | | ``` year_month_weekday() = default; ``` | (1) | (since C++20) | | ``` constexpr year_month_weekday(const std::chrono::year& y, const std::chrono::month& m, const std::chrono::weekday_indexed& wdi) noexcept; ``` | (2) | (since C++20) | | ``` constexpr year_month_weekday(const std::chrono::sys_days& dp) noexcept; ``` | (3) | (since C++20) | | ``` explicit constexpr year_month_weekday(const std::chrono::local_days& dp) noexcept; ``` | (4) | (since C++20) | Constructs a `year_month_weekday` object. 1) Default constructor leaves the fields uninitialized. 2) Constructs a `year_month_weekday` object storing the year `y`, the month `m`, the weekday `wdi.weekday()` and the weekday index `wdi.index()`. 3) Constructs a `year_month_weekday` object corresponding to the date represented by `dp`. For any `year_month_weekday` object storing a valid date, converting it to `sys_days` and back yields the same value. This constructor defines an implicit conversion from `sys_days` to `year_month_weekday`. 4) Constructs a `year_month_weekday` object corresponding to the date represented by `dp`. Equivalent to `year_month_weekday(sys_days(dp.time_since_epoch()))`. ### Notes A `year_month_weekday` can also be created by combining one of the partial-date types `std::chrono::year_month` and `std::chrono::month_weekday` with the missing component (indexed weekday and year, respectively) using `operator/`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) |
programming_docs
cpp std::chrono::year_month_weekday::year, std::chrono::year_month_weekday::month, std::chrono::year_month_weekday::weekday, std::chrono::year_month_weekday::index, std::chrono::year_month_weekday::weekday_indexed std::chrono::year\_month\_weekday::year, std::chrono::year\_month\_weekday::month, std::chrono::year\_month\_weekday::weekday, std::chrono::year\_month\_weekday::index, std::chrono::year\_month\_weekday::weekday\_indexed ============================================================================================================================================================================================================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::year year() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month month() const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::weekday weekday() const noexcept; ``` | (3) | (since C++20) | | ``` constexpr unsigned index() const noexcept; ``` | (4) | (since C++20) | | ``` constexpr std::chrono::weekday_indexed weekday_indexed() const noexcept; ``` | (5) | (since C++20) | Retrieves the field values stored in this `year_month_weekday` object. ### Return values 1) Returns the stored `std::chrono::year` value. 2) Returns the stored `std::chrono::month` value. 3) Returns the stored `std::chrono::weekday` value. 4) Returns the stored weekday index. 5) `weekday()[index()]`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto ym {std::chrono::year(2021)/std::chrono::January}; constexpr auto wdi {std::chrono::Wednesday[1]}; auto ymwdi {ym/wdi}; auto index = ymwdi.index() + 1; auto weekday = ymwdi.weekday() + std::chrono::days(1); ymwdi = {ymwdi.year()/ymwdi.month()/weekday[index]}; // Second Thursday in January, 2021 std::cout << (std::chrono::year_month_day{ymwdi} == std::chrono::January/14/2021) << '\n'; } ``` Output: ``` true ``` cpp std::chrono::year_month_weekday::operator+=, std::chrono::year_month_weekday::operator-= std::chrono::year\_month\_weekday::operator+=, std::chrono::year\_month\_weekday::operator-= ============================================================================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month_weekday& operator+=( const std::chrono::years& dy ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday& operator+=( const std::chrono::months& dm ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday& operator-=( const std::chrono::years& dy ) const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday& operator-=( const std::chrono::months& dm ) const noexcept; ``` | (4) | (since C++20) | Modifies the time point `*this` represents by the duration `dy` or `dm`. 1) Equivalent to `*this = *this + dy;` 2) Equivalent to `*this = *this + dm;` 3) Equivalent to `*this = *this - dy;` 4) Equivalent to `*this = *this - dm;` For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (1,3) are preferred if the call would otherwise be ambiguous. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ymwi {1/std::chrono::Wednesday[2]/2021}; ymwi += std::chrono::years(5); std::cout << (static_cast<std::chrono::year_month_day>(ymwi) == std::chrono::year(2026)/1/14) << ' '; ymwi -= std::chrono::months(1); std::cout << (static_cast<std::chrono::year_month_day>(ymwi) == std::chrono::day(10)/12/2025) << '\n'; } ``` Output: ``` true true ``` ### See also | | | | --- | --- | | [operator+operator-](operator_arith_2 "cpp/chrono/year month weekday/operator arith 2") (C++20) | adds or subtracts a `year_month_weekday` and some number of years or months (function) | cpp std::chrono::operator==(std::chrono::year_month_weekday) std::chrono::operator==(std::chrono::year\_month\_weekday) ========================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==(const std::chrono::year_month_weekday& x, const std::chrono::year_month_weekday& y) noexcept; ``` | | (since C++20) | Compares the two `year_month_weekday` values `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.year() == y.year() && x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed()`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { constexpr auto ymwdi1 {Wednesday[1]/January/2021}; constexpr year_month_weekday ymwdi2 {year(2021), month(1), weekday(3)[1]}; std::cout << std::boolalpha << (ymwdi1 == ymwdi2) << '\n'; } ``` Output: ``` true ``` cpp std::chrono::year_month_weekday::ok std::chrono::year\_month\_weekday::ok ===================================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if this `year_month_weekday` object represents a valid date. ### Return value `true` if this `year_month_weekday` object represents a valid date, that is, `year().ok() && month().ok() && weekday_indexed().ok()` is `true` and there are at least `index()` `weekday()`s in the specified year and month. Otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ymwdi {std::chrono::Wednesday[1]/1/2021}; std::cout << (ymwdi.ok()) << ' '; ymwdi = std::chrono::year(2021)/std::chrono::month(1)/ std::chrono::Wednesday[42]; std::cout << (ymwdi.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::operator<<(std::chrono::month_day) std::chrono::operator<<(std::chrono::month\_day) ================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::month_day& md ); ``` | | (since C++20) | Outputs a textual representation of `md` into the stream `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}/{}"), md.month(), md.day())`. where `STATICALLY_WIDEN<CharT>("{:L}/{}")` is `"{:L}/{}"` if `CharT` is `char`, and `L"{:L}/{}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::month\_day>](formatter "cpp/chrono/month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_day` according to the provided format (class template specialization) | cpp std::chrono::month_day::month, std::chrono::month_day::day std::chrono::month\_day::month, std::chrono::month\_day::day ============================================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::month month() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::day day() const noexcept; ``` | (1) | (since C++20) | Retrieves the month and day values stored in this `month_day` object. ### Return value 1) Returns the stored `std::chrono::month` value. 2) Returns the stored `std::chrono::day` value. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto md {std::chrono::July/15}; std::cout << (md.month() == std::chrono::month(7)) << ' '; std::cout << (md.day() == std::chrono::day(15)) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::month_day::month_day std::chrono::month\_day::month\_day =================================== | | | | | --- | --- | --- | | ``` month_day() = default; ``` | (1) | (since C++20) | | ``` constexpr month_day(const std::chrono::month& m, const std::chrono::day& d) noexcept; ``` | (2) | (since C++20) | Constructs a `month_day`. 1) Default constructor leaves the stored month and day values uninitialized. 2) Constructs a `month_day` that stores the month `m` and the day `d`. ### Notes A more convenient way to construct a `month_day` is with `operator/`, e.g., `[std::chrono::April](http://en.cppreference.com/w/cpp/chrono/month)/1`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::operator==,<=>(std::chrono::month_day) std::chrono::operator==,<=>(std::chrono::month\_day) ==================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::month_day& x, const std::chrono::month_day& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::month_day& x, const std::chrono::month_day& y ) noexcept; ``` | (2) | (since C++20) | Compares two `month_day` values. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `x.month() == y.month() && x.day() == y.day()` 2) `x.month() <=> y.month() != 0 ? x.month() <=> y.month() : x.day() <=> y.day()` ### Example ``` #include <iostream> #include <chrono> int main() { constexpr auto md1 {std::chrono::August/15}; constexpr auto md2 {std::chrono::month(8)/std::chrono::day(15)}; std::cout << std::boolalpha << (md1 == md2) << '\n'; static_assert(md1 <= md2); } ``` Output: ``` true ``` cpp std::chrono::month_day::ok std::chrono::month\_day::ok =========================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Determines whether this `month_day` stores a valid month-day combination. The combination is valid if `month()` represents a valid month (`month().ok() == true`), `unsigned{day()} >= 1`, and `unsigned{day()} <= D`, where D is the number of days in the month represented by `month()`. The number of days in February is considered to be 29. ### Return value `true` if the month and day combination is valid, otherwise false. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto md1 {std::chrono::July/15}; std::cout << (md1.ok()) << ' '; constexpr std::chrono::month_day md2 {std::chrono::month(14), std::chrono::day(42)}; std::cout << (md2.ok()) << ' '; constexpr auto md3 {std::chrono::February/29}; std::cout << (md3.ok()) << '\n'; } ``` Output: ``` true false true ``` cpp std::chrono::duration_values<Rep>::zero std::chrono::duration\_values<Rep>::zero ======================================== | | | | | --- | --- | --- | | ``` static constexpr Rep zero(); ``` | | (until C++20) | | ``` static constexpr Rep zero() noexcept; ``` | | (since C++20) | Returns a zero-length representation. ### Parameters (none). ### Return value returns `Rep(0)`. ### See also | | | | --- | --- | | [zero](../duration/zero "cpp/chrono/duration/zero") [static] | returns the special duration value zero (public static member function of `std::chrono::duration<Rep,Period>`) | | [min](min "cpp/chrono/duration values/min") [static] | returns the smallest possible representation (public static member function) | | [max](max "cpp/chrono/duration values/max") [static] | returns the largest possible representation (public static member function) | cpp std::chrono::duration_values<Rep>::max std::chrono::duration\_values<Rep>::max ======================================= | | | | | --- | --- | --- | | ``` static constexpr Rep max(); ``` | | (until C++20) | | ``` static constexpr Rep max() noexcept; ``` | | (since C++20) | Returns the largest possible representation. ### Parameters (none). ### Return value returns `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<Rep>::max()`. ### See also | | | | --- | --- | | [max](../duration/max "cpp/chrono/duration/max") [static] | returns the special duration value max (public static member function of `std::chrono::duration<Rep,Period>`) | | [zero](zero "cpp/chrono/duration values/zero") [static] | returns a zero-length representation (public static member function) | | [min](min "cpp/chrono/duration values/min") [static] | returns the smallest possible representation (public static member function) | cpp std::chrono::duration_values<Rep>::min std::chrono::duration\_values<Rep>::min ======================================= | | | | | --- | --- | --- | | ``` static constexpr Rep min(); ``` | | (until C++20) | | ``` static constexpr Rep min() noexcept; ``` | | (since C++20) | Returns the lowest possible representation. ### Parameters (none). ### Return value returns `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<Rep>::lowest()`. ### See also | | | | --- | --- | | [min](../duration/min "cpp/chrono/duration/min") [static] | returns the special duration value min (public static member function of `std::chrono::duration<Rep,Period>`) | | [zero](zero "cpp/chrono/duration values/zero") [static] | returns a zero-length representation (public static member function) | | [max](max "cpp/chrono/duration values/max") [static] | returns the largest possible representation (public static member function) | cpp std::chrono::operator<<(std::chrono::month_weekday) std::chrono::operator<<(std::chrono::month\_weekday) ==================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::month_weekday& mwd ); ``` | | (since C++20) | Outputs a textual representation of `mwd` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}/{:L}"), mwd.month(), mwd.weekday\_indexed());` where `STATICALLY_WIDEN<CharT>("{:L}/{:L}")` is `"{:L}/{:L}"` if `CharT` is `char`, and `L"{:L}/{:L}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::month>](../month/formatter "cpp/chrono/month/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month` according to the provided format (class template specialization) | cpp std::chrono::month_weekday::month_weekday std::chrono::month\_weekday::month\_weekday =========================================== | | | | | --- | --- | --- | | ``` constexpr month_weekday(const std::chrono::month& m, const std::chrono::weekday_indexed& wdi) noexcept; ``` | | (since C++20) | Constructs a `month_weekday` object that stores the [`month`](../month "cpp/chrono/month") `m` and the [`weekday_indexed`](../weekday_indexed "cpp/chrono/weekday indexed") `wdi`. ### Notes A more convenient way to construct a `month_weekday` is with `operator/`, e.g., `[std::chrono::April](http://en.cppreference.com/w/cpp/chrono/month)/[std::chrono::Sunday](http://en.cppreference.com/w/cpp/chrono/weekday)[2]`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::month_weekday::month, std::chrono::month_weekday::weekday_indexed std::chrono::month\_weekday::month, std::chrono::month\_weekday::weekday\_indexed ================================================================================= | | | | | --- | --- | --- | | ``` constexpr std::chrono::month month() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::weekday_indexed weekday_indexed() const noexcept; ``` | (2) | (since C++20) | Retrieves a copy of the [`month`](../month "cpp/chrono/month") and [`weekday_indexed`](../weekday_indexed "cpp/chrono/weekday indexed") objects stored in `*this`. ### Return value 1) a copy of the `std::chrono::month` object stored in `*this` 2) a copy of the `std::chrono::weekday_indexed` object stored in `*this` ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto mwdi {std::chrono::March/std::chrono::Friday[1]}; // 1st Friday in a March std::cout << (std::chrono::year_month_day{mwdi/2024} == std::chrono::year_month_day{std::chrono::March/1/2024}) << ' '; auto index = mwdi.weekday_indexed().index(); auto weekday = mwdi.weekday_indexed().weekday(); mwdi = {mwdi.month(), weekday[index + 4]}; // 5th Friday in a March std::cout << (std::chrono::year_month_day{mwdi/2024} == std::chrono::year_month_day{std::chrono::March/29/2024}) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::operator==(std::chrono::month_weekday) std::chrono::operator==(std::chrono::month\_weekday) ==================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==(const std::chrono::month_weekday& x, const std::chrono::month_weekday& y) noexcept; ``` | | (since C++20) | Compares the two `month_weekday` values `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed()`. ### Example ``` #include <iostream> #include <chrono> int main() { constexpr auto mwdi1 {std::chrono::March/std::chrono::Friday[1]}; constexpr std::chrono::month_weekday mwdi2 {std::chrono::month(3), std::chrono::weekday(5)[1]}; std::cout << std::boolalpha << (mwdi1 == mwdi2) << '\n'; } ``` Output: ``` true ```
programming_docs
cpp std::chrono::month_weekday::ok std::chrono::month\_weekday::ok =============================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the contained [`month`](../month "cpp/chrono/month") and [`weekday_indexed`](../weekday_indexed "cpp/chrono/weekday indexed") objects are valid. ### Return value `month().ok() && weekday_indexed().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto mwdi {std::chrono::March/std::chrono::Friday[1]}; std::cout << (mwdi.ok()) << ' '; mwdi = {std::chrono::month(17)/std::chrono::Friday[1]}; std::cout << (mwdi.ok()) << ' '; mwdi = {std::chrono::March/std::chrono::Friday[-4]}; std::cout << (mwdi.ok()) << '\n'; } ``` Output: ``` true false false ``` cpp std::chrono::operator<<(std::chrono::sys_time) std::chrono::operator<<(std::chrono::sys\_time) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits, class Duration> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::chrono::sys_time<Duration>& tp); ``` | (1) | (since C++20) | | ``` template <class CharT, class Traits, class Duration> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::chrono::sys_days& tp); ``` | (2) | (since C++20) | Outputs `tp` into the stream `os`. 1) Equivalent to: ``` return os << std::format(os.getloc(), STATICALLY-WIDEN<CharT>("{:L%F %T}"), tp); ``` where `STATICALLY_WIDEN<CharT>("{:L%F %T}")` is `"{:L%F %T}"` if `CharT` is `char`, and `L"{:L%F %T}"` if `CharT` is `wchar_t`. This overload participates in overload resolution only if `std::chrono::treat_as_floating_point_v<typename Duration::rep>` is `false` and `Duration(1) < [std::chrono::days](http://en.cppreference.com/w/cpp/chrono/duration)(1)`. 2) Equivalent to `os << [std::chrono::year\_month\_day](http://en.cppreference.com/w/cpp/chrono/year_month_day)(tp);` ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::sys\_time>](formatter "cpp/chrono/system clock/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `sys_time` according to the provided format (class template specialization) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [operator<<](../year_month_day/operator_ltlt "cpp/chrono/year month day/operator ltlt") (C++20) | outputs a `year_month_day` into a stream (function template) | cpp std::chrono::system_clock::now std::chrono::system\_clock::now =============================== | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::system_clock> now() noexcept; ``` | | (since C++11) | Returns a time point representing the current point in time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::system_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::system_clock::to_time_t std::chrono::system\_clock::to\_time\_t ======================================= | | | | | --- | --- | --- | | ``` static std::time_t to_time_t( const time_point& t ) noexcept; ``` | | (since C++11) | Converts `t` to a `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` type. If `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` has lower precision, it is implementation-defined whether the value is rounded or truncated. ### Parameters | | | | | --- | --- | --- | | t | - | system clock time point to convert | ### Return value A `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` value representing `t`. ### Example Get the current time as a `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` two ways. ``` #include <iostream> #include <ctime> #include <chrono> #include <thread> using namespace std::chrono_literals; int main() { // The old way std::time_t oldt = std::time(nullptr); std::this_thread::sleep_for(2700ms); // The new way std::time_t newt = std::chrono::system_clock::to_time_t( std::chrono::system_clock::now()); std::cout << "oldt-newt == " << oldt-newt << " s\n"; } ``` Possible output: ``` oldt-newt == -3 s ``` ### See also | | | | --- | --- | | [from\_time\_t](from_time_t "cpp/chrono/system clock/from time t") [static] | converts `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` to a system clock time point (public static member function) | cpp std::chrono::system_clock::from_time_t std::chrono::system\_clock::from\_time\_t ========================================= | | | | | --- | --- | --- | | ``` static std::chrono::system_clock::time_point from_time_t( std::time_t t ) noexcept; ``` | | (since C++11) | Converts `t` to a time point type, using the coarser precision of the two types. If `time_point` has lower precision, it is implementation defined whether the value is rounded or truncated. ### Parameters | | | | | --- | --- | --- | | t | - | `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` value to convert | ### Return value A value of type [`std::chrono::system_clock::time_point`](../system_clock#Member_types "cpp/chrono/system clock") representing `t`. ### Example ``` #include <iostream> #include <ctime> #include <chrono> #include <thread> int main() { using namespace std::chrono_literals; const std::time_t t = std::time(nullptr); // usually has "1 second" precision const auto from = std::chrono::system_clock::from_time_t(t); std::this_thread::sleep_for(500ms); const auto diff = std::chrono::system_clock::now() - from; std::cout << diff << " (" << std::chrono::round<std::chrono::milliseconds>(diff) << ")\n"; } ``` Possible output: ``` 987654321ns (987ms) ``` ### See also | | | | --- | --- | | [to\_time\_t](to_time_t "cpp/chrono/system clock/to time t") [static] | converts a system clock time point to `[std::time\_t](../c/time_t "cpp/chrono/c/time t")` (public static member function) | cpp std::chrono::file_clock::to_utc, std::chrono::file_clock::from_utc std::chrono::file\_clock::to\_utc, std::chrono::file\_clock::from\_utc ====================================================================== | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::utc_time</*see below*/> to_utc( const std::chrono::file_time<Duration>& t ); ``` | (1) | (since C++20) (optional) | | ``` template < class Duration > static std::chrono::file_time</*see below*/> from_utc( const std::chrono::utc_time<Duration>& t ); ``` | (2) | (since C++20) (optional) | 1) Converts the `file_time` `t` to a `utc_time` representing the same point in time. 2) Converts the `utc_time` `t` to a `file_time` representing the same point in time. The duration of the return type is computed from `Duration` in an unspecified manner. These function templates are optional: an implementation may choose to instead provide `to_sys` and `from_sys`. ### Return value 1) A `utc_time` representing the same point in time as the argument. 2) A `file_time` representing the same point in time as the argument. ### Notes User code should usually use `std::chrono::clock_cast`, which provides a generic interface to convert time points between clocks, rather than call these functions directly. ### Example ### See also | | | | --- | --- | | [to\_sysfrom\_sys](to_from_sys "cpp/chrono/file clock/to from sys") [static] (optional) | converts between `file_time` and `sys_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::operator<<(std::chrono::file_time) std::chrono::operator<<(std::chrono::file\_time) ================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Duration > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::file_time<Duration>& tp ); ``` | | (since C++20) | Outputs `tp` into the stream `os`, as if by `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY-WIDEN("{:L%F %T}"), tp)`, where `STATICALLY_WIDEN<CharT>("{:L%F %T}")` is `"{:L%F %T}"` if `CharT` is `char`, and `L"{:L%F %T}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::file\_time>](formatter "cpp/chrono/file clock/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `file_time` according to the provided format (class template specialization) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | cpp std::chrono::file_clock::now std::chrono::file\_clock::now ============================= | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::file_clock> now() noexcept; ``` | | (since C++20) | Returns a time point representing the current point in time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::file_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::file_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::file_clock::to_sys, std::chrono::file_clock::from_sys std::chrono::file\_clock::to\_sys, std::chrono::file\_clock::from\_sys ====================================================================== | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::sys_time</*see below*/> to_sys( const std::chrono::file_time<Duration>& t ); ``` | (1) | (since C++20) (optional) | | ``` template< class Duration > static std::chrono::file_time</*see below*/> from_sys( const std::chrono::sys_time<Duration>& t ); ``` | (2) | (since C++20) (optional) | 1) Converts the `file_time` `t` to a `sys_time` representing the same point in time. 2) Converts the `sys_time` `t` to a `file_time` representing the same point in time. The duration of the return type is computed from `Duration` in an unspecified manner. These function templates are optional: an implementation may choose to instead provide `to_utc` and `from_utc`. ### Return value 1) A `sys_time` representing the same point in time as the argument. 2) A `file_time` representing the same point in time as the argument. ### Notes User code should usually use `std::chrono::clock_cast`, which provides a generic interface to convert time points between clocks, rather than call these functions directly. ### Example ### See also | | | | --- | --- | | [to\_utcfrom\_utc](to_from_utc "cpp/chrono/file clock/to from utc") [static] (optional) | converts between `file_time` and `utc_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::tzdb::current_zone std::chrono::tzdb::current\_zone ================================ | | | | | --- | --- | --- | | ``` const std::chrono::time_zone* current_zone() const; ``` | | (since C++20) | Obtains a pointer to a `std::chrono::time_zone` in this database that represents the local time zone of the computer. ### Return value A pointer to the `std::chrono::time_zone` in this database that represents the local time zone of the computer. cpp std::chrono::tzdb::locate_zone std::chrono::tzdb::locate\_zone =============================== | | | | | --- | --- | --- | | ``` const std::chrono::time_zone* locate_zone(std::string_view tz_name) const; ``` | | (since C++20) | Obtains a pointer to a `std::chrono::time_zone` in this database that represents the time zone designated by `tz_name`. If `p` is the returned pointer, then either `p->name() == tz_name` or that there is a `[std::chrono::time\_zone\_link](../time_zone_link "cpp/chrono/time zone link")` `l` in this database such that `p->name() == l.target() && l.name() == tz_name`. ### Return value A pointer to the `std::chrono::time_zone` in this database that represents the time zone designated by `tz_name`. ### Exceptions Throws `[std::runtime\_error](../../error/runtime_error "cpp/error/runtime error")` if no such `time_zone` can be found. cpp std::chrono::time_zone_link::name, std::chrono::time_zone_link::target std::chrono::time\_zone\_link::name, std::chrono::time\_zone\_link::target ========================================================================== | | | | | --- | --- | --- | | ``` std::string_view name() const noexcept; ``` | (1) | | | ``` std::string_view target() const noexcept; ``` | (2) | | Accesses the name and target of this `time_zone_link` object. ### Return value 1) The alternative name this `time_zone_link` object represents. 2) The name of the `std::chrono::time_zone` for which this `time_zone_link` object provides an alternative name. cpp std::chrono::operator<<(std::chrono::year_month_day_last) std::chrono::operator<<(std::chrono::year\_month\_day\_last) ============================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year_month_day_last& ymdl ); ``` | | (since C++20) | Outputs a textual representation of `ymdl` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{}/{:L}"), ymdl.year(), ymdl.month\_day\_last());` where `STATICALLY_WIDEN<CharT>("{}/{:L}")` is `"{}/{:L}"` if `CharT` is `char`, and `L"{}/{:L}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year\_month\_day>](../year_month_day/formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day` according to the provided format (class template specialization) | cpp std::chrono::year_month_day_last::year_month_day_last std::chrono::year\_month\_day\_last::year\_month\_day\_last =========================================================== | | | | | --- | --- | --- | | ``` constexpr year_month_day_last( const std::chrono::year& y, const std::chrono::month_day_last& mdl ) noexcept; ``` | | (since C++20) | Constructs a `year_month_day_last` object storing the year `y` and the month `mdl.month()`. The constructed object represents the last day of that year and month. ### Notes A `year_month_day_last` can also be created by combining a `std::chrono::year_month` with `std::chrono::last` using `operator/`. ### Example ``` #include <chrono> #include <iostream> int main() { std::cout << "All last days of months of a given year: \n"; constexpr std::chrono::year year{2021}; for (int i{1}; i <= 12; ++i) { const std::chrono::month_day_last mdl{std::chrono::month(i) / std::chrono::last}; const std::chrono::year_month_day_last ymdl{year, mdl}; std::cout << ymdl << " day: " << ymdl.day() << '\n'; } } ``` Possible output: ``` All last days of months of a given year: 2021/Jan/last day: 31 2021/Feb/last day: 28 2021/Mar/last day: 31 2021/Apr/last day: 30 2021/May/last day: 31 2021/Jun/last day: 30 2021/Jul/last day: 31 2021/Aug/last day: 31 2021/Sep/last day: 30 2021/Oct/last day: 31 2021/Nov/last day: 30 2021/Dec/last day: 31 ``` ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) |
programming_docs
cpp std::chrono::year_month_day_last::year, std::chrono::year_month_day_last::month, std::chrono::year_month_day_last::day, std::chrono::year_month_day_last::month_day_last std::chrono::year\_month\_day\_last::year, std::chrono::year\_month\_day\_last::month, std::chrono::year\_month\_day\_last::day, std::chrono::year\_month\_day\_last::month\_day\_last ====================================================================================================================================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::year year() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month month() const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::day day() const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::month_day_last month_day_last() const noexcept; ``` | (4) | (since C++20) | Retrieves the field values stored in this `year_month_day_last` object. ### Return values 1) Returns the stored `std::chrono::year` value. 2) Returns the stored `std::chrono::month` value. 3) A `std::chrono::day` value corresponding to the last day of the stored year and month. If `this->ok()` is `false`, the return value is unspecified. 4) A `std::chrono::month_day_last` constructed from `month()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; constexpr auto ymdl {std::chrono::last/11/2020}; std::cout << (ymdl.day() == std::chrono::day(30)) << ' ' << (ymdl.month() == std::chrono::November) << ' ' << (ymdl.year() == std::chrono::year(2020)) << ' '; constexpr auto mdl = ymdl.month_day_last(); std::cout << (mdl == (std::chrono::November/std::chrono::last)) << '\n'; } ``` Output: ``` true true true true ``` cpp std::chrono::year_month_day_last::operator+=, std::chrono::year_month_day_last::operator-= std::chrono::year\_month\_day\_last::operator+=, std::chrono::year\_month\_day\_last::operator-= ================================================================================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month_day_last& operator+=( const std::chrono::years& dy ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year_month_day_last& operator+=( const std::chrono::months& dm ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year_month_day_last& operator-=( const std::chrono::years& dy ) const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year_month_day_last& operator-=( const std::chrono::months& dm ) const noexcept; ``` | (4) | (since C++20) | Modifies the time point `*this` represents by the duration `dy` or `dm`. 1) Equivalent to `*this = *this + dy;` 2) Equivalent to `*this = *this + dm;` 3) Equivalent to `*this = *this - dy;` 4) Equivalent to `*this = *this - dm;` For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (1,3) are preferred if the call would otherwise be ambiguous. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ymdl {11/std::chrono::last/2020}; ymdl += std::chrono::years(15); std::cout << (ymdl.day() == std::chrono::day(30)) << ' ' << (ymdl.month() == std::chrono::November) << ' ' << (ymdl.year() == std::chrono::year(2035)) << ' '; ymdl -= std::chrono::months(6); std::cout << (ymdl.day() == std::chrono::day(31)) << ' ' << (ymdl.month() == std::chrono::May) << ' ' << (ymdl.year() == std::chrono::year(2035)) << '\n'; } ``` Output: ``` true true true true true true ``` ### See also | | | | --- | --- | | [operator+operator-](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) | cpp std::chrono::year_month_day_last::ok std::chrono::year\_month\_day\_last::ok ======================================= | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if `*this` represents a valid date. Because a `year_month_day_last` represents the last day of a particular month, it represents a valid date as long as the year and month are valid. ### Return value `year().ok() && month().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto ymdl {std::chrono::last/11/2020}; std::cout << (ymdl.ok()) << ' '; ymdl = std::chrono::year(2020)/std::chrono::month(13)/std::chrono::last; std::cout << (ymdl.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::operator<<(std::chrono::weekday) std::chrono::operator<<(std::chrono::weekday) ============================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::weekday& wd ); ``` | | (since C++20) | If `!wd.ok()`, inserts `wd.c_encoding()` followed by `" is not a valid weekday"` into `os`. Otherwise, forms a `std::basic_string<CharT>` `s` consisting of the abbreviated weekday name for the weekday represented by `wd`, determined using the locale associated with `os`, and inserts `s` into `os`. Equivalent to. `return os << (wd.ok() ? [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L%a}"), wd) : [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{} is not a valid weekday"), wd.c\_encoding()));` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::weekday>](formatter "cpp/chrono/weekday/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday` according to the provided format (class template specialization) | cpp std::chrono::weekday::operator[] std::chrono::weekday::operator[] ================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::weekday_indexed operator[](unsigned index) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::weekday_last operator[](std::chrono::last_spec) const noexcept; ``` | (2) | (since C++20) | 1) Constructs a `weekday_indexed` from `*this` and `index`. The result represents the `index`-th weekday in some yet-to-be-specified month. If `index` is not in the range [0, 7] or if `!ok()` the values held in the result is unspecified. 2) Constructs a `weekday_last` from `*this`. The result represents the last weekday in some yet-to-be-specified month. ### Return value 1) `[std::chrono::weekday\_indexed](http://en.cppreference.com/w/cpp/chrono/weekday_indexed)(\*this, index)` 2) `[std::chrono::weekday\_last](http://en.cppreference.com/w/cpp/chrono/weekday_last)(\*this)` ### Example ``` #include <chrono> #include <iostream> using namespace std::chrono; int main() { constexpr auto second_tuesday_in_October_2019 = year_month_day{ Tuesday[2] / October / 2019y }; constexpr auto last_tuesday_in_October_2019 = year_month_day { Tuesday[last] / October / 2019y }; std::cout << second_tuesday_in_October_2019 << '\n' << last_tuesday_in_October_2019 << '\n'; } ``` Possible output: ``` 2019-10-08 2019-10-29 ``` cpp std::chrono::weekday::operator++, std::chrono::weekday::operator-- std::chrono::weekday::operator++, std::chrono::weekday::operator-- ================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::weekday& operator++() noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::weekday operator++(int) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::weekday& operator--() noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::weekday operator--(int) noexcept; ``` | (4) | (since C++20) | Adds or subtracts 1 from the weekday value, reducing the result modulo 7 to an integer in the range [0, 6]. 1-2) Performs `\*this += [std::chrono::days](http://en.cppreference.com/w/cpp/chrono/duration){1};` 3-4) Performs `\*this -= [std::chrono::days](http://en.cppreference.com/w/cpp/chrono/duration){1};` ### Parameters (none). ### Return value 1,3) a reference to this `weekday` after modification 2,4) a copy of the `weekday` made before modification ### Notes After a call to one of these functions, `ok()` is always true. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; std::chrono::weekday wd {0}; // Sunday is 0 or 7 --wd; std::cout << (wd == std::chrono::Saturday) << ' '; ++wd; std::cout << (wd == std::chrono::Sunday) << '\n'; } ``` Output: ``` true true ``` ### See also | | | | --- | --- | | [operator+=operator-=](operator_arith "cpp/chrono/weekday/operator arith") | adds or subtracts a number of days (public member function) | | [operator+operator-](operator_arith_2 "cpp/chrono/weekday/operator arith 2") (C++20) | performs arithmetic on `weekday`s (function) | cpp std::chrono::weekday::weekday std::chrono::weekday::weekday ============================= | | | | | --- | --- | --- | | ``` weekday() = default; ``` | (1) | (since C++20) | | ``` explicit constexpr weekday( unsigned wd ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr weekday( const std::chrono::sys_days& dp ) noexcept; ``` | (3) | (since C++20) | | ``` explicit constexpr weekday( const std::chrono::local_days& dp ) noexcept; ``` | (4) | (since C++20) | Constructs a `weekday` object. 1) Default constructor leaves the weekday value uninitialized. 2) Constructs a `weekday` object holding the weekday value `wd`. If `wd == 7`, the value held is `​0​`. If `wd > 255`, the value held is unspecified. 3) Constructs a `weekday` object representing the day of the week `dp` corresponds to. This constructor defines an implicit conversion from `std::chrono::sys_days` to `weekday`. 4) Constructs a `weekday` object representing the day of the week `dp` corresponds to, as if by `weekday([std::chrono::sys\_days](http://en.cppreference.com/w/cpp/chrono/system_clock)(dp.time\_since\_epoch()))`. ### Example ``` #include <chrono> #include <iostream> #include <iomanip> int main() { constexpr std::chrono::weekday friday{5}; // uses overload (2) static_assert(friday == std::chrono::Friday); for (int y {2020}; y <= 2023; ++y) { const std::chrono::year cur_year{y}; for (int cur_month{1}; cur_month != 13; ++cur_month) { const std::chrono::year_month_day ymd{ cur_year / cur_month / 13 }; const std::chrono::weekday cur_weekday{ std::chrono::sys_days{ ymd } }; // (3) if (cur_weekday == friday) { // std::cout << ymd << " is " << friday << '\n'; std::cout << int(ymd.year()) << '-' << std::setw(2) << std::setfill('0') << unsigned(ymd.month()) << '-' << unsigned(ymd.day()) << " is Fri\n"; } } } } ``` Output: ``` 2020-03-13 is Fri 2020-11-13 is Fri 2021-08-13 is Fri 2022-05-13 is Fri 2023-01-13 is Fri 2023-10-13 is Fri ``` cpp std::chrono::weekday::c_encoding, std::chrono::weekday::iso_encoding std::chrono::weekday::c\_encoding, std::chrono::weekday::iso\_encoding ====================================================================== | | | | | --- | --- | --- | | ``` constexpr unsigned c_encoding() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr unsigned iso_encoding() const noexcept; ``` | (2) | (since C++20) | 1) Returns the weekday value stored in `*this`. 2) Returns the weekday value stored in `*this`, except that Sunday (stored as `​0​`) is interpreted as `7` according to ISO 8601. ### Return value 1) The weekday value stored in `*this`. 2) `c_encoding() == 0u ? 7u : c_encoding()`. ### Example ``` #include <chrono> #include <iostream> int main() { std::cout << "i: C: ISO: Weekday:\n"; for (unsigned i{0}; i != 8; ++i) { const std::chrono::weekday w{i}; std::cout << i << " " << w.c_encoding() << " " << w.iso_encoding() << " " << w << '\n'; } } ``` Possible output: ``` i: C: ISO: Weekday: 0 0 7 Sun 1 1 1 Mon 2 2 2 Tue 3 3 3 Wed 4 4 4 Thu 5 5 5 Fri 6 6 6 Sat 7 0 7 Sun ``` cpp std::chrono::operator==(std::chrono::weekday) std::chrono::operator==(std::chrono::weekday) ============================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::weekday& x, const std::chrono::weekday& y ) noexcept; ``` | | (since C++20) | Compare the two `std::chrono::weekday` `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.c_encoding() == y.c_encoding()`. ### Notes `weekday` does not support the `<`, `<=`, `>` and `>=` operators because there is no universal consensus on which day is the first day of the week. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::literals; constexpr std::chrono::weekday wd1{2}; constexpr std::chrono::weekday wd2{std::chrono::Friday}; // 1 January 2021 is a Friday constexpr std::chrono::weekday wd3{2021y/1/1}; std::cout << std::boolalpha; std::cout << (wd1 == wd2) << "\n"; std::cout << (wd2 == wd3) << "\n"; } ``` Output: ``` false true ``` cpp std::chrono::weekday::ok std::chrono::weekday::ok ======================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the weekday value stored in `*this` is in the valid range, i.e., [0, 6]. ### Return value `true` if the weekday value stored in `*this` is in the range [0, 6]. Otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { for (const unsigned u : {0, 1, 6, 7, 8, 9}) { const std::chrono::weekday wd{u}; std::cout << "u = " << u << ", wd = " << wd.c_encoding() // Monday is 1 << (wd.ok() ? " is a valid weekday.\n" : " is an invalid weekday!\n"); } } ``` Output: ``` u = 0, wd = 0 is a valid weekday. u = 1, wd = 1 is a valid weekday. u = 6, wd = 6 is a valid weekday. u = 7, wd = 0 is a valid weekday. u = 8, wd = 8 is an invalid weekday! u = 9, wd = 9 is an invalid weekday! ``` ### See also | | | | --- | --- | | [c\_encodingiso\_encoding](encoding "cpp/chrono/weekday/encoding") | retrieves the stored weekday valueretrieves ISO 8601 weekday value (public member function) | cpp std::chrono::operator<<(std::chrono::weekday_last) std::chrono::operator<<(std::chrono::weekday\_last) =================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::weekday_last& wdl ); ``` | | (since C++20) | Outputs a textual representation of `wdl` into the stream `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}[last]"), wdl.weekday());` where `STATICALLY_WIDEN<CharT>("{:L}[last]")` is `"{:L}[last]"` if `CharT` is `char`, and `L"{:L}[last]"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::weekday>](../weekday/formatter "cpp/chrono/weekday/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday` according to the provided format (class template specialization) | cpp std::chrono::weekday_last::weekday_last std::chrono::weekday\_last::weekday\_last ========================================= | | | | | --- | --- | --- | | ``` explicit constexpr weekday_last( const std::chrono::weekday& wd ) noexcept; ``` | | (since C++20) | Constructs a `weekday_last` object storing the `weekday` `wd`. ### Notes A more convenient way to construct a `weekday_last` is with `weekday`'s `operator[]`, i.e., `wd[[std::chrono::last](http://en.cppreference.com/w/cpp/chrono/last_spec)]`. ### Example ``` #include <chrono> #include <iostream> using namespace std::chrono; int main() { const year_month_day ymd { floor<days>(system_clock::now()) }; const weekday_last wdl { Sunday[last] }; // A last Sunday of a month const year_month_day last_sun { ymd.year() / ymd.month() / wdl }; std::cout << "The last Sunday of current month falls on " << (int)last_sun.year() << '/' << (unsigned)last_sun.month() << '/' << (unsigned)last_sun.day() << '\n'; } ``` Possible output: ``` The last Sunday of current month falls on 2021/9/26 ``` cpp std::chrono::weekday_last::weekday std::chrono::weekday\_last::weekday =================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::weekday weekday() const noexcept; ``` | | (since C++20) | Retrieves a copy of the `std::chrono::weekday` object stored in `*this`. ### Return value A copy of the `std::chrono::weekday` object stored in `*this`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto wdl {Tuesday[last]}; // Last Tuesday of a month std::cout << (year_month_day{wdl/10/2019} == year_month_day{October/29/2019}) << ' '; wdl = {(wdl.weekday() + days(2))[last]}; // Last Tuesday is now last Thursday std::cout << (year_month_day{wdl/10/2019} == year_month_day{October/31/2019}) << '\n'; } ``` Output: ``` true true ```
programming_docs
cpp std::chrono::operator==(std::chrono::weekday_last) std::chrono::operator==(std::chrono::weekday\_last) =================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::weekday_last& x, const std::chrono::weekday_last& y ) noexcept; ``` | | (since C++20) | Compares the two `weekday_last` values `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.weekday() == y.weekday()`. ### Example ``` #include <iostream> #include <chrono> int main() { constexpr auto wdl1 {std::chrono::Tuesday[std::chrono::last]}; constexpr std::chrono::weekday_last wdl2 {std::chrono::weekday(2)}; std::cout << std::boolalpha << (wdl1 == wdl2) << ' ' << (wdl1 == std::chrono::Wednesday[std::chrono::last]) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::weekday_last::ok std::chrono::weekday\_last::ok ============================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the weekday object stored in `*this` is valid. ### Return value `weekday().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto wdl {std::chrono::Tuesday[std::chrono::last]}; std::cout << (wdl.ok()) << ' '; wdl = {std::chrono::weekday(42)[std::chrono::last]}; std::cout << (wdl.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::weekday_indexed::weekday_indexed std::chrono::weekday\_indexed::weekday\_indexed =============================================== | | | | | --- | --- | --- | | ``` weekday_indexed() = default; ``` | (1) | (since C++20) | | ``` constexpr weekday_indexed(const std::chrono::weekday& wd, unsigned index) noexcept; ``` | (2) | (since C++20) | Constructs a `weekday_indexed`. 1) Default constructor leaves both the `std::chrono::weekday` and the index value uninitialized. 2) Constructs a `weekday_indexed` storing the weekday `wd` and the index `index`. The values held are unspecified if `!wd.ok() || index > 7`. ### Notes A more convenient way to construct a `weekday_indexed` is with `weekday`'s `operator[]`, i.e., `wd[index]`. ### Example ``` #include <chrono> #include <iostream> using namespace std::chrono; int main() { constexpr auto third_friday = weekday_indexed(Friday, 3); // uses constructor (2) static_assert(third_friday == Friday[3]); weekday_indexed wdi = Tuesday[2]; // represents the 2nd Tuesday std::cout << year_month_day{ wdi / October / 2019y } << '\n'; } ``` Possible output: ``` 2019-10-08 ``` ### See also | | | | --- | --- | | [operator[]](../weekday/operator_at "cpp/chrono/weekday/operator at") | convenience syntax for constructing a [`weekday_indexed`](../weekday_indexed "cpp/chrono/weekday indexed") or [`weekday_last`](../weekday_last "cpp/chrono/weekday last") from this `weekday` (public member function of `std::chrono::weekday`) | cpp std::chrono::weekday_indexed::index std::chrono::weekday\_indexed::index ==================================== | | | | | --- | --- | --- | | ``` constexpr unsigned index() const noexcept; ``` | | (since C++20) | Accesses the index stored in `*this`. ### Return value The index stored in `*this`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; std::chrono::weekday_indexed wdi {std::chrono::Tuesday[2]}; // 2nd Tuesday of a month std::cout << (std::chrono::year_month_day{wdi/10/2019} == std::chrono::year_month_day{std::chrono::October/8/2019}) << ' '; wdi = {wdi.weekday()[wdi.index() + 2]}; // 2nd Tuesday => 4th Tuesday std::cout << (std::chrono::year_month_day{wdi/10/2019} == std::chrono::year_month_day{std::chrono::October/22/2019}) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::operator<<(std::chrono::weekday_indexed) std::chrono::operator<<(std::chrono::weekday\_indexed) ====================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::weekday_indexed& wdi ); ``` | | (since C++20) | Outputs a textual representation of `wdi` into the stream `os`, as if by: `if (wdi.index() >=1 && wdi.index() <= 5) { os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}[{}]"), wdi.weekday(), wdi.index()); } else { os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}[{} is not a valid index]"), wdi.weekday(), wdi.index()); }` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::weekday>](../weekday/formatter "cpp/chrono/weekday/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `weekday` according to the provided format (class template specialization) | cpp std::chrono::weekday_indexed::weekday std::chrono::weekday\_indexed::weekday ====================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::weekday weekday() const noexcept; ``` | | (since C++20) | Retrieves a copy of the `std::chrono::weekday` object stored in `*this`. ### Return value A copy of the `std::chrono::weekday` object stored in `*this`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; std::chrono::weekday_indexed wdi {std::chrono::Tuesday[2]}; // 2nd Tuesday of a month std::cout << (std::chrono::year_month_day{wdi/10/2019} == std::chrono::year_month_day{std::chrono::October/8/2019}) << ' '; wdi = {wdi.weekday() + std::chrono::days(2), wdi.index()}; // 2nd Tuesday => 2nd Thursday std::cout << (std::chrono::year_month_day{wdi/10/2019} == std::chrono::year_month_day{std::chrono::October/10/2019}) << '\n'; } ``` Output: ``` true true ``` ### See also | | | | --- | --- | | [index](index "cpp/chrono/weekday indexed/index") | access the stored index (public member function) | cpp std::chrono::operator==(std::chrono::weekday_indexed) std::chrono::operator==(std::chrono::weekday\_indexed) ====================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::weekday_indexed& x, const std::chrono::weekday_indexed& y ) noexcept; ``` | | (since C++20) | Compares the two `weekday_indexed` `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.weekday() == y.weekday() && x.index() == y.index()`. ### Example ``` #include <chrono> int main() { constexpr std::chrono::weekday_indexed wdi1 {std::chrono::Wednesday[2]}; constexpr std::chrono::weekday_indexed wdi2 {std::chrono::weekday(3), 2}; static_assert(wdi1 == wdi2); } ``` cpp std::chrono::weekday_indexed::ok std::chrono::weekday\_indexed::ok ================================= | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the weekday object and the index stored in `*this` are both valid. ### Return value `true` if `weekday().ok() == true` and `index()` is in the range [1, 5]. Otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; std::chrono::weekday_indexed wdi {std::chrono::Tuesday[2]}; std::cout << (wdi.ok()) << ' '; wdi = {std::chrono::weekday(42)[2]}; std::cout << (wdi.ok()) << ' '; wdi = {std::chrono::Tuesday[-4]}; std::cout << (wdi.ok()) << '\n'; } ``` Output: ``` true false false ``` cpp std::chrono::operator<<(std::chrono::year_month_weekday_last) std::chrono::operator<<(std::chrono::year\_month\_weekday\_last) ================================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year_month_weekday_last& ymwdl ); ``` | | (since C++20) | Outputs a textual representation of `ymwdl` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{}/{:L}/{:L}"), ymwdl.year(), ymwdl.month(), ymwdl.weekday\_last());` where `STATICALLY_WIDEN<CharT>("{}/{:L}/{:L}")` is `"{}/{:L}/{:L}"` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year\_month\_day>](../year_month_day/formatter "cpp/chrono/year month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year_month_day` according to the provided format (class template specialization) | cpp std::chrono::year_month_weekday_last::year_month_weekday_last std::chrono::year\_month\_weekday\_last::year\_month\_weekday\_last =================================================================== | | | | | --- | --- | --- | | ``` constexpr year_month_weekday_last(const std::chrono::year& y, const std::chrono::month& m, const std::chrono::weekday_last& wdl) noexcept; ``` | | (since C++20) | Constructs a `year_month_weekday_last` object storing the year `y`, the month `m`, and the weekday `wdl.weekday()`. The constructed object represents the last weekday of that year and month. ### Notes A `year_month_weekday_last` can also be created by combining one of the partial-date types `std::chrono::year_month` and `std::chrono::month_weekday_last` with the missing component (`weekday_last` and `year`, respectively) using `operator/`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::year_month_weekday_last::year, std::chrono::year_month_weekday_last::month, std::chrono::year_month_weekday_last::weekday, std::chrono::year_month_weekday_last::weekday_last std::chrono::year\_month\_weekday\_last::year, std::chrono::year\_month\_weekday\_last::month, std::chrono::year\_month\_weekday\_last::weekday, std::chrono::year\_month\_weekday\_last::weekday\_last ======================================================================================================================================================================================================= | | | | | --- | --- | --- | | ``` constexpr std::chrono::year year() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::month month() const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::weekday weekday() const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::weekday_last weekday_last() const noexcept; ``` | (4) | (since C++20) | Retrieves the field values stored in this `year_month_weekday_last` object. ### Return values 1) Returns the stored `std::chrono::year` value. 2) Returns the stored `std::chrono::month` value. 3) Returns the stored `std::chrono::weekday` value. 4) `[std::chrono::weekday\_last](http://en.cppreference.com/w/cpp/chrono/weekday_last)(weekday())`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto ymwdl {Tuesday[last]/November/2022}; auto wdl = ymwdl.weekday_last(); wdl = (wdl.weekday() + days(1))[last]; ymwdl = {ymwdl.year() + years(1), ymwdl.month() - months(2), wdl}; std::cout << (year_month_day(ymwdl) == September/27/2023) << '\n'; } ``` Output: ``` true ``` cpp std::chrono::year_month_weekday_last::operator+=, std::chrono::year_month_weekday_last::operator-= std::chrono::year\_month\_weekday\_last::operator+=, std::chrono::year\_month\_weekday\_last::operator-= ======================================================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::year_month_weekday_last& operator+=( const std::chrono::years& dy ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday_last& operator+=( const std::chrono::months& dm ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday_last& operator-=( const std::chrono::years& dy ) const noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year_month_weekday_last& operator-=( const std::chrono::months& dm ) const noexcept; ``` | (4) | (since C++20) | Modifies the time point `*this` represents by the duration `dy` or `dm`. 1) Equivalent to `*this = *this + dy;` 2) Equivalent to `*this = *this + dm;` 3) Equivalent to `*this = *this - dy;` 4) Equivalent to `*this = *this - dm;` For durations that are convertible to both `std::chrono::years` and `std::chrono::months`, the `years` overloads (1,3) are preferred if the call would otherwise be ambiguous. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto ymwdl {August/Tuesday[last]/2022}; ymwdl += months(2); std::cout << (year_month_day{ymwdl} == October/25/2022) << ' '; ymwdl -= years(1); std::cout << (year_month_day{ymwdl} == October/26/2021) << '\n'; } ``` Output: ``` true true ``` ### See also | | | | --- | --- | | [operator+operator-](operator_arith_2 "cpp/chrono/year month weekday last/operator arith 2") (C++20) | adds or subtracts a `year_month_weekday_last` and some number of years or months (function) | cpp std::chrono::operator==(std::chrono::year_month_weekday_last) std::chrono::operator==(std::chrono::year\_month\_weekday\_last) ================================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==(const std::chrono::year_month_weekday_last& x, const std::chrono::year_month_weekday_last& y) noexcept; ``` | | (since C++20) | Compares the two `year_month_weekday_last` values `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.year() == y.year() && x.month() == y.month() && x.weekday() == y.weekday()`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { constexpr auto ymwdl1 {Tuesday[last]/11/2021}; auto ymwdl2 = Tuesday[last]/11/2020; ymwdl2 += months(12); std::cout << std::boolalpha << (ymwdl1 == ymwdl2) << '\n'; } ``` Output: ``` true ``` cpp std::chrono::year_month_weekday_last::ok std::chrono::year\_month\_weekday\_last::ok =========================================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if this object represents a valid date. Since a `year_month_weekday_last` represents the last weekday of a particular month, it is valid as long as the year, month and weekday are valid. ### Return value `year().ok() && month().ok() && weekday().ok()`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto ymwdl {Tuesday[last]/11/2020}; std::cout << (ymwdl.ok()) << ' '; ymwdl = Tuesday[last]/-2/2021; std::cout << (ymwdl.ok()) << ' '; ymwdl += months(0); // Normalize month std::cout << (ymwdl.ok()) << '\n'; } ``` Output: ``` true false true ``` cpp std::chrono::operator<<(std::chrono::year) std::chrono::operator<<(std::chrono::year) ========================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::year& y ); ``` | | (since C++20) | Forms a `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` `s` consisting of the year value stored in `y` formatted as a decimal number, left-padded with `0` to four digits if the result would otherwise be less than four digits. Then, if `!y.ok()`, append `" is not a valid year"` to the formatted string. Inserts that string into `os`. Equivalent to. `return os << (y.ok() ? [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(STATICALLY_WIDEN<CharT>("{:%Y}"), y) : [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(STATICALLY_WIDEN<CharT>("{:%Y} is not a valid year"), y));` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Example ``` #include <chrono> #include <iostream> int main() { constexpr std::chrono::year y1 {2020}, y2 {-020}, y3 {98304}; std::cout << y1 << '\n' << y2 << '\n' << y3 << '\n'; } ``` Possible output: ``` 2020 -0016 -32768 is not a valid year ``` ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::year>](formatter "cpp/chrono/year/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `year` according to the provided format (class template specialization) | cpp std::chrono::year::is_leap std::chrono::year::is\_leap =========================== | | | | | --- | --- | --- | | ``` constexpr bool is_leap() const noexcept; ``` | | (since C++20) | Determines if `*this` represents a leap year in the [proleptic Gregorian calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar "enwiki:Proleptic Gregorian calendar"). `*this` represents a leap year if the stored year value. * is divisible by 4 and not divisible by 100; or * is divisible by 400. ### Return value `true` if `*this` represents a leap year, otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; for (const std::chrono::year y : {2020y, 2021y, 2000y, 3000y}) { if (const int iy{ static_cast<int>(y) }; y.is_leap()) { std::cout << iy << " is a leap year because it is divisible by " << (iy % 400 == 0 ? "400\n" : "4 and not divisible by 100\n"); } else { std::cout << iy << " is not a leap year\n"; } } } ``` Output: ``` 2020 is a leap year because it is divisible by 4 and not divisible by 100 2021 is not a leap year 2000 is a leap year because it is divisible by 400 3000 is not a leap year ```
programming_docs
cpp std::chrono::year::operator int std::chrono::year::operator int =============================== | | | | | --- | --- | --- | | ``` explicit constexpr operator int() const noexcept; ``` | | (since C++20) | Returns the year value stored in `*this`. ### Return value The year value stored in `*this`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { constexpr std::chrono::year y {2020}; std::cout << "The year is: " << int(y) << '\n'; const year_month_day ymd{floor<days>(system_clock::now())}; const std::chrono::year this_year{ymd.year()}; std::cout << "This year is: " << int(this_year) << '\n'; } ``` cpp std::chrono::year::year std::chrono::year::year ======================= | | | | | --- | --- | --- | | ``` year() = default; ``` | (1) | (since C++20) | | ``` explicit constexpr year( int y ) noexcept; ``` | (2) | (since C++20) | Constructs a `year` object. 1) Default constructor leaves the year value uninitialized. 2) If `y` is in the range [-32767, 32767], constructs a `year` object holding the year value `y`. Otherwise the value held is unspecified. ### Example ``` #include <chrono> #include <iostream> int main() { using namespace std::chrono; constexpr int leap_years = [] { int count{}; for (int i{year::min()}; i <= int{year::max()}; ++i) if (year{i}.is_leap()) // uses constructor (2) ++count; return count; } (); static_assert(15891 == leap_years); std::cout << "There are " << leap_years << " leap years in the range [" << int(year::min()) << ", " << int(year::max()) << "].\n"; } ``` Output: ``` There are 15891 leap years in the range [-32767, 32767]. ``` cpp std::chrono::year::max std::chrono::year::max ====================== | | | | | --- | --- | --- | | ``` static constexpr year max() noexcept; ``` | | (since C++20) | Returns the largest possible `year`, that is, `[std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(32767)`. ### Return value `[std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(32767)`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << "The maximum year is: " << (int)std::chrono::year::max() << '\n'; } ``` Output: ``` The maximum year is: 32767 ``` cpp std::chrono::year::min std::chrono::year::min ====================== | | | | | --- | --- | --- | | ``` static constexpr std::chrono::year min() noexcept; ``` | | (since C++20) | Returns the smallest possible `year`, that is, `[std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(-32767)`. ### Return value `[std::chrono::year](http://en.cppreference.com/w/cpp/chrono/year)(-32767)`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << "The minimum year is: " << (int)std::chrono::year::min() << '\n'; } ``` Output: ``` The minimum year is: -32767 ``` cpp std::chrono::year::operator++, std::chrono::year::operator-- std::chrono::year::operator++, std::chrono::year::operator-- ============================================================ | | | | | --- | --- | --- | | ``` constexpr std::chrono::year& operator++() noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::year operator++(int) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::year& operator--() noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::year operator--(int) noexcept; ``` | (4) | (since C++20) | Adds or subtracts 1 from the year value. 1-2) Performs `\*this += [std::chrono::years](http://en.cppreference.com/w/cpp/chrono/duration){1};` 3-4) Performs `\*this -= [std::chrono::years](http://en.cppreference.com/w/cpp/chrono/duration){1};` ### Parameters (none). ### Return value 1,3) a reference to this `year` after modification 2,4) a copy of the `year` made before modification ### Notes If the result would be outside the range [-32767, 32767], the actual stored value is unspecified. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; std::chrono::year y {2020}; std::cout << (++y == std::chrono::year(2021)) << ' '; std::cout << (--y == std::chrono::year(2020)) << '\n'; using namespace std::literals::chrono_literals; y = 32767y; y++; //< unspecified, see Notes std::cout << static_cast<int>(y) << '\n'; } ``` Possible output: ``` true true -32768 ``` ### See also | | | | --- | --- | | [operator+=operator-=](operator_arith "cpp/chrono/year/operator arith") | adds or subtracts a number of years from a `year` (public member function) | | [operator+operator-](operator_arith_2 "cpp/chrono/year/operator arith 2") (C++20) | performs arithmetic on `year`s (function) | cpp std::chrono::operator==,<=>(std::chrono::year) std::chrono::operator==,<=>(std::chrono::year) ============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::year& x, const std::chrono::year& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::year& x, const std::chrono::year& y ) noexcept; ``` | (2) | (since C++20) | Compare the two `std::chrono::year` `x` and `y`. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `int(x) == int(y)` 2) `int(x) <=> int(y)` ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono; constexpr year y1{2020}; constexpr year y2{2021}; std::cout << std::boolalpha << (y1 != y2) << '\n'; static_assert( (2020y < 2023y) && (2020y == 2020y) && (2020y <= 2023y) && (2023y > 2020y) && (2023y != 2020y) && (2023y >= 2020y) ); } ``` Output: ``` true ``` cpp std::chrono::year::ok std::chrono::year::ok ===================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the year value stored in `*this` is in the valid range, i.e., [-32767, 32767]. ### Return value `true` if the year value stored in `*this` is in the range [-32767, 32767]. Otherwise `false`. ### Possible implementation See the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/919858077f4b768c8472f29b977edf0aa6e0f1e5/libstdc%2B%2B-v3/include/std/chrono#L1606), [libc++](https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/include/chrono#L1832), and Howard Hinnant's [date.h](https://github.com/HowardHinnant/date/blob/0b72599bd43f72d8935e507e25e4f0063f9bb34e/include/date/date.h#L1630). | | | --- | | ``` class Year { short year_; // exposition-only public: bool ok() const noexcept { return year_ != std::numeric_limits<short>::min(); } /*...*/ }; ``` | ### Example ``` #include <iostream> #include <iomanip> #include <chrono> int main() { for (const int i : {2020, 0x8000, 0x8001, 0xFFFF, 0x18000}) { const std::chrono::year y{i}; std::cout << std::boolalpha << "input year: " << std::setw(6) << i << " │ internal value: " << std::setw(7) << static_cast<int>(y) << " │ ok(): " << y.ok() << '\n'; } } ``` Possible output: ``` input year: 2020 │ internal value: 2020 │ ok(): true input year: 32768 │ internal value: -32768 │ ok(): false input year: 32769 │ internal value: -32767 │ ok(): true input year: 65535 │ internal value: -1 │ ok(): true input year: 98304 │ internal value: -32768 │ ok(): false ``` cpp std::chrono::operator<<(std::chrono::month_weekday_last) std::chrono::operator<<(std::chrono::month\_weekday\_last) ========================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::month_weekday_last& mwdl ); ``` | | (since C++20) | Outputs a textual representation of `mwdl` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}/{:L}"), mwdl.month(), mwdl.weekday\_last());` where `STATICALLY_WIDEN<CharT>("{:L}/{:L}")` is `"{:L}/{:L}"` if `CharT` is `char`, and `L"{:L}/{:L}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::month>](../month/formatter "cpp/chrono/month/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month` according to the provided format (class template specialization) | cpp std::chrono::month_weekday_last::month_weekday_last std::chrono::month\_weekday\_last::month\_weekday\_last ======================================================= | | | | | --- | --- | --- | | ``` constexpr month_weekday_last( const std::chrono::month& m, const std::chrono::weekday_last& wdl ) noexcept; ``` | | (since C++20) | Constructs a `month_weekday_last` object that stores the [`month`](../month "cpp/chrono/month") `m` and the [`weekday_last`](../weekday_last "cpp/chrono/weekday last") `wdl`. ### Notes A more convenient way to construct a `month_weekday_last` is with `operator/`, e.g., `[std::chrono::April](http://en.cppreference.com/w/cpp/chrono/month)/[std::chrono::Sunday](http://en.cppreference.com/w/cpp/chrono/weekday)[[std::chrono::last](http://en.cppreference.com/w/cpp/chrono/last_spec)]`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::month_weekday_last::month, std::chrono::month_weekday_last::weekday_last std::chrono::month\_weekday\_last::month, std::chrono::month\_weekday\_last::weekday\_last ========================================================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::month month() const noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::weekday_last weekday_last() const noexcept; ``` | (2) | (since C++20) | Retrieves a copy of the [`month`](../month "cpp/chrono/month") and [`weekday_last`](../weekday_last "cpp/chrono/weekday last") objects stored in `*this`. ### Return value 1) a copy of the `std::chrono::month` object stored in `*this` 2) a copy of the `std::chrono::weekday_last` object stored in `*this` ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto mwdl {March/Friday[last]}; // Last Friday in a March auto ywdl {year(2024)/mwdl}; std::cout << (year_month_day{ywdl} == year_month_day{March/29/2024}) << ' '; // Last Friday of the next month, in 2024 mwdl = {(mwdl.month() + months(1))/mwdl.weekday_last()}; ywdl = {year(2024)/mwdl}; std::cout << (year_month_day{ywdl} == year_month_day{April/26/2024}) << '\n'; } ``` Output: ``` true true ``` cpp std::chrono::operator==(std::chrono::month_weekday_last) std::chrono::operator==(std::chrono::month\_weekday\_last) ========================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::month_weekday_last& x, const std::chrono::month_weekday_last& y ) noexcept; ``` | | (since C++20) | Compares the two `month_weekday_last` values `x` and `y`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value `x.month() == y.month() && x.weekday_last() == y.weekday_last()`. ### Example ``` #include <chrono> int main() { constexpr std::chrono::month_weekday_last mwdl1 { std::chrono::March/std::chrono::Friday[std::chrono::last] }; constexpr std::chrono::month_weekday_last mwdl2 { std::chrono::March, std::chrono::Friday[std::chrono::last] }; static_assert(mwdl1 == mwdl2); } ``` cpp std::chrono::month_weekday_last::ok std::chrono::month\_weekday\_last::ok ===================================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the contained [`month`](../month "cpp/chrono/month") and [`weekday_last`](../weekday_last "cpp/chrono/weekday last") objects are valid. ### Return value `month().ok() && weekday_last().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto mwdl {std::chrono::March/std::chrono::Wednesday[std::chrono::last]}; std::cout << (mwdl.ok()) << ' '; mwdl = {std::chrono::month(3)/std::chrono::weekday(42)[std::chrono::last]}; std::cout << (mwdl.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::utc_clock::to_sys std::chrono::utc\_clock::to\_sys ================================ | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::sys_time<std::common_type_t<Duration, std::chrono::seconds>> to_sys( const std::chrono::utc_time<Duration>& t ); ``` | | (since C++20) | Converts a `utc_time` `t` to a `sys_time` representing the same point in time (if possible). If `t` represents a time point during a leap second insertion, the last representable value of `sys_time` prior to the insertion of the leap second is returned. In all other cases, `utc_clock::from_sys(utc_clock::to_sys(t)) == t`. ### Return value A `sys_time` representing the same point in time as `t`, or the last representable value prior to the insertion of the leap second if `t` represents a time point during a leap second insertion. ### See also | | | | --- | --- | | [from\_sys](from_sys "cpp/chrono/utc clock/from sys") [static] | converts `sys_time` to `utc_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::operator<<(std::chrono::utc_time) std::chrono::operator<<(std::chrono::utc\_time) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Duration > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::utc_time<Duration>& tp ); ``` | | (since C++20) | Outputs `tp` into the stream `os`, as if by `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY-WIDEN("{:L%F %T}"), tp)`, where `STATICALLY_WIDEN<CharT>("{:L%F %T}")` is `"{:L%F %T}"` if `CharT` is `char`, and `L"{:L%F %T}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::utc\_time>](formatter "cpp/chrono/utc clock/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `utc_time` according to the provided format (class template specialization) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | cpp std::chrono::utc_clock::now std::chrono::utc\_clock::now ============================ | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::utc_clock> now(); ``` | | (since C++20) | Returns a time point representing the current point in time. The result is calculated as if by `[std::chrono::utc\_clock::from\_sys](http://en.cppreference.com/w/cpp/chrono/utc_clock/from_sys)([std::chrono::system\_clock::now](http://en.cppreference.com/w/cpp/chrono/system_clock/now)())`. Implementations may use a more accurate value of UTC time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::utc_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::utc_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::leap_second_info std::chrono::leap\_second\_info =============================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` struct leap_second_info { bool is_leap_second; std::chrono::seconds elapsed; }; ``` | | (since C++20) | A `leap_second_info` indicates whether a UTC time is during a positive leap second insertion and the total number of leap seconds between 1 January 1970 and the UTC time. `leap_second_info` has no base classes or members other than `is_leap_second`, `elapsed`, and implicitly declared special member functions. ### Member objects | | | | --- | --- | | is\_leap\_second | whether the UTC time is during a positive leap second insertion (public member object) | | elapsed | the sum of leap seconds between 1 January 1970 and the UTC time (public member object) | ### Notes `leap_second_info` is typically obtained from `[std::chrono::get\_leap\_second\_info](get_leap_second_info "cpp/chrono/utc clock/get leap second info")`. ### See also | | | | --- | --- | | [leap\_second](../leap_second "cpp/chrono/leap second") (C++20) | contains information about a leap second insertion (class) |
programming_docs
cpp std::chrono::get_leap_second_info std::chrono::get\_leap\_second\_info ==================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class Duration > std::chrono::leap_second_info get_leap_second_info( const std::chrono::utc_time<Duration>& ut ); ``` | | (since C++20) | Obtains a `[std::chrono::leap\_second\_info](leap_second_info "cpp/chrono/utc clock/leap second info")` whose `is_leap_second` and `elapsed` indicate whether `ut` is during a positive leap second insertion and the sum of leap seconds between 1 January 1970 and `ut`, respectively. ### Parameters | | | | | --- | --- | --- | | ut | - | UTC time to examine | ### Return value A `leap_second_info` value specified above. ### Exceptions May throw implementation-defined exceptions. ### See also | | | | --- | --- | | [leap\_second\_info](leap_second_info "cpp/chrono/utc clock/leap second info") (C++20) | leap second insertion information (class) | | [leap\_second](../leap_second "cpp/chrono/leap second") (C++20) | contains information about a leap second insertion (class) | cpp std::chrono::utc_clock::from_sys std::chrono::utc\_clock::from\_sys ================================== | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::utc_time<std::common_type_t<Duration, std::chrono::seconds>> from_sys( const std::chrono::sys_time<Duration>& t ); ``` | | (since C++20) | Converts a `sys_time` `t` to a `utc_time` `u` that represents the same point in time. `u.time_since_epoch() - t.time_since_epoch()` is equal to the number of leap seconds that was inserted between `t` and 1 January 1970. If `t` is the exact date of a leap second insertion, that leap second is counted as inserted. ### Return value A `utc_time` representing the same point in time as `t`. ### See also | | | | --- | --- | | [to\_sys](to_sys "cpp/chrono/utc clock/to sys") [static] | converts `utc_time` to `sys_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::steady_clock::now std::chrono::steady\_clock::now =============================== | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::steady_clock> now() noexcept; ``` | | (since C++11) | Returns a time point representing the current point in time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::steady_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::operator<<(std::chrono::gps_time) std::chrono::operator<<(std::chrono::gps\_time) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Duration > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::gps_time<Duration>& tp ); ``` | | (since C++20) | Outputs `tp` into the stream `os`, as if by `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY-WIDEN("{:L%F %T}"), tp)`, where `STATICALLY_WIDEN<CharT>("{:L%F %T}")` is `"{:L%F %T}"` if `CharT` is `char`, and `L"{:L%F %T}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::gps\_time>](formatter "cpp/chrono/gps clock/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `gps_time` according to the provided format (class template specialization) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | cpp std::chrono::gps_clock::now std::chrono::gps\_clock::now ============================ | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::gps_clock> now(); ``` | | (since C++20) | Returns a time point representing the current point in time. The result is calculated as if by `[std::chrono::gps\_clock::from\_utc](http://en.cppreference.com/w/cpp/chrono/gps_clock/from_utc)([std::chrono::utc\_clock::now](http://en.cppreference.com/w/cpp/chrono/utc_clock/now)())`. Implementations may use a more accurate value of GPS time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::gps_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::gps_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::gps_clock::to_utc std::chrono::gps\_clock::to\_utc ================================ | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::utc_time<std::common_type_t<Duration, std::chrono::seconds>> to_utc( const std::chrono::gps_time<Duration>& t ) noexcept; ``` | | (since C++20) | Converts the `gps_time` `t` to a `utc_time` representing the same point in time. ### Return value A `std::chrono::utc_time` representing the same point in time as `t`, computed as if by constructing a value of the return type from `t.time_since_epoch()` and adding `315964809s`. (315964809 is the number of seconds between the epochs of the two clocks: 1980-01-06 00:00:00 UTC for `gps_clock` and 1970-01-01 00:00:00 UTC for `utc_clock`.). ### Example ### See also | | | | --- | --- | | [from\_utc](from_utc "cpp/chrono/gps clock/from utc") [static] | converts a `utc_time` to `gps_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::gps_clock::from_utc std::chrono::gps\_clock::from\_utc ================================== | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::gps_time<std::common_type_t<Duration, std::chrono::seconds>> from_utc( const std::chrono::utc_time<Duration>& ) noexcept; ``` | | (since C++20) | Converts the `utc_time` `t` to a `gps_time` representing the same point in time. ### Return value A `std::chrono::gps_time` representing the same point in time as `t`, computed as if by constructing a value of the return type from `t.time_since_epoch()` and subtracting `315964809s`. (315964809 is the number of seconds between the epochs of the two clocks: 1980-01-06 00:00:00 UTC for `gps_clock` and 1970-01-01 00:00:00 UTC for `utc_clock`.). ### Example ### See also | | | | --- | --- | | [to\_utc](to_utc "cpp/chrono/gps clock/to utc") [static] | converts a `gps_time` to `utc_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::operator<<(std::chrono::tai_time) std::chrono::operator<<(std::chrono::tai\_time) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Duration > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::tai_time<Duration>& tp ); ``` | | (since C++20) | Outputs `tp` into the stream `os`, as if by `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY-WIDEN("{:L%F %T}"), tp)`, where `STATICALLY_WIDEN<CharT>("{:L%F %T}")` is `"{:L%F %T}"` if `CharT` is `char`, and `L"{:L%F %T}"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [std::formatter<std::chrono::tai\_time>](formatter "cpp/chrono/tai clock/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `tai_time` according to the provided format (class template specialization) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | cpp std::chrono::tai_clock::now std::chrono::tai\_clock::now ============================ | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::tai_clock> now(); ``` | | (since C++20) | Returns a time point representing the current point in time. The result is calculated as if by `[std::chrono::tai\_clock::from\_utc](http://en.cppreference.com/w/cpp/chrono/tai_clock/from_utc)([std::chrono::utc\_clock::now](http://en.cppreference.com/w/cpp/chrono/utc_clock/now)())`. Implementations may use a more accurate value of TAI time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::tai_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::tai_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::tai_clock::to_utc std::chrono::tai\_clock::to\_utc ================================ | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::utc_time<std::common_type_t<Duration, std::chrono::seconds>> to_utc( const std::chrono::tai_time<Duration>& t ) noexcept; ``` | | (since C++20) | Converts the `tai_time` `t` to a `utc_time` representing the same point in time. ### Return value A `std::chrono::utc_time` representing the same point in time as `t`, computed as if by constructing a value of the return type from `t.time_since_epoch()` and subtracting `378691210s`. (378691210 is the number of seconds between the epochs of the two clocks: 1958-01-01 00:00:00 TAI and 1970-01-01 00:00:00 UTC.). ### See also | | | | --- | --- | | [from\_utc](from_utc "cpp/chrono/tai clock/from utc") [static] | converts `utc_time` to `tai_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::tai_clock::from_utc std::chrono::tai\_clock::from\_utc ================================== | | | | | --- | --- | --- | | ``` template< class Duration > static std::chrono::tai_time<std::common_type_t<Duration, std::chrono::seconds>> from_utc( const std::chrono::utc_time<Duration>& ) noexcept; ``` | | (since C++20) | Converts the `utc_time` `t` to a `tai_time` representing the same point in time. ### Return value A `std::chrono::tai_time` representing the same point in time as `t`, computed as if by constructing a value of the return type from `t.time_since_epoch()` and adding `378691210s`. (378691210 is the number of seconds between the epochs of the two clocks: 1958-01-01 00:00:00 TAI and 1970-01-01 00:00:00 UTC.). ### See also | | | | --- | --- | | [to\_utc](to_utc "cpp/chrono/tai clock/to utc") [static] | converts `tai_time` to `utc_time` (public static member function) | | [clock\_cast](../clock_cast "cpp/chrono/clock cast") (C++20) | convert time points of one clock to another (function template) | cpp std::chrono::operator<<(std::chrono::day) std::chrono::operator<<(std::chrono::day) ========================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::day& d ); ``` | | (since C++20) | Forms a `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` `s` consisting of the day value stored in `d` formatted as a decimal number, with a leading zero if the result would otherwise be a single decimal digit. Then, if `!d.ok()`, append `" is not a valid day"` to the formatted string. Inserts that string into `os`. Equivalent to. `return os << (d.ok() ? [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(STATICALLY_WIDEN<CharT>("{:%d}"), d) : [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(STATICALLY_WIDEN<CharT>("{:%d} is not a valid day"), d));` where `STATICALLY_WIDEN<CharT>("...")` is `"..."` if `CharT` is `char`, and `L"..."` if `CharT` is `wchar_t`. ### Return value `os`. ### Example ``` #include <chrono> #include <iostream> int main() { constexpr std::chrono::day d1 {31}, d2 {7}, d3 {42}, d4 {}; std::cout << d1 << '\n' << d2 << '\n' << d3 << '\n' << d4 << '\n'; } ``` Possible output: ``` 31 07 42 is not a valid day 00 is not a valid day ``` ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::day>](formatter "cpp/chrono/day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `day` according to the provided format (class template specialization) | cpp std::chrono::day::day std::chrono::day::day ===================== | | | | | --- | --- | --- | | ``` day() = default; ``` | (1) | (since C++20) | | ``` explicit constexpr day( unsigned d ) noexcept; ``` | (2) | (since C++20) | Constructs a `day` object. 1) Default constructor leaves the day value uninitialized. 2) If `d <= 255`, constructs a `day` object holding the day value `d`. Otherwise the value held is unspecified. cpp std::chrono::day::operator unsigned std::chrono::day::operator unsigned =================================== | | | | | --- | --- | --- | | ``` explicit constexpr operator unsigned() const noexcept; ``` | | (since C++20) | Returns the day value stored in `*this`. ### Return value The day value stored in `*this`. ### Example ``` #include <iostream> #include <chrono> int main() { constexpr std::chrono::day d {15}; constexpr unsigned day = static_cast<unsigned>(d); std::cout << "The day is: " << day << '\n'; } ``` Output: ``` The day is: 15 ``` cpp std::chrono::day::operator++, std::chrono::day::operator-- std::chrono::day::operator++, std::chrono::day::operator-- ========================================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::day& operator++() noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::chrono::day operator++( int ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::chrono::day& operator--() noexcept; ``` | (3) | (since C++20) | | ``` constexpr std::chrono::day operator--( int ) noexcept; ``` | (4) | (since C++20) | Adds or subtracts 1 from the day value. 1-2) Performs `\*this += [std::chrono::days](http://en.cppreference.com/w/cpp/chrono/duration){1};` 3-4) Performs `\*this -= [std::chrono::days](http://en.cppreference.com/w/cpp/chrono/duration){1};` ### Parameters (none). ### Return value 1,3) a reference to this `day` after modification 2,4) a copy of the `day` made before modification ### Notes If the result would be outside the range [0, 255], the actual stored value is unspecified. ### Example ``` #include <cassert> #include <chrono> int main() { std::chrono::day d {15}; ++d; assert(d == std::chrono::day(16)); --d; assert(d == std::chrono::day(15)); } ``` ### See also | | | | --- | --- | | [operator+=operator-=](operator_arith "cpp/chrono/day/operator arith") | adds or subtracts a number of days (public member function) | | [operator+operator-](operator_arith_2 "cpp/chrono/day/operator arith 2") (C++20) | adds or subtracts a number of days and a `day`, or find the difference between two `day`s (function) |
programming_docs
cpp std::chrono::operator==,<=>(std::chrono::day) std::chrono::operator==,<=>(std::chrono::day) ============================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::day& x, const std::chrono::day& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::day& x, const std::chrono::day& y ) noexcept; ``` | (2) | (since C++20) | Compare the two `std::chrono::day` `x` and `y`. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. ### Return value 1) `unsigned(x) == unsigned(y)` 2) `unsigned(x) <=> unsigned(y)` ### Example ``` #include <iostream> #include <chrono> int main() { std::chrono::day d1{15}; std::chrono::day d2{20}; d1 == d2 ? std::cout << "d1 and d2 are equal\n" : std::cout << "d1 and d2 are not equal\n"; using namespace std::literals::chrono_literals; std::cout << std::boolalpha << (6d < 9d) << ' ' << (6d == 6d) << ' ' << (6d <= 9d) << ' ' << (9d > 6d) << ' ' << (9d != 6d) << ' ' << (9d >= 6d) << '\n'; } ``` Output: ``` d1 and d2 are not equal true true true true true true ``` cpp std::chrono::day::ok std::chrono::day::ok ==================== | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the day value stored in `*this` is in the valid range, i.e., [1, 31]. ### Return value `true` if the day value stored in `*this` is in the range [1, 31]. Otherwise `false`. ### Example ``` #include <iostream> #include <chrono> int main() { std::chrono::day d1{15}; std::cout << static_cast<unsigned>(d1); if (d1.ok()) { std::cout << " is a valid day.\n"; } else { std::cout << " is an invalid day!\n"; } std::chrono::day d2{35}; std::cout << static_cast<unsigned>(d2) << (d2.ok() ? " is a valid day.\n" : " is an invalid day!\n"); } ``` Output: ``` 15 is a valid day. 35 is an invalid day! ``` ### See also | | | | --- | --- | | [operator unsigned](operator_unsigned "cpp/chrono/day/operator unsigned") | retrieves the stored day value (public member function) | cpp std::chrono::duration<Rep,Period>::operator++, std::chrono::duration<Rep,Period>::operator-- std::chrono::duration<Rep,Period>::operator++, std::chrono::duration<Rep,Period>::operator-- ============================================================================================ | | | | | --- | --- | --- | | | (1) | | | ``` duration& operator++(); ``` | (until C++17) | | ``` constexpr duration& operator++(); ``` | (since C++17) | | | (2) | | | ``` duration operator++(int); ``` | (until C++17) | | ``` constexpr duration operator++(int); ``` | (since C++17) | | | (3) | | | ``` duration& operator--(); ``` | (until C++17) | | ``` constexpr duration& operator--(); ``` | (since C++17) | | | (4) | | | ``` duration operator--(int); ``` | (until C++17) | | ``` constexpr duration operator--(int); ``` | (since C++17) | Increments or decrements the number of ticks for this duration. If `rep_` is a member variable holding the number of ticks in a duration object, 1) Equivalent to `++rep_; return *this;` 2) Equivalent to `return duration(rep_++)` 3) Equivalent to `--rep_; return *this;` 4) Equivalent to `return duration(rep_--);` ### Parameters (none). ### Return value 1,3) a reference to this duration after modification 2,4) a copy of the duration made before modification ### Example ``` #include <chrono> #include <iostream> int main() { std::chrono::hours h(1); std::chrono::minutes m = ++h; m--; std::cout << m.count() << " minutes\n"; } ``` Output: ``` 119 minutes ``` ### See also | | | | --- | --- | | [operator+=operator-=operator\*=operator/=operator%=](operator_arith3 "cpp/chrono/duration/operator arith3") | implements compound assignment between two durations (public member function) | | [operator+operator-operator\*operator/operator%](operator_arith4 "cpp/chrono/duration/operator arith4") (C++11) | implements arithmetic operations with durations as arguments (function template) | cpp std::chrono::duration<Rep,Period>::duration std::chrono::duration<Rep,Period>::duration =========================================== | | | | | --- | --- | --- | | ``` constexpr duration() = default; ``` | (1) | (since C++11) | | ``` duration( const duration& ) = default; ``` | (2) | (since C++11) | | ``` template< class Rep2 > constexpr explicit duration( const Rep2& r ); ``` | (3) | (since C++11) | | ``` template< class Rep2, class Period2 > constexpr duration( const duration<Rep2,Period2>& d ); ``` | (4) | (since C++11) | Constructs a new `duration` from one of several optional data sources. 1) The default constructor is defaulted. 2) The copy constructor is defaulted (makes a bitwise copy of the tick count). 3) Constructs a duration with `r` ticks. Note that this constructor only participates in overload resolution if `const Rep2&` (the argument type) is implicitly convertible to `rep` (the type of this duration's ticks) and * `[std::chrono::treat\_as\_floating\_point](http://en.cppreference.com/w/cpp/chrono/treat_as_floating_point)<rep>::value` is true, or * `[std::chrono::treat\_as\_floating\_point](http://en.cppreference.com/w/cpp/chrono/treat_as_floating_point)<Rep2>::value` is false. (that is, a duration with an integer tick count cannot be constructed from a floating-point value, but a duration with a floating-point tick count can be constructed from an integer value) 4) Constructs a duration by converting `d` to an appropriate period and tick count, as if by `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<duration>(d).count()`. In order to prevent truncation during conversion, this constructor only participates in overload resolution if computation of the conversion factor (by `[std::ratio\_divide](http://en.cppreference.com/w/cpp/numeric/ratio/ratio_divide)<Period2, Period>`) does not overflow and: * `[std::chrono::treat\_as\_floating\_point](http://en.cppreference.com/w/cpp/chrono/treat_as_floating_point)<rep>::value == true` or both: * `[std::ratio\_divide](http://en.cppreference.com/w/cpp/numeric/ratio/ratio_divide)<Period2, period>::den == 1`, and * `[std::chrono::treat\_as\_floating\_point](http://en.cppreference.com/w/cpp/chrono/treat_as_floating_point)<Rep2>::value == false`. (that is, either the duration uses floating-point ticks, or `Period2` is exactly divisible by period) ### Parameters | | | | | --- | --- | --- | | r | - | a tick count | | d | - | a duration to copy from | ### Example The following code shows several examples (both valid and invalid) of how to construct durations: ``` #include <chrono> int main() { std::chrono::hours h(1); // one hour std::chrono::milliseconds ms{3}; // 3 milliseconds std::chrono::duration<int, std::kilo> ks(3); // 3000 seconds // error: treat_as_floating_point<int>::value == false, // This duration allows whole tick counts only // std::chrono::duration<int, std::kilo> d3(3.5); // 30Hz clock using fractional ticks std::chrono::duration<double, std::ratio<1, 30>> hz30(3.5); // 3000 microseconds constructed from 3 milliseconds std::chrono::microseconds us = ms; // error: 1/1000000 is not divisible by 1/1000 // std::chrono::milliseconds ms2 = us std::chrono::duration<double, std::milli> ms2 = us; // 3.0 milliseconds } ``` ### 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 3050](https://cplusplus.github.io/LWG/issue3050) | C++11 | convertibility constraint used non-const xvalue | use const lvalues instead | ### See also | | | | --- | --- | | [operator=](operator= "cpp/chrono/duration/operator=") | assigns the contents (public member function) | cpp std::chrono::operator<< (std::chrono::duration) std::chrono::operator<< (std::chrono::duration) =============================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits, class Rep, class Period> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::chrono::duration<Rep, Period>& d); ``` | | (since C++20) | Inserts a textual representation of `d` into `os`. Behaves as if it was implemented as. ``` std::basic_ostringstream<CharT, Traits> s; s.flags(os.flags()); s.imbue(os.getloc()); s.precision(os.precision()); s << d.count() << units_suffix; // see below return os << s.str(); ``` In other words, the stream flags, locale, and precision are determined by the stream, but any padding are determined using the entire output string. The `units_suffix` is determined based on `Period::type` according to the following table. | `Period::type` | Suffix | | --- | --- | | `std::atto` | `as` | | `[std::femto](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `fs` | | `[std::pico](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `ps` | | `[std::nano](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `ns` | | `[std::micro](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `µs` (U+00B5) or `us`, it is implementation-defined which one is used | | `[std::milli](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `ms` | | `[std::centi](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `cs` | | `[std::deci](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `ds` | | [`std::ratio<1>`](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio") | `s` | | `[std::deca](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `das` | | `[std::hecto](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `hs` | | `[std::kilo](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `ks` | | `[std::mega](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `Ms` | | `[std::giga](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `Gs` | | `[std::tera](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `Ts` | | `[std::peta](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `Ps` | | `[std::exa](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | `Es` | | [`std::ratio<60>`](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio") | `min` | | [`std::ratio<3600>`](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio") | `h` | | [`std::ratio<86400>`](../../numeric/ratio/ratio "cpp/numeric/ratio/ratio") | `d` | | None of the above, and `Period::type::den == 1` | `[*num*]s` | | None of the above | `[*num*/*den*]s` | For the last two rows of the table, `*num*` and `*den*` in the suffix are `Period::type::num` and `Period::type::den` formatted as a decimal number with no leading zeroes, respectively. ### Return value A reference to the stream, i.e., `os`. ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::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) | | [operator<<operator>>](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function 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::chrono::round(std::chrono::duration) std::chrono::round(std::chrono::duration) ========================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Rep, class Period> constexpr ToDuration round( const std::chrono::duration<Rep, Period>& d ); ``` | | (since C++17) | Returns the value `t` representable in `ToDuration` that is the closest to `d`. If there are two such values, returns the even value (that is, the value `t` such that `t % 2 == 0`). The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")` and `std::chrono::treat_as_floating_point_v<typename ToDuration::rep>` is `false`. ### Parameters | | | | | --- | --- | --- | | d | - | duration to convert | ### Return value `d` rounded to the nearest duration of type `ToDuration`, rounding to even in halfway cases. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Rep, class Period, class = std::enable_if_t<detail::is_duration_v<To> && !std::chrono::treat_as_floating_point_v<typename To::rep>>> constexpr To round(const std::chrono::duration<Rep, Period>& d) { To t0 = std::chrono::floor<To>(d); To t1 = t0 + To{1}; auto diff0 = d - t0; auto diff1 = t1 - d; if (diff0 == diff1) { if (t0.count() & 1) return t1; return t0; } else if (diff0 < diff1) { return t0; } return t1; } ``` | ### Example ``` #include <iostream> #include <iomanip> #include <chrono> int main() { using namespace std::chrono_literals; using Sec = std::chrono::seconds; for (std::cout << "Duration\tFloor\tRound\tCeil\n" "(ms)\t\t(sec)\t(sec)\t(sec)\n"; auto const d: { +4999ms, +5000ms, +5001ms, +5499ms, +5500ms, +5999ms, -4999ms, -5000ms, -5001ms, -5499ms, -5500ms, -5999ms, }) { std::cout << std::showpos << d.count() << "\t\t" << std::chrono::floor<Sec>(d).count() << '\t' << std::chrono::round<Sec>(d).count() << '\t' << std::chrono::ceil <Sec>(d).count() << '\n'; } } ``` Output: ``` Duration Floor Round Ceil (ms) (sec) (sec) (sec) +4999 +4 +5 +5 +5000 +5 +5 +5 +5001 +5 +5 +6 +5499 +5 +5 +6 +5500 +5 +6 +6 +5999 +5 +6 +6 -4999 -5 -5 -4 -5000 -5 -5 -5 -5001 -6 -5 -5 -5499 -6 -5 -5 -5500 -6 -6 -5 -5999 -6 -6 -5 ``` ### See also | | | | --- | --- | | [duration\_cast](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)](floor "cpp/chrono/duration/floor") (C++17) | converts a duration to another, rounding down (function template) | | [ceil(std::chrono::duration)](ceil "cpp/chrono/duration/ceil") (C++17) | converts a duration to another, rounding up (function template) | | [round(std::chrono::time\_point)](../time_point/round "cpp/chrono/time point/round") (C++17) | converts a time\_point to another, rounding to nearest, ties to even (function template) | | [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](../../numeric/math/round "cpp/numeric/math/round") (C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) | cpp std::chrono::duration<Rep,Period>::operator+=, -=, *=, /=, %= std::chrono::duration<Rep,Period>::operator+=, -=, \*=, /=, %= ============================================================== | | | | | --- | --- | --- | | | (1) | | | ``` duration& operator+=(const duration& d); ``` | (until C++17) | | ``` constexpr duration& operator+=(const duration& d); ``` | (since C++17) | | | (2) | | | ``` duration& operator-=(const duration& d); ``` | (until C++17) | | ``` constexpr duration& operator-=(const duration& d); ``` | (since C++17) | | | (3) | | | ``` duration& operator*=(const rep& rhs); ``` | (until C++17) | | ``` constexpr duration& operator*=(const rep& rhs); ``` | (since C++17) | | | (4) | | | ``` duration& operator/=(const rep& rhs); ``` | (until C++17) | | ``` constexpr duration& operator/=(const rep& rhs); ``` | (since C++17) | | | (5) | | | ``` duration& operator%=(const rep& rhs); ``` | (until C++17) | | ``` constexpr duration& operator%=(const rep& rhs); ``` | (since C++17) | | | (6) | | | ``` duration& operator%=(const duration& rhs); ``` | (until C++17) | | ``` constexpr duration& operator%=(const duration& rhs); ``` | (since C++17) | Performs compound assignments between two durations with the same period or between a duration and a tick count value. If `rep_` is the member variable holding the number of ticks in this duration object, 1) Equivalent to `rep_ += d.count(); return *this;` 2) Equivalent to `rep_ -= d.count(); return *this;` 3) Equivalent to `rep_ *= rhs; return *this;` 4) Equivalent to `rep_ /= rhs; return *this;` 5) Equivalent to `rep_ %= rhs; return *this;` 6) Equivalent to `rep_ %= d.count(); return *this;` ### Parameters | | | | | --- | --- | --- | | d | - | duration on the right-hand side of the operator | | rhs | - | number of ticks on the right-hand side of the operator | ### Return value A reference to this duration after modification. ### Example ``` #include <chrono> #include <iostream> int main() { std::chrono::minutes m(11); m *= 2; m += std::chrono::hours(10); // hours implicitly convert to minutes std::cout << m.count() << " minutes equals " << std::chrono::duration_cast<std::chrono::hours>(m).count() << " hours and "; m %= std::chrono::hours(1); std::cout << m.count() << " minutes\n"; } ``` Output: ``` 622 minutes equals 10 hours and 22 minutes ``` ### See also | | | | --- | --- | | [operator++operator++(int)operator--operator--(int)](operator_arith2 "cpp/chrono/duration/operator arith2") | increments or decrements the tick count (public member function) | | [operator+operator-operator\*operator/operator%](operator_arith4 "cpp/chrono/duration/operator arith4") (C++11) | implements arithmetic operations with durations as arguments (function template) | cpp std::chrono::from_stream (std::chrono::duration) std::chrono::from\_stream (std::chrono::duration) ================================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Rep, class Period, class Alloc = std::allocator<CharT> > std::basic_istream<CharT, Traits>& from_stream( std::basic_istream<CharT, Traits>& is, const CharT* fmt, std::chrono::duration<Rep, Period>& d, std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr, std::chrono::minutes* offset = nullptr ); ``` | | (since C++20) | Attempts to parse the input stream `is` into the `[std::chrono::duration](../duration "cpp/chrono/duration")` `d`, interpreted as the time of day since midnight, according to the format string `fmt`. Behaves as an [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that it has an unspecified effect on `is.gcount()`. After constructing and checking the sentry object, attempts to parse the input stream `is` into `d` according to the format string `fmt`. If the parse fails to decode a valid `duration`, `is.setstate([std::ios\_base::failbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate))` is called and `d` is not modified. If the format specifier `%Z` is used and successfully parsed, the parsed value is assigned to `*abbrev` if `abbrev` is not null. If the format specifier `%z` or a modified variant is used and successfully parsed, the parsed value is assigned to `*offset` if `offset` is not null. ### Parameters | | | | | --- | --- | --- | | is | - | an input stream | | fmt | - | a format string (see below) | | d | - | `[std::chrono::duration](../duration "cpp/chrono/duration")` object to hold the parse result | | abbrev | - | if not null, pointer to an object that will hold the time zone abbreviation or name corresponding to the `%Z` specifier | | offset | - | if not null, pointer to an object that will hold the offset from UTC corresponding to the `%z` specifier | ### Format string The format string consists of zero or more conversion specifiers and ordinary characters. Each ordinary character, excluding whitespace characters and the terminating null character, matches one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. Each whitespace character matches zero or more whitespace characters in the input stream. Each unmodified conversion specifier begins with a `%` character followed by a character that determines the behavior of the specifier. Some conversion specifiers have a modified form in which an `E` or `O` modifier character is inserted after the `%` character. Some conversion specifiers have a modified form in which a width parameter given as a positive decimal integer (shown as *`N`* below) is inserted after the `%` character. Each conversion specifier causes the matched characters to be interpreted as parts of date and time types according to the table below. A character sequence in the format string that begins with a `%` but does not match one of the conversion specifiers below is interpreted as ordinary characters. If `from_stream` fails to parse everything specified by the format string, or if insufficient information is parsed to specify a complete result, or if parsing discloses contradictory information, `is.setstate([std::ios\_base::failbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate))` is called. The following conversion specifiers are available: | Conversion specifier | Explanation | | --- | --- | | `%%` | Matches a literal `%` character. | | `%n` | Matches one whitespace character. | | `%t` | Matches zero or one whitespace character. | | Year | | `%C` `%*N*C` `%EC` | Parses the century as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%EC` interprets the locale's alternative representation of the century. | | `%y` `%*N*y` `%Ey` `%Oy` | Parses the last two decimal digits of the year. If the century is not otherwise specified (e.g. with %C), values in the range [69, 99] are presumed to refer to the years 1969 to 1999, and values in the range [00, 68] are presumed to refer to the years 2000 to 2068. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified commands `%Ey` and `%Oy` interpret the locale's alternative representation. | | `%Y` `%*N*Y` `%EY` | Parses the year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 4. Leading zeroes are permitted but not required. The modified command `%EY` interprets the locale's alternative representation. | | Month | | `%b``%B``%h` | Parses the locale's full or abbreviated case-insensitive month name. | | `%m` `%*N*m``%Om` | Parses the month as a decimal number (January is `1`). The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%Om` interprets the locale's alternative representation. | | Day | | `%d``%*N*d``%Od``%e` `%*N*e``%Oe` | Parses the day of month as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified commands `%Od` and `%Oe` interpret the locale's alternative representation. | | Day of the week | | `%a``%A` | Parses the locale's full or abbreviated case-insensitive weekday name. | | `%u``%*N*u` | Parses the ISO weekday as a decimal number (1-7), where Monday is `1`. The width *N* specifies the maximum number of characters to read. The default width is 1. Leading zeroes are permitted but not required. | | `%w``%*N*w``%Ow` | Parses the weekday as a decimal number (0-6), where Sunday is `0`. The width *N* specifies the maximum number of characters to read. The default width is 1. Leading zeroes are permitted but not required. The modified command `%Ow` interprets the locale's alternative representation. | | ISO 8601 week-based year | | In ISO 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 | | `%g``%*N*g` | Parses the last two decimal digits of the ISO 8601 week-based year. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. | | `%G``%*N*G` | Parses the ISO 8601 week-based year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 4. Leading zeroes are permitted but not required. | | `%V``%*N*V` | Parses the ISO 8601 week of the year as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. | | Week/day of the year | | `%j``%*N*j` | Parses the day of the year as a decimal number (January 1 is `1`). The width *N* specifies the maximum number of characters to read. The default width is 3. Leading zeroes are permitted but not required. | | `%U``%*N*U``%OU` | Parses the week number of the year as a decimal number. The first Sunday of the year is the first day of week 01. Days of the same year prior to that are in week 00. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OU` interprets the locale's alternative representation. | | `%W``%*N*W``%OW` | Parses the week number of the year as a decimal number. The first Monday of the year is the first day of week 01. Days of the same year prior to that are in week 00. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OW` interprets the locale's alternative representation. | | Date | | `%D` | Equivalent to `"%m/%d/%y"`. | | `%F``%*N*F` | Equivalent to `"%Y-%m-%d"`. If the width is specified, it is only applied to the `%Y`. | | `%x``%Ex` | Parses the locale's date representation. The modified command `%Ex` interprets the locale's alternate date representation. | | Time of day | | `%H``%*N*H``%OH` | Parses the hour (24-hour clock) as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OH` interprets the locale's alternative representation. | | `%I``%*N*I``%OI` | Parses the hour (12-hour clock) as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OI` interprets the locale's alternative representation. | | `%M``%*N*M``%OM` | Parses the minute as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OM` interprets the locale's alternative representation. | | `%S``%*N*S``%OS` | Parses the second as a decimal number. The width *N* specifies the maximum number of characters to read. The default width is 2. Leading zeroes are permitted but not required. The modified command `%OS` interprets the locale's alternative representation. | | `%p` | Parses the locale's equivalent of the AM/PM designations associated with a 12-hour clock. | | `%R` | Equivalent to `"%H:%M"`. | | `%T` | Equivalent to `"%H:%M:%S"`. | | `%r` | Parses the locale's 12-hour clock time. | | `%X``%EX` | Parses the locale's time representation. The modified command `%EX` interprets the locale's alternate time representation. | | Miscellaneous | | `%c``%Ec` | Parses the locale's date and time representation. The modified command `%Ec` interprets the locale's alternative date and time representation. | | `%z``%Ez``%Oz` | Parses the offset from UTC in the format `[+|-]hh[mm]`. For example `-0430` refers to 4 hours 30 minutes behind UTC and `04` refers to 4 hours ahead of UTC. The modified commands `%Ez` and `%Oz` parses the format `[+|-]h[h][:mm]` (i.e., requiring a `:` between the hours and minutes and making the leading zero for hour optional). | | `%Z` | Parses the time zone abbreviation or name, taken as the longest sequence of characters that only contains the characters `A` through `Z`, `a` through `z`, `0` through `9`, `-`, `+`, `_`, and `/`. | ### Return value `is`. ### Example ``` #include <chrono> #include <iostream> #include <locale> #include <sstream> int main() { std::istringstream is{"16:14:34"}; is.imbue(std::locale("en_US.utf-8")); std::chrono::hours hh; is >> std::chrono::from_stream("%H:%M:%S", hh); is.fail() ? std::cout << "Parse failed!\n" : std::cout << hh.count() << '\n'; } ``` Possible output: ``` 16 ``` ### See also | | | | --- | --- | | [parse](../parse "cpp/chrono/parse") (C++20) | parses a `chrono` object from a stream (function template) |
programming_docs
cpp std::chrono::duration<Rep,Period>::count std::chrono::duration<Rep,Period>::count ======================================== | | | | | --- | --- | --- | | ``` constexpr rep count() const; ``` | | | Returns the number of ticks for this duration. ### Parameters (none). ### Return value The number of ticks for this duration. ### Example ``` #include <chrono> #include <iostream> int main() { std::chrono::milliseconds ms{3}; // 3 milliseconds // 6000 microseconds constructed from 3 milliseconds std::chrono::microseconds us = 2*ms; // 30Hz clock using fractional ticks std::chrono::duration<double, std::ratio<1, 30>> hz30(3.5); std::cout << "3 ms duration has " << ms.count() << " ticks\n" << "6000 us duration has " << us.count() << " ticks\n" << "3.5 30Hz duration has " << hz30.count() << " ticks\n"; } ``` Output: ``` 3 ms duration has 3 ticks 6000 us duration has 6000 ticks 3.5 30Hz duration has 3.5 ticks ``` ### See also | | | | --- | --- | | [duration\_cast](duration_cast "cpp/chrono/duration/duration cast") (C++11) | converts a duration to another, with a different tick interval (function template) | cpp std::chrono::ceil(std::chrono::duration) std::chrono::ceil(std::chrono::duration) ======================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Rep, class Period> constexpr ToDuration ceil(const std::chrono::duration<Rep, Period>& d); ``` | | (since C++17) | Returns the smallest duration `t` representable in `ToDuration` that is greater or equal to `d`. The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. ### Parameters | | | | | --- | --- | --- | | d | - | duration to convert | ### Return value `d` rounded up to a duration of type `ToDuration`. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Rep, class Period, class = std::enable_if_t<detail::is_duration_v<To>>> constexpr To ceil(const std::chrono::duration<Rep, Period>& d) { To t = std::chrono::duration_cast<To>(d); if (t < d) return t + To{1}; return t; } ``` | ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; using Min = std::chrono::minutes; std::cout << std::showpos << "ceil(+2.4min) = " << std::chrono::ceil<Min>(+2.4min).count() << "min\n" << "ceil(-2.4min) = " << std::chrono::ceil<Min>(-2.4min).count() << "min\n" << "ceil(+0.0min) = " << std::chrono::ceil<Min>(+0.0min).count() << "min\n"; } ``` Output: ``` ceil(+2.4min) = +3min ceil(-2.4min) = -2min ceil(+0.0min) = +0min ``` ### See also | | | | --- | --- | | [duration\_cast](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)](floor "cpp/chrono/duration/floor") (C++17) | converts a duration to another, rounding down (function template) | | [round(std::chrono::duration)](round "cpp/chrono/duration/round") (C++17) | converts a duration to another, rounding to nearest, ties to even (function template) | | [ceil(std::chrono::time\_point)](../time_point/ceil "cpp/chrono/time point/ceil") (C++17) | converts a time\_point to another, rounding up (function template) | | [ceilceilfceill](../../numeric/math/ceil "cpp/numeric/math/ceil") (C++11)(C++11) | nearest integer not less than the given value (function) | cpp std::chrono::duration<Rep,Period>::zero std::chrono::duration<Rep,Period>::zero ======================================= | | | | | --- | --- | --- | | ``` static constexpr duration zero(); ``` | | (until C++20) | | ``` static constexpr duration zero() noexcept; ``` | | (since C++20) | Returns a zero-length duration. If the representation `rep` of the duration requires some other implementation to return a zero-length duration, `[std::chrono::duration\_values](../duration_values "cpp/chrono/duration values")` can be specialized to return the desired value. ### Parameters (none). ### Return value returns `duration([std::chrono::duration\_values](http://en.cppreference.com/w/cpp/chrono/duration_values)<rep>::zero())`. ### Example ``` #include <chrono> #include <ratio> int main() { static_assert((std::chrono::hours::zero() == std::chrono::nanoseconds::zero()) && (std::chrono::duration<short, std::nano>::zero() == std::chrono::duration<int, std::deci>::zero()) && (std::chrono::duration<short, std::deca>::zero() == std::chrono::duration<long, std::exa>::zero()) && (std::chrono::duration<long, std::atto>::zero().count() == std::chrono::duration<float, std::exa>::zero().count())); } ``` ### See also | | | | --- | --- | | [min](min "cpp/chrono/duration/min") [static] | returns the special duration value min (public static member function) | | [max](max "cpp/chrono/duration/max") [static] | returns the special duration value max (public static member function) | cpp std::chrono::duration<Rep,Period>::max std::chrono::duration<Rep,Period>::max ====================================== | | | | | --- | --- | --- | | ``` static constexpr duration max(); ``` | | (until C++20) | | ``` static constexpr duration max() noexcept; ``` | | (since C++20) | Returns a duration with the largest possible value. If the representation `rep` of the duration requires some other implementation to return a maximum-length duration, `[std::chrono::duration\_values](../duration_values "cpp/chrono/duration values")` can be specialized to return the desired value. ### Parameters (none). ### Return value returns `duration([std::chrono::duration\_values](http://en.cppreference.com/w/cpp/chrono/duration_values)<rep>::max())`. ### Example ``` #include <chrono> #include <iostream> #include <iomanip> #include <cstdint> int main() { constexpr uint64_t chrono_years_max = std::chrono::years::max().count(); constexpr uint64_t chrono_seconds_max = std::chrono::seconds::max().count(); constexpr uint64_t age_of_universe_in_years{13'787'000'000}; //: λCDM ≈ k₁/H₀ = k₂/42. constexpr uint64_t seconds_per_year{365'25 * 24 * 36}; // 365¼ × 24 × 60 × 60 constexpr uint64_t age_of_universe_in_seconds{age_of_universe_in_years * seconds_per_year}; std::cout << "The Age of the Universe is ≈ " << std::scientific << std::setprecision(2) << static_cast<double>(age_of_universe_in_years) << " years or " << static_cast<double>(age_of_universe_in_seconds) << " seconds.\n\n" << "chrono::years::max() = " << chrono_years_max << ", sizeof(chrono::years) = " << sizeof(std::chrono::years) << " bytes.\n" "chrono::years " << (age_of_universe_in_years <= chrono_years_max ? "CAN" : "CANNOT") << " keep the Age of the Universe in YEARS.\n\n" << "chrono::seconds::max() = " << chrono_seconds_max << ", sizeof(chrono::seconds) = " << sizeof(std::chrono::seconds) << " bytes.\n" "chrono::seconds " << (age_of_universe_in_seconds <= chrono_seconds_max ? "CAN" : "CANNOT") << " keep the Age of the Universe in SECONDS.\n"; } ``` Possible output: ``` The Age of the Universe is ≈ 1.38e+10 years or 4.35e+17 seconds. chrono::years::max() = 2147483647, sizeof(chrono::years) = 4 bytes. chrono::years CANNOT keep the Age of the Universe in YEARS. chrono::seconds::max() = 9223372036854775807, sizeof(chrono::seconds) = 8 bytes. chrono::seconds CAN keep the Age of the Universe in SECONDS. ``` ### See also | | | | --- | --- | | [zero](zero "cpp/chrono/duration/zero") [static] | returns the special duration value zero (public static member function) | | [min](min "cpp/chrono/duration/min") [static] | returns the special duration value min (public static member function) | cpp std::chrono::duration<Rep,Period>::min std::chrono::duration<Rep,Period>::min ====================================== | | | | | --- | --- | --- | | ``` static constexpr duration min(); ``` | | (until C++20) | | ``` static constexpr duration min() noexcept; ``` | | (since C++20) | Returns a duration with the lowest possible value. If the representation `rep` of the duration requires some other implementation to return a minimum-length duration, `[std::chrono::duration\_values](../duration_values "cpp/chrono/duration values")` can be specialized to return the desired value. ### Parameters (none). ### Return value returns `duration([std::chrono::duration\_values](http://en.cppreference.com/w/cpp/chrono/duration_values)<rep>::min())`. ### See also | | | | --- | --- | | [zero](zero "cpp/chrono/duration/zero") [static] | returns the special duration value zero (public static member function) | | [max](max "cpp/chrono/duration/max") [static] | returns the special duration value max (public static member function) | cpp std::chrono::abs(std::chrono::duration) std::chrono::abs(std::chrono::duration) ======================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class Rep, class Period> constexpr std::chrono::duration<Rep, Period> abs( std::chrono::duration<Rep, Period> d ); ``` | | (since C++17) | Returns the absolute value of the duration `d`. Specifically, if `d >= d.zero()`, return `d`, otherwise return `-d`. The function does not participate in the overload resolution unless `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<Rep>::is\_signed` is `true`. ### Parameters | | | | | --- | --- | --- | | d | - | duration | ### Return value Absolute value of `d`. ### Possible implementation | | | --- | | ``` template <class Rep, class Period, class = std::enable_if_t< std::chrono::duration<Rep, Period>::min() < std::chrono::duration<Rep, Period>::zero()>> constexpr std::chrono::duration<Rep, Period> abs(std::chrono::duration<Rep, Period> d) { return d >= d.zero() ? d : -d; } ``` | ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono; static_assert(abs(-42s) == std::chrono::abs(42s)); std::cout << "abs(+3min) = " << abs(3min).count() << '\n' << "abs(-3min) = " << abs(-3min).count() << '\n'; } ``` Output: ``` abs(+3min) = 3 abs(-3min) = 3 ``` ### See also | | | | --- | --- | | [operator+operator-](operator_arith "cpp/chrono/duration/operator arith") | implements unary + and unary - (public member function) | | [abs(int)labsllabs](../../numeric/math/abs "cpp/numeric/math/abs") (C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) | cpp std::chrono::duration<Rep,Period>::operator= std::chrono::duration<Rep,Period>::operator= ============================================ | | | | | --- | --- | --- | | ``` duration& operator=( const duration &other ) = default; ``` | | (since C++11) | Assigns the contents of one `duration` to another. ### Parameters | | | | | --- | --- | --- | | other | - | `duration` to copy from | ### Example ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono_literals; std::chrono::hours z_hours{}; std::chrono::seconds z_seconds{}; z_hours = 2h; // ok, no conversion needed z_seconds = z_hours; // First, the converting ctor is used to create a temporary object of `lhs`s type. // This ctor implicitly invokes the casting function // chrono::duration_cast<std::seconds>(z_hours). The resulting `rhs` rvalue // has the same type as `lhs`, and the `operator=` finally performs the assignment. std::cout << "hours: " << z_hours.count() << '\n'; std::cout << "seconds: " << z_seconds.count() << '\n'; z_seconds -= 42s; // z_hours = z_seconds; // compile-time error (which is good): incompatible types. // The library avoids the implicit cast to prevent a potential precision loss. z_hours = std::chrono::duration_cast<std::chrono::hours>(z_seconds); // ok z_hours = std::chrono::duration_cast<decltype(z_hours)>(z_seconds); // ditto std::cout << "hours: " << z_hours.count() << '\n'; std::cout << "seconds: " << z_seconds.count() << '\n'; std::chrono::duration<double, std::ratio<3600>> z2_hours{}; z2_hours = z_seconds; // ok, no truncation, implicit cast std::cout << "hours: " << z2_hours.count() << '\n'; } ``` Output: ``` hours: 2 seconds: 7200 hours: 1 seconds: 7158 hours: 1.98833 ``` ### See also | | | | --- | --- | | [(constructor)](duration "cpp/chrono/duration/duration") | constructs new duration (public member function) | cpp std::chrono::duration_cast std::chrono::duration\_cast =========================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Rep, class Period> constexpr ToDuration duration_cast(const std::chrono::duration<Rep,Period>& d); ``` | | (since C++11) | Converts a `[std::chrono::duration](../duration "cpp/chrono/duration")` to a duration of different type `ToDuration`. The function does not participate in overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. No implicit conversions are used. Multiplications and divisions are avoided where possible, if it is known at compile time that one or more parameters are `1`. Computations are done in the widest type available and converted, as if by [`static_cast`](../../language/static_cast "cpp/language/static cast"), to the result type only when finished. ### Parameters | | | | | --- | --- | --- | | d | - | duration to convert | ### Return value `d` converted to a duration of type `ToDuration`. ### Notes Casting between integer durations where the source period is exactly divisible by the target period (e.g. hours to minutes) or between floating-point durations can be performed with ordinary casts or implicitly via [`std::chrono::duration` constructors](duration "cpp/chrono/duration/duration"), no `duration_cast` is needed. Casting from a floating-point duration to an integer duration is [subject to undefined behavior](../../language/implicit_conversion#Floating_-_integral_conversions "cpp/language/implicit conversion") when the floating-point value is NaN, infinity, or too large to be representable by the target's integer type. Otherwise, casting to an integer duration is subject to truncation as with any `static_cast` to an integer type. ### Example This example measures the execution time of a function. ``` #include <iostream> #include <chrono> #include <ratio> #include <thread> void f() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { auto t1 = std::chrono::high_resolution_clock::now(); f(); auto t2 = std::chrono::high_resolution_clock::now(); // floating-point duration: no duration_cast needed std::chrono::duration<double, std::milli> fp_ms = t2 - t1; // integral duration: requires duration_cast auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); // converting integral duration to integral duration of shorter divisible time unit: // no duration_cast needed std::chrono::duration<long, std::micro> int_usec = int_ms; std::cout << "f() took " << fp_ms.count() << " ms, " << "or " << int_ms.count() << " whole milliseconds " << "(which is " << int_usec.count() << " whole microseconds)" << std::endl; } ``` Possible output: ``` f() took 1000.23 ms, or 1000 whole milliseconds (which is 1000000 whole microseconds) ``` ### See also | | | | --- | --- | | [duration](../duration "cpp/chrono/duration") (C++11) | a time interval (class template) | | [time\_point\_cast](../time_point/time_point_cast "cpp/chrono/time point/time point cast") (C++11) | converts a time point to another time point on the same clock, with a different duration (function template) | | [floor(std::chrono::duration)](floor "cpp/chrono/duration/floor") (C++17) | converts a duration to another, rounding down (function template) | | [ceil(std::chrono::duration)](ceil "cpp/chrono/duration/ceil") (C++17) | converts a duration to another, rounding up (function template) | | [round(std::chrono::duration)](round "cpp/chrono/duration/round") (C++17) | converts a duration to another, rounding to nearest, ties to even (function template) | cpp std::chrono::duration<Rep,Period>::operator+(unary), std::chrono::duration<Rep,Period>::operator-(unary) std::chrono::duration<Rep,Period>::operator+(unary), std::chrono::duration<Rep,Period>::operator-(unary) ======================================================================================================== | | | | | --- | --- | --- | | | (1) | | | ``` constexpr duration operator+() const; ``` | (until C++17) | | ``` constexpr std::common_type_t<duration> operator+() const; ``` | (since C++17) | | | (2) | | | ``` constexpr duration operator-() const; ``` | (until C++17) | | ``` constexpr std::common_type_t<duration> operator-() const; ``` | (since C++17) | Implements unary plus and unary minus for the durations. If `rep_` is a member variable holding the number of ticks in a duration object, and `D` is the return type, 1) Equivalent to `return D(*this);` 2) Equivalent to `return D(-rep_);` ### Parameters (none). ### Return value 1) a copy of this duration object 2) a copy of this duration object, with the number of ticks negated ### Example ``` #include <chrono> #include <iostream> int main() { std::chrono::seconds s1(10); std::chrono::seconds s2 = -s1; std::cout << "negated 10 seconds are " << s2.count() << " seconds\n"; } ``` Output: ``` negated 10 seconds are -10 seconds ``` ### See also | | | | --- | --- | | [operator++operator++(int)operator--operator--(int)](operator_arith2 "cpp/chrono/duration/operator arith2") | increments or decrements the tick count (public member function) | | [operator+operator-operator\*operator/operator%](operator_arith4 "cpp/chrono/duration/operator arith4") (C++11) | implements arithmetic operations with durations as arguments (function template) | cpp std::chrono::floor(std::chrono::duration) std::chrono::floor(std::chrono::duration) ========================================= | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class ToDuration, class Rep, class Period> constexpr ToDuration floor(const std::chrono::duration<Rep, Period>& d); ``` | | (since C++17) | Returns the greatest duration `t` representable in `ToDuration` that is less or equal to `d`. The function does not participate in the overload resolution unless `ToDuration` is a specialization of `[std::chrono::duration](../duration "cpp/chrono/duration")`. ### Parameters | | | | | --- | --- | --- | | d | - | duration to convert | ### Return value `d` rounded down to a duration of type `ToDuration`. ### Possible implementation | | | --- | | ``` namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template <class To, class Rep, class Period, class = std::enable_if_t<detail::is_duration_v<To>>> constexpr To floor(const duration<Rep, Period>& d) { To t = std::chrono::duration_cast<To>(d); if (t > d) return t - To{1}; return t; } ``` | ### Example ``` #include <iostream> #include <iomanip> #include <chrono> int main() { using namespace std::chrono_literals; using Sec = std::chrono::seconds; for (std::cout << "Duration\tFloor\tRound\tCeil\n" "(ms)\t\t(sec)\t(sec)\t(sec)\n"; auto const d: { +4999ms, +5000ms, +5001ms, +5499ms, +5500ms, +5999ms, -4999ms, -5000ms, -5001ms, -5499ms, -5500ms, -5999ms, }) { std::cout << std::showpos << d.count() << "\t\t" << std::chrono::floor<Sec>(d).count() << '\t' << std::chrono::round<Sec>(d).count() << '\t' << std::chrono::ceil <Sec>(d).count() << '\n'; } } ``` Output: ``` Duration Floor Round Ceil (ms) (sec) (sec) (sec) +4999 +4 +5 +5 +5000 +5 +5 +5 +5001 +5 +5 +6 +5499 +5 +5 +6 +5500 +5 +6 +6 +5999 +5 +6 +6 -4999 -5 -5 -4 -5000 -5 -5 -5 -5001 -6 -5 -5 -5499 -6 -5 -5 -5500 -6 -6 -5 -5999 -6 -6 -5 ``` ### See also | | | | --- | --- | | [duration\_cast](duration_cast "cpp/chrono/duration/duration cast") (C++11) | converts a duration to another, with a different tick interval (function template) | | [ceil(std::chrono::duration)](ceil "cpp/chrono/duration/ceil") (C++17) | converts a duration to another, rounding up (function template) | | [round(std::chrono::duration)](round "cpp/chrono/duration/round") (C++17) | converts a duration to another, rounding to nearest, ties to even (function template) | | [floor(std::chrono::time\_point)](../time_point/floor "cpp/chrono/time point/floor") (C++17) | converts a time\_point to another, rounding down (function template) | | [floorfloorffloorl](../../numeric/math/floor "cpp/numeric/math/floor") (C++11)(C++11) | nearest integer not greater than the given value (function) |
programming_docs
cpp operator==,!=,<,<=,>,>=,<=>(std::chrono::duration) operator==,!=,<,<=,>,>=,<=>(std::chrono::duration) ================================================== | | | | | --- | --- | --- | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator==(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (1) | (since C++11) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator!=(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (2) | (since C++11) (until C++20) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator<(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (3) | (since C++11) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator<=(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (4) | (since C++11) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator>(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (5) | (since C++11) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> constexpr bool operator>=(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (6) | (since C++11) | | ``` template <class Rep1, class Period1, class Rep2, class Period2> requires std::three_way_comparable<std::common_type_t<Rep1, Rep2>> constexpr auto operator<=>(const std::chrono::duration<Rep1, Period1>& lhs, const std::chrono::duration<Rep2, Period2>& rhs); ``` | (7) | (since C++20) | Compares two durations. Let `CT` be `[std::common\_type](http://en.cppreference.com/w/cpp/types/common_type)<[std::chrono::duration](http://en.cppreference.com/w/cpp/chrono/duration)<Rep1, Period1>, [std::chrono::duration](http://en.cppreference.com/w/cpp/chrono/duration)<Rep2, Period2>>::type`: 1-2) Checks if `lhs` and `rhs` are equal, i.e. the number of ticks for the type common to both durations are equal. 3-6) Compares `lhs` to `rhs`, i.e. compares the number of ticks for the type common to both durations. 7) Compares `lhs` to `rhs`, i.e. compares the number of ticks for the type common to both durations. The return type is deduced from `CT(lhs).count() <=> CT(rhs).count()`. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs | - | duration on the left-hand side of the operator | | rhs | - | duration on the right-hand side of the operator | ### Return value 1) `CT(lhs).count() == CT(rhs).count()` 2) `!(lhs == rhs)` 3) `CT(lhs).count() < CT(rhs).count()` 4) `!(rhs < lhs)` 5) `rhs < lhs` 6) `!(lhs < rhs)` 7) `CT(lhs).count() <=> CT(rhs).count()` ### Example ``` #include <chrono> #include <iostream> int main() { if(std::chrono::seconds(2) == std::chrono::milliseconds(2000)) std::cout << "2 s == 2000 ms\n"; else std::cout << "2 s != 2000 ms\n"; if(std::chrono::seconds(61) > std::chrono::minutes(1)) std::cout << "61 s > 1 min\n"; else std::cout << "61 s <= 1 min\n"; using namespace std::chrono_literals; static_assert(1h == 60min); static_assert(1min == 60s); static_assert(1s == 1'000ms); static_assert(1ms == 1'000us); static_assert(1us == 1'000ns); } ``` Output: ``` 2 s == 2000 ms 61 s > 1 min ``` cpp std::common_type(std::chrono::duration) std::common\_type(std::chrono::duration) ======================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class Rep1, class Period1, class Rep2, class Period2> struct common_type<std::chrono::duration<Rep1, Period1>, std::chrono::duration<Rep2, Period2>> { typedef std::chrono::duration< typename std::common_type<Rep1, Rep2>::type, /*see note*/> type; }; ``` | | (since C++11) | Exposes the type named `type`, which is the common type of two `[std::chrono::duration](../duration "cpp/chrono/duration")`s, whose period is the greatest common divisor of `Period1` and `Period2`. ### Note The period of the resulting duration can be computed by forming a ratio of the greatest common divisor of `Period1::num` and `Period2::num` and the least common multiple of `Period1::den` and `Period2::den`. ### Example ``` #include <type_traits> #include <iostream> #include <chrono> // std::chrono already finds the greatest common divisor, // likely using std::common_type<>. We make the type // deduction externally. template <typename T,typename S> constexpr auto durationDiff(const T& t, const S& s) -> typename std::common_type<T,S>::type { typedef typename std::common_type<T,S>::type Common; return Common(t) - Common(s); } int main() { using namespace std::literals; constexpr auto ms = 30ms; constexpr auto us = 1100us; constexpr auto diff = durationDiff(ms, us); std::cout << ms.count() << "ms - " << us.count() << "μs = " << diff.count() << (std::is_same<decltype(diff), decltype(ms)>() ? "ms" : "μs") << '\n'; } ``` Output: ``` 30ms - 1100μs = 28900μs ``` ### See also | | | | --- | --- | | [std::common\_type<std::chrono::time\_point>](../time_point/common_type "cpp/chrono/time point/common type") (C++11) | specializes the `[std::common\_type](../../types/common_type "cpp/types/common type")` trait (class template specialization) | | [common\_type](../../types/common_type "cpp/types/common type") (C++11) | determines the common type of a group of types (class template) | cpp std::chrono::high_resolution_clock::now std::chrono::high\_resolution\_clock::now ========================================= | | | | | --- | --- | --- | | ``` static std::chrono::time_point<std::chrono::high_resolution_clock> now() noexcept; ``` | | (since C++11) | Returns a time point representing the current point in time. ### Parameters (none). ### Return value A time point representing the current time. ### Example ``` #include <iostream> #include <iomanip> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main() { std::cout << std::fixed << std::setprecision(9) << std::left; for (auto size = 1ull; size < 1000'000'000ull; size *= 100) { // record start time auto start = std::chrono::high_resolution_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = end - start; std::cout << "Time to fill and iterate a vector of " << std::setw(9) << size << " ints : " << diff.count() << " s\n"; } } ``` Possible output: ``` Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s ``` cpp std::chrono::month_day_last::month_day_last std::chrono::month\_day\_last::month\_day\_last =============================================== | | | | | --- | --- | --- | | ``` explicit constexpr month_day_last(const std::chrono::month& m) noexcept; ``` | | (since C++20) | Constructs a `month_day_last` object that represents the last day of the month `m`. ### Notes A more convenient way to construct a `month_day_last` is with `operator/`, e.g., `[std::chrono::April](http://en.cppreference.com/w/cpp/chrono/month)/[std::chrono::last](http://en.cppreference.com/w/cpp/chrono/last_spec)`. ### See also | | | | --- | --- | | [operator/](../operator_slash "cpp/chrono/operator slash") (C++20) | conventional syntax for Gregorian calendar date creation (function) | cpp std::chrono::operator<<(std::chrono::month_day_last) std::chrono::operator<<(std::chrono::month\_day\_last) ====================================================== | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::month_day_last& mdl ); ``` | | (since C++20) | Outputs a textual representation of `mdl` into `os`, as if by. `os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L}/last"), mdl.month());` where `STATICALLY_WIDEN<CharT>("{:L}/last")` is `"{:L}/last"` if `CharT` is `char`, and `L"{:L}/last"` if `CharT` is `wchar_t`. ### Return value `os`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::month\_day>](../month_day/formatter "cpp/chrono/month day/formatter") (C++20) | specialization of `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` that formats a `month_day` according to the provided format (class template specialization) | cpp std::chrono::month_day_last::ok std::chrono::month\_day\_last::ok ================================= | | | | | --- | --- | --- | | ``` constexpr bool ok() const noexcept; ``` | | (since C++20) | Checks if the `month` object stored in `*this` is valid. ### Return value `month().ok()`. ### Example ``` #include <iostream> #include <chrono> int main() { std::cout << std::boolalpha; auto mdl {std::chrono::February/std::chrono::last}; std::cout << (mdl.ok()) << ' '; mdl = {std::chrono::month(42)/std::chrono::last}; std::cout << (mdl.ok()) << '\n'; } ``` Output: ``` true false ``` cpp std::chrono::month_day_last::month std::chrono::month\_day\_last::month ==================================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::month month() const noexcept; ``` | | (since C++20) | Retrieves a copy of the `std::chrono::month` object stored in `*this`. ### Return value A copy of the `std::chrono::month` object stored in `*this`. ### Example ``` #include <iostream> #include <chrono> using namespace std::chrono; int main() { std::cout << std::boolalpha; auto mdl {February/last}; // Last day of a February auto ymdl {year(2020)/mdl}; std::cout << (year_month_day{ymdl} == year_month_day{February/29/2020}) << ' '; // Last day of the next month, in 2020 mdl = {(mdl.month() + months(1))/last}; ymdl = {year(2020)/mdl}; std::cout << (year_month_day{ymdl} == year_month_day{March/31/2020}) << '\n'; } ``` Output: ``` true true ``` cpp std::strftime std::strftime ============= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::size_t strftime( char* str, std::size_t count, const char* format, const std::tm* time ); ``` | | | Converts the date and time information from a given calendar time `time` to a null-terminated multibyte character string `str` according to [format string](#Format_string) `format`. Up to `count` bytes are written. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the first element of the char array for output | | count | - | maximum number of bytes to write | | format | - | pointer to a null-terminated multibyte character string specifying the [format of conversion](#Format_string) | | time | - | pointer to the date and time information to be converted | ### 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 The number of bytes written into the character array pointed to by `str` not including the terminating `'\0'` on success. If `count` was reached before the entire string could be stored, `​0​` is returned and the contents are undefined. ### Example ``` #include <ctime> #include <iostream> #include <locale> int main() { std::time_t t = std::time(nullptr); char mbstr[100]; if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&t))) { std::cout << mbstr << '\n'; } std::locale::global(std::locale("ja_JP.utf8")); if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&t))) { std::cout << mbstr << '\n'; } } ``` Possible output: ``` Tuesday Tue Sep 7 19:40:35 2021 火曜日 2021年09月07日 19時40分35秒 ``` ### See also | | | | --- | --- | | [asctime](asctime "cpp/chrono/c/asctime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to a textual representation (function) | | [ctime](ctime "cpp/chrono/c/ctime") | converts a `[std::time\_t](time_t "cpp/chrono/c/time t")` object to a textual representation (function) | | [wcsftime](wcsftime "cpp/chrono/c/wcsftime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to custom wide string textual representation (function) | | [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) | | [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) | | [C documentation](https://en.cppreference.com/w/c/chrono/strftime "c/chrono/strftime") for `strftime` |
programming_docs
cpp std::difftime std::difftime ============= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` double difftime( std::time_t time_end, std::time_t time_beg ); ``` | | | Computes difference between two calendar times as `[std::time\_t](time_t "cpp/chrono/c/time t")` objects (`time_end - time_beg`) in seconds. If `time_end` refers to time point before `time_beg` then the result is negative. ### Parameters | | | | | --- | --- | --- | | time\_beg, time\_end | - | times to compare | ### Return value Difference between two times in seconds. ### Notes On POSIX systems, `[std::time\_t](time_t "cpp/chrono/c/time t")` is measured in seconds, and `difftime` is equivalent to arithmetic subtraction, but C and C++ allow fractional units for `time_t`. ### Example ``` #include <iostream> #include <ctime> int main() { std::time_t start = std::time(nullptr); volatile double d = 1.0; // some time-consuming operation for (int p=0; p<10000; ++p) { for (int q=0; q<100000; ++q) { d = d+p*d*q+d; } } std::cout << "Wall time passed: " << std::difftime(std::time(nullptr), start) << " s.\n"; } ``` Possible output: ``` Wall time passed: 9 s. ``` ### See also | | | | --- | --- | | [duration](../duration "cpp/chrono/duration") (C++11) | a time interval (class template) | | [C documentation](https://en.cppreference.com/w/c/chrono/difftime "c/chrono/difftime") for `difftime` | cpp std::gmtime std::gmtime =========== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::tm* gmtime( const std::time_t* time ); ``` | | | Converts given time since epoch as `[std::time\_t](time_t "cpp/chrono/c/time t")` value into calendar time, expressed in Coordinated Universal Time (UTC). ### Parameters | | | | | --- | --- | --- | | time | - | pointer to a time\_t object to convert | ### Return value Pointer to a static internal `[std::tm](tm "cpp/chrono/c/tm")` object on success, or null pointer otherwise. The structure may be shared between `std::gmtime`, `[std::localtime](localtime "cpp/chrono/c/localtime")`, and `[std::ctime](ctime "cpp/chrono/c/ctime")` and may be overwritten on each invocation. ### Notes This function may not be thread-safe. POSIX requires that this function sets `[errno](../../error/errno "cpp/error/errno")` to `[EOVERFLOW](../../error/errno_macros "cpp/error/errno macros")` if it fails because the argument is too large. ### Example ``` #include <iostream> #include <sstream> #include <iomanip> #include <ctime> int main() { setenv("TZ", "/usr/share/zoneinfo/Europe/London", 1); // POSIX-specific std::tm tm{}; // get_time does not set all fields hence {} tm.tm_year = 2020-1900; // 2020 tm.tm_mon = 7-1; // July tm.tm_mday = 15; // 15th tm.tm_hour = 10; tm.tm_min = 15; tm.tm_isdst = 1; // Daylight saving in London std::time_t t = std::mktime(&tm); std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z") << '\n'; std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n'; } ``` Possible output: ``` UTC: Wed Jul 15 09:15:00 2020 GMT local: Wed Jul 15 10:15:00 2020 BST ``` ### See also | | | | --- | --- | | [localtime](localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/gmtime "c/chrono/gmtime") for `gmtime` | cpp std::time_t std::time\_t ============ | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ time_t; ``` | | | Arithmetic type capable of representing times. Although not defined, this is almost always an integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to [POSIX time](https://en.wikipedia.org/wiki/Unix_time "enwiki:Unix time"). ### See also | | | | --- | --- | | [time](time "cpp/chrono/c/time") | returns the current time of the system as time since epoch (function) | | [localtime](localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [gmtime](gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) | | [to\_time\_t](../system_clock/to_time_t "cpp/chrono/system clock/to time t") [static] | converts a system clock time point to `std::time_t` (public static member function of `std::chrono::system_clock`) | | [C documentation](https://en.cppreference.com/w/c/chrono/time_t "c/chrono/time t") for `time_t` | cpp std::ctime std::ctime ========== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` char* ctime( const std::time_t* time ); ``` | | | Converts given time since epoch to a calendar local time and then to a textual representation, as if by calling `[std::asctime](http://en.cppreference.com/w/cpp/chrono/c/asctime)([std::localtime](http://en.cppreference.com/w/cpp/chrono/c/localtime)(time))`. The resulting string has the following format: ``` Www Mmm dd hh:mm:ss yyyy\n ``` * `Www` - the day of the week (one of `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`). * `Mmm` - the month (one of `Jan`, `Feb`, `Mar`, `Apr`, `May`, `Jun`, `Jul`, `Aug`, `Sep`, `Oct`, `Nov`, `Dec`). * `dd` - the day of the month * `hh` - hours * `mm` - minutes * `ss` - seconds * `yyyy` - years The function does not support localization. ### Parameters | | | | | --- | --- | --- | | time | - | pointer to a `[std::time\_t](time_t "cpp/chrono/c/time t")` object specifying the time to print | ### Return value Pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between `[std::asctime](asctime "cpp/chrono/c/asctime")` and `std::ctime`, and may be overwritten on each invocation of any of those functions. ### Notes This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static `[std::tm](tm "cpp/chrono/c/tm")` object which may be shared with `[std::gmtime](gmtime "cpp/chrono/c/gmtime")` and `[std::localtime](localtime "cpp/chrono/c/localtime")`. POSIX marks this function obsolete and recommends `[std::strftime](strftime "cpp/chrono/c/strftime")` instead. The behavior may be undefined for the values of `[std::time\_t](time_t "cpp/chrono/c/time t")` that result in the string longer than 25 characters (e.g. year 10000). ### Example ``` #include <ctime> #include <cstring> #include <cassert> #include <iostream> int main() { std::time_t result = std::time(nullptr); std::cout << std::ctime(&result); char buffer[32]; std::strncpy(buffer, std::ctime(&result), 26); assert('\n' == buffer[std::strlen(buffer)-1]); std::cout << buffer; } ``` Possible output: ``` Mon Oct 11 17:10:55 2021 Mon Oct 11 17:10:55 2021 ``` ### See also | | | | --- | --- | | [asctime](asctime "cpp/chrono/c/asctime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to a textual representation (function) | | [strftime](strftime "cpp/chrono/c/strftime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to custom textual representation (function) | | [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) | | [C documentation](https://en.cppreference.com/w/c/chrono/ctime "c/chrono/ctime") for `ctime` | cpp std::mktime std::mktime =========== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::time_t mktime( std::tm* time ); ``` | | | Converts local calendar time to a time since epoch as a `time_t` object. `time->tm_wday` and `time->tm_yday` are ignored. The values in `time` are permitted to be outside their normal ranges. A negative value of `time->tm_isdst` causes `mktime` to attempt to determine if Daylight Saving Time was in effect. If the conversion is successful, the `time` object is modified. All fields of `time` are updated to fit their proper ranges. `time->tm_wday` and `time->tm_yday` are recalculated using information available in other fields. ### Parameters | | | | | --- | --- | --- | | time | - | pointer to a `[std::tm](tm "cpp/chrono/c/tm")` object specifying local calendar time to convert | ### Return value Time since epoch as a `[std::time\_t](time_t "cpp/chrono/c/time t")` object on success or `-1` if `time` cannot be represented as a `[std::time\_t](time_t "cpp/chrono/c/time t")` object. ### Notes If the `[std::tm](tm "cpp/chrono/c/tm")` object was obtained from `[std::get\_time](../../io/manip/get_time "cpp/io/manip/get time")` or the POSIX [`strptime`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html), the value of `tm_isdst` is indeterminate, and needs to be set explicitly before calling `mktime`. ### Example Construct a local time explicitly. ``` #include <iostream> #include <sstream> #include <iomanip> #include <ctime> int main() { setenv("TZ", "/usr/share/zoneinfo/America/Los_Angeles", 1); // POSIX-specific std::tm tm{}; // zero initialise tm.tm_year = 2020-1900; // 2020 tm.tm_mon = 2-1; // February tm.tm_mday = 15; // 15th tm.tm_hour = 10; tm.tm_min = 15; tm.tm_isdst = 0; // Not daylight saving std::time_t t = std::mktime(&tm); std::tm local = *std::localtime(&t); std::cout << "local: " << std::put_time(&local, "%c %Z") << '\n'; } ``` Possible output: ``` local: Sat Feb 15 10:15:00 2020 PST ``` ### See also | | | | --- | --- | | [localtime](localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/mktime "c/chrono/mktime") for `mktime` | cpp std::wcsftime std::wcsftime ============= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t wcsftime( wchar_t* str, std::size_t count, const wchar_t* format, const std::tm* time ); ``` | | | Converts the date and time information from a given calendar time `time` to a null-terminated wide character string `str` according to [format string](#Format_string) `format`. Up to `count` wide characters are written. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the first element of the `wchar_t` array for output | | count | - | maximum number of wide characters to write | | format | - | pointer to a null-terminated wide character string specifying the [format of conversion](#Format_string) | | time | - | pointer to the date and time information to be converted | ### 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 Number of wide characters written into the wide character array pointed to by `str` not including the terminating `L'\0'` on success. If `count` was reached before the entire string could be stored, `​0​` is returned and the contents are undefined. ### Example ``` #include <ctime> #include <cwchar> #include <iostream> #include <locale> int main() { std::locale::global(std::locale("ja_JP.utf8")); std::time_t t = std::time(nullptr); wchar_t wstr[100]; if(std::wcsftime(wstr, 100, L"%A %c", std::localtime(&t))) { std::wcout << wstr << '\n'; } } ``` Possible output: ``` 火曜日 2011年12月27日 17時43分13秒 ``` ### See also | | | | --- | --- | | [strftime](strftime "cpp/chrono/c/strftime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to custom textual representation (function) | | [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) | | [C documentation](https://en.cppreference.com/w/c/chrono/wcsftime "c/chrono/wcsftime") for `wcsftime` |
programming_docs
cpp std::localtime std::localtime ============== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::tm* localtime( const std::time_t *time ); ``` | | | Converts given time since epoch as `[std::time\_t](time_t "cpp/chrono/c/time t")` value into calendar time, expressed in local time. ### Parameters | | | | | --- | --- | --- | | time | - | pointer to a `[std::time\_t](time_t "cpp/chrono/c/time t")` object to convert | ### Return value pointer to a static internal `[std::tm](tm "cpp/chrono/c/tm")` object on success, or null pointer otherwise. The structure may be shared between `[std::gmtime](gmtime "cpp/chrono/c/gmtime")`, `std::localtime`, and `[std::ctime](ctime "cpp/chrono/c/ctime")`, and may be overwritten on each invocation. ### Notes This function may not be thread-safe. POSIX requires that this function sets `[errno](../../error/errno "cpp/error/errno")` to `[EOVERFLOW](../../error/errno_macros "cpp/error/errno macros")` if it fails because the argument is too large. [POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/localtime.html) that the timezone information is determined by this function as if by calling [`tzset`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tzset.html), which reads the environment variable `TZ`. ### Example ``` #include <iostream> #include <sstream> #include <iomanip> #include <ctime> int main() { setenv("TZ", "/usr/share/zoneinfo/America/Los_Angeles", 1); // POSIX-specific std::tm tm{}; // zero initialise tm.tm_year = 2020-1900; // 2020 tm.tm_mon = 2-1; // February tm.tm_mday = 15; // 15th tm.tm_hour = 10; tm.tm_min = 15; tm.tm_isdst = 0; // Not daylight saving std::time_t t = std::mktime(&tm); std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z") << '\n'; std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n'; } ``` Possible output: ``` UTC: Sat Feb 15 18:15:00 2020 GMT local: Sat Feb 15 10:15:00 2020 PST ``` ### See also | | | | --- | --- | | [gmtime](gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) | | [localtimelocaltime\_rlocaltime\_s](https://en.cppreference.com/w/c/chrono/localtime "c/chrono/localtime") (C23)(C11) | converts time since epoch to calendar time expressed as local time (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/localtime "c/chrono/localtime") for `localtime` | cpp std::timespec std::timespec ============= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` struct timespec; ``` | | (since C++17) | Structure holding an interval broken down into seconds and nanoseconds. ### Member objects | | | | --- | --- | | `[std::time\_t](time_t "cpp/chrono/c/time t")` `tv_sec` | whole seconds – >= 0 | | `long` `tv_nsec` | nanoseconds – [0, 999999999] | ### See also | | | | --- | --- | | [timespec\_get](timespec_get "cpp/chrono/c/timespec get") (C++17) | returns the calendar time in seconds and nanoseconds based on a given time base (function) | | [tm](tm "cpp/chrono/c/tm") | calendar time type (class) | | [C documentation](https://en.cppreference.com/w/c/chrono/timespec "c/chrono/timespec") for `timespec` | cpp std::time std::time ========= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::time_t time( std::time_t* arg ); ``` | | | Returns the current calendar time encoded as a `[std::time\_t](time_t "cpp/chrono/c/time t")` object, and also stores it in the object pointed to by `arg`, unless `arg` is a null pointer. ### Parameters | | | | | --- | --- | --- | | arg | - | pointer to a `[std::time\_t](time_t "cpp/chrono/c/time t")` object to store the time, or a null pointer | ### Return value Current calendar time encoded as `[std::time\_t](time_t "cpp/chrono/c/time t")` object on success, `([std::time\_t](http://en.cppreference.com/w/cpp/chrono/c/time_t))(-1)` on error. If `arg` is not null, the return value is also stored in the object pointed to by `arg`. ### Notes The encoding of calendar time in `[std::time\_t](time_t "cpp/chrono/c/time t")` is unspecified, but most systems conform to the [POSIX specification](http://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html) and return a value of integral type holding 86400 times the number of calendar days since [the Epoch](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) plus the number of seconds that have passed since the last midnight UTC. Most notably, POSIX time does not (and can not) take leap seconds into account, so that this integral value is not equal to the number of [S.I. seconds](https://en.wikipedia.org/wiki/SI_base_unit#Definitions "enwiki:SI base unit") that have passed since the epoch, but rather is reduced with the number of leap seconds that have occurred since the epoch. Implementations in which `[std::time\_t](time_t "cpp/chrono/c/time t")` is a 32-bit signed integer (many historical implementations) fail in the year [2038](https://en.wikipedia.org/wiki/Year_2038_problem "enwiki:Year 2038 problem"). ### Example ``` #include <ctime> #include <iostream> int main() { std::time_t result = std::time(nullptr); std::cout << std::asctime(std::localtime(&result)) << result << " seconds since the Epoch\n"; } ``` Possible output: ``` Wed Sep 21 10:27:52 2011 1316615272 seconds since the Epoch ``` ### See also | | | | --- | --- | | [timespec\_get](timespec_get "cpp/chrono/c/timespec get") (C++17) | returns the calendar time in seconds and nanoseconds based on a given time base (function) | | [localtime](localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [gmtime](gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) | | [system\_clock](../system_clock "cpp/chrono/system clock") (C++11) | wall clock time from the system-wide realtime clock (class) | | [C documentation](https://en.cppreference.com/w/c/chrono/time "c/chrono/time") for `time` | cpp std::timespec_get std::timespec\_get ================== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` int timespec_get( std::timespec* ts, int base ); ``` | (1) | (since C++17) | | ``` #define TIME_UTC /* implementation-defined */ ``` | (2) | (since C++17) | 1) Modifies the `[std::timespec](timespec "cpp/chrono/c/timespec")` object pointed to by `ts` to hold the current calendar time in the time base `base`. 2) Expands to a value suitable for use as the `base` argument of `std::timespec_get` Other macro constants beginning with `TIME_` may be provided by the implementation to indicate additional time bases. If `base` is `TIME_UTC`, then. * `ts->tv_sec` is set to the number of seconds since an implementation defined epoch, truncated to a whole value * `ts->tv_nsec` member is set to the integral number of nanoseconds, rounded to the resolution of the system clock ### Parameters | | | | | --- | --- | --- | | ts | - | pointer to an object of type `[std::timespec](timespec "cpp/chrono/c/timespec")` | | base | - | `TIME_UTC` or another nonzero integer value indicating the time base | ### Return value The value of `base` if successful, zero otherwise. ### Notes The POSIX function [clock\_gettime(CLOCK\_REALTIME, ts)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) may also be used to populate a `std::timespec` with the time since the Epoch. ### Example ``` #include <iostream> #include <ctime> int main() { std::timespec ts; std::timespec_get(&ts, TIME_UTC); char buf[100]; std::strftime(buf, sizeof buf, "%D %T", std::gmtime(&ts.tv_sec)); std::cout << "Current time: " << buf << '.' << ts.tv_nsec << " UTC\n"; } ``` Possible output: ``` Current time: 06/24/16 20:07:42.949494132 UTC ``` ### See also | | | | --- | --- | | [timespec](timespec "cpp/chrono/c/timespec") (C++17) | time in seconds and nanoseconds (struct) | | [time](time "cpp/chrono/c/time") | returns the current time of the system as time since epoch (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/timespec_get "c/chrono/timespec get") for `timespec_get` | cpp std::clock_t std::clock\_t ============= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ clock_t; ``` | | | Arithmetic type capable of representing the process running time of implementation-defined range and precision. ### See also | | | | --- | --- | | [clock](clock "cpp/chrono/c/clock") | returns raw processor clock time since the program is started (function) | | [CLOCKS\_PER\_SEC](clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC") | number of processor clock ticks per second (macro constant) | | [C documentation](https://en.cppreference.com/w/c/chrono/clock_t "c/chrono/clock t") for `clock_t` | cpp std::asctime std::asctime ============ | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` char* asctime( const std::tm* time_ptr ); ``` | | | Converts given calendar time `[std::tm](tm "cpp/chrono/c/tm")` to a textual representation of the following fixed 25-character form: `Www Mmm dd hh:mm:ss yyyy\n`. * `Www` - three-letter English abbreviated day of the week from `time_ptr->tm_wday`, one of `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`. * `Mmm` - three-letter English abbreviated month name from `time_ptr->tm_mon`, one of `Jan`, `Feb`, `Mar`, `Apr`, `May`, `Jun`, `Jul`, `Aug`, `Sep`, `Oct`, `Nov`, `Dec`. * `dd` - 2-digit day of the month from `timeptr->tm_mday` as if printed by `sprintf` using `%2d` * `hh` - 2-digit hour from `timeptr->tm_hour` as if printed by `sprintf` using `%.2d` * `mm` - 2-digit minute from `timeptr->tm_min` as if printed by `sprintf` using `%.2d` * `ss` - 2-digit second from `timeptr->tm_sec` as if printed by `sprintf` using `%.2d` * `yyyy` - 4-digit year from `timeptr->tm_year + 1900` as if printed by `sprintf` using `%4d` The behavior is undefined if any member of `*time_ptr` is outside its normal range. The behavior is undefined if the calendar year indicated by `time_ptr->tm_year` has more than 4 digits or is less than the year 1000. The function does not support localization, and the newline character cannot be removed. The function modifies static storage and is not thread-safe. ### Parameters | | | | | --- | --- | --- | | time\_ptr | - | pointer to a `[std::tm](tm "cpp/chrono/c/tm")` object specifying the time to print | ### Return value Pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between `std::asctime` and `[std::ctime](ctime "cpp/chrono/c/ctime")`, and may be overwritten on each invocation of any of those functions. ### Notes This function returns a pointer to static data and is not thread-safe. POSIX marks this function obsolete and recommends locale-dependent `[std::strftime](strftime "cpp/chrono/c/strftime")` instead. In `[std::locale](../../locale/locale "cpp/locale/locale")``("C")` the `[std::strftime](strftime "cpp/chrono/c/strftime")` format string `"%c\n"` will be an exact match to `std::asctime` output, while in other locales the format string `"%a %b %e %H:%M:%S %Y\n"` will be a potentially closer but not always exact match. POSIX limits undefined behaviors only to the cases when the output string would be longer than 25 characters, when `timeptr->tm_wday` or `timeptr->tm_mon` are not within the expected ranges, or when `timeptr->tm_year` exceeds `INT_MAX-1990`. Some implementations handle `timeptr->tm_mday==0` as meaning the last day of the preceding month. ### Example ``` #include <ctime> #include <iomanip> #include <iostream> int main() { const std::time_t now = std::time(nullptr); for (const char *localeName : {"C", "en_US.utf8", "de_DE.utf8", "ja_JP.utf8" }) { std::cout << "locale " << localeName << ":" "\n" << std::left; std::locale::global(std::locale(localeName)); std::cout << std::setw(40) << " asctime" << std::asctime(std::localtime(&now)); // strftime output for comparison: char buf[64]; if (strftime(buf, sizeof buf, "%c\n", std::localtime(&now))) { std::cout << std::setw(40) << " strftime %c" << buf; } if (strftime(buf, sizeof buf, "%a %b %e %H:%M:%S %Y\n", std::localtime(&now))) { std::cout << std::setw(40) << " strftime %a %b %e %H:%M:%S %Y" << buf; } std::cout << '\n'; } } ``` Possible output: ``` locale C: asctime Wed Nov 4 00:45:01 2020 strftime %c Wed Nov 4 00:45:01 2020 strftime %a %b %e %H:%M:%S %Y Wed Nov 4 00:45:01 2020 locale en_US.utf8: asctime Wed Nov 4 00:45:01 2020 strftime %c Wed 04 Nov 2020 12:45:01 AM UTC strftime %a %b %e %H:%M:%S %Y Wed Nov 4 00:45:01 2020 locale de_DE.utf8: asctime Wed Nov 4 00:45:01 2020 strftime %c Mi 04 Nov 2020 00:45:01 UTC strftime %a %b %e %H:%M:%S %Y Mi Nov 4 00:45:01 2020 locale ja_JP.utf8: asctime Wed Nov 4 00:45:01 2020 strftime %c 2020年11月04日 00時45分01秒 strftime %a %b %e %H:%M:%S %Y 水 11月 4 00:45:01 2020 ``` ### See also | | | | --- | --- | | [ctime](ctime "cpp/chrono/c/ctime") | converts a `[std::time\_t](time_t "cpp/chrono/c/time t")` object to a textual representation (function) | | [strftime](strftime "cpp/chrono/c/strftime") | converts a `[std::tm](tm "cpp/chrono/c/tm")` object to custom textual representation (function) | | [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) | | [C documentation](https://en.cppreference.com/w/c/chrono/asctime "c/chrono/asctime") for `asctime` | cpp std::tm std::tm ======= | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` struct tm; ``` | | | Structure holding a calendar date and time broken down into its components. ### Member objects | | | | --- | --- | | int tm\_sec | seconds after the minute – [0, 61] (until C++11)[0, 60] (since C++11)[[note 1]](#cite_note-leapsecond-1) (public member object) | | int tm\_min | minutes after the hour – [0, 59] (public member object) | | int tm\_hour | hours since midnight – [0, 23] (public member object) | | int tm\_mday | day of the month – [1, 31] (public member object) | | int tm\_mon | months since January – [0, 11] (public member object) | | int tm\_year | years since 1900 (public member object) | | int tm\_wday | days since Sunday – [0, 6] (public member object) | | int tm\_yday | days since January 1 – [0, 365] (public member object) | | int tm\_isdst | Daylight Saving Time flag. The value is positive if DST is in effect, zero if not and negative if no information is available (public member object) | ###### Notes The Standard mandates only the presence of the aforementioned members in either order. The implementations usually add more data-members to this structure. 1. Range allows for a positive leap second. Two leap seconds in the same minute are not allowed (the range 0..61 was a defect introduced in C89 and corrected in C99) ### Example ``` #include <ctime> #include <iostream> int main() { std::tm tm{}; tm.tm_year = 2022-1900; tm.tm_mday = 1; std::mktime(&tm); std::cout << std::asctime(&tm) << "sizeof(std::tm) = " << sizeof(std::tm) << '\n'; } ``` Possible output: ``` Sat Jan 1 00:00:00 2022 sizeof(std::tm) = 56 ``` ### See also | | | | --- | --- | | [localtime](localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [gmtime](gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/tm "c/chrono/tm") for `tm` | cpp CLOCKS_PER_SEC CLOCKS\_PER\_SEC ================ | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` #define CLOCKS_PER_SEC /*implementation defined*/ ``` | | | Expands to an expression (not necessarily a compile-time constant) of type `[std::clock\_t](clock_t "cpp/chrono/c/clock t")` equal to the number of clock ticks per second, as returned by `[std::clock()](clock "cpp/chrono/c/clock")`. ### Notes POSIX defines `CLOCKS_PER_SEC` as one million, regardless of the actual precision of `[std::clock()](clock "cpp/chrono/c/clock")`. ### See also | | | | --- | --- | | [clock](clock "cpp/chrono/c/clock") | returns raw processor clock time since the program is started (function) | | [clock\_t](clock_t "cpp/chrono/c/clock t") | process running time (typedef) | | [C documentation](https://en.cppreference.com/w/c/chrono/CLOCKS_PER_SEC "c/chrono/CLOCKS PER SEC") for `CLOCKS_PER_SEC` | cpp std::clock std::clock ========== | Defined in header `[<ctime>](../../header/ctime "cpp/header/ctime")` | | | | --- | --- | --- | | ``` std::clock_t clock(); ``` | | | Returns the approximate processor time used by the process since the beginning of an implementation-defined era related to the program's execution. To convert result value to seconds divide it by `[CLOCKS\_PER\_SEC](clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC")`. Only the difference between two values returned by different calls to `std::clock` is meaningful, as the beginning of the `std::clock` era does not have to coincide with the start of the program. `std::clock` time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system. For example, if the CPU is shared by other processes, `std::clock` time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, `std::clock` time may advance faster than wall clock. ### Parameters (none). ### Return value Processor time used by the program so far or `[std::clock\_t](http://en.cppreference.com/w/cpp/chrono/c/clock_t)(-1)` if that information is unavailable or its value cannot be represented. ### Exceptions Throws nothing. ### Notes On POSIX-compatible systems, [`clock_gettime`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) with clock id `CLOCK_PROCESS_CPUTIME_ID` offers better resolution. The value returned by `clock()` may wrap around on some non-conforming implementations. For example, on such an implementation, if `[std::clock\_t](clock_t "cpp/chrono/c/clock t")` is a signed 32-bit integer and `[CLOCKS\_PER\_SEC](clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC")` is 1000000, it will wrap after about 2147 seconds (about 36 minutes). ### Example This example demonstrates the difference between `clock()` time and real time. ``` #include <iostream> #include <iomanip> #include <chrono> #include <ctime> #include <thread> // the function f() does some time-consuming work void f() { volatile double d = 0; for(int n=0; n<10000; ++n) for(int m=0; m<10000; ++m) { double diff = d*n*m; d = diff + d; } } int main() { std::clock_t c_start = std::clock(); auto t_start = std::chrono::high_resolution_clock::now(); std::thread t1(f); std::thread t2(f); // f() is called on two threads t1.join(); t2.join(); std::clock_t c_end = std::clock(); auto t_end = std::chrono::high_resolution_clock::now(); std::cout << std::fixed << std::setprecision(2) << "CPU time used: " << 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << " ms\n" << "Wall clock time passed: " << std::chrono::duration<double, std::milli>(t_end-t_start).count() << " ms\n"; } ``` Possible output: ``` CPU time used: 1590.00 ms Wall clock time passed: 808.23 ms ``` ### See also | | | | --- | --- | | [ctime](ctime "cpp/chrono/c/ctime") | converts a `[std::time\_t](time_t "cpp/chrono/c/time t")` object to a textual representation (function) | | [time](time "cpp/chrono/c/time") | returns the current time of the system as time since epoch (function) | | [C documentation](https://en.cppreference.com/w/c/chrono/clock "c/chrono/clock") for `clock` |
programming_docs
cpp std::chrono::hh_mm_ss<Duration>::hh_mm_ss std::chrono::hh\_mm\_ss<Duration>::hh\_mm\_ss ============================================= | | | | | --- | --- | --- | | ``` constexpr hh_mm_ss() noexcept : hh_mm_ss{Duration::zero()} {} ``` | (1) | | | ``` explicit constexpr hh_mm_ss( Duration d ); ``` | (2) | | Constructs a `hh_mm_ss` object. 1) Constructs a `hh_mm_ss` object corresponding to `Duration::zero()`. 2) Constructs a `hh_mm_ss` object corresponding to `d`: * `is_negative()` returns `d < Duration::zero()`. * `hours()` returns `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::hours](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d))`. * `minutes()` returns `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::minutes](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d) - hours())`. * `seconds()` returns `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::seconds](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d) - hours() - minutes())`. * `subseconds()` returns `abs(d) - hours() - minutes() - seconds()` if `std::chrono::treat_as_floating_point_v<precision::rep>` is `true`; otherwise it returns `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<precision>(abs(d) - hours() - minutes() - seconds())`. ### Parameters | | | | | --- | --- | --- | | d | - | the duration to be broken down. | ### Example cpp std::chrono::hh_mm_ss<Duration>::operator precision, std::chrono::hh_mm_ss<Duration>::to_duration std::chrono::hh\_mm\_ss<Duration>::operator precision, std::chrono::hh\_mm\_ss<Duration>::to\_duration ====================================================================================================== | | | | | --- | --- | --- | | ``` constexpr explicit operator precision() const noexcept; ``` | (1) | | | ``` constexpr precision to_duration() const noexcept; ``` | (2) | | Returns the represented duration. ### Return value The represented duration. ### Example cpp std::chrono::operator<<(std::chrono::hh_mm_ss) std::chrono::operator<<(std::chrono::hh\_mm\_ss) ================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Duration > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::chrono::hh_mm_ss<Duration>& t ); ``` | | (since C++20) | Outputs `t` into the stream `os`. Equivalent to `return os << [std::format](http://en.cppreference.com/w/cpp/utility/format/format)(os.getloc(), STATICALLY_WIDEN<CharT>("{:L%T}"), hms);` where `STATICALLY_WIDEN<CharT>("{:L%T}")` is `"{:L%T}"` if `CharT` is `char`, and `L"{:L%T}"` if `CharT` is `wchar_t`. ### Parameters | | | | | --- | --- | --- | | os | - | the output stream. | | t | - | the time of day to be output. | ### Return value `os`. ### 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 | | --- | --- | --- | --- | | [P2372R3](https://wg21.link/P2372R3) | C++20 | the given locale was used by default | `L` is needed to use the given locale | ### See also | | | | --- | --- | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [std::formatter<std::chrono::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::hh_mm_ss<Duration>::is_negative, std::chrono::hh_mm_ss<Duration>::hours, std::chrono::hh_mm_ss<Duration>::minutes, std::chrono::hh_mm_ss<Duration>::seconds, std::chrono::hh_mm_ss<Duration>::subseconds std::chrono::hh\_mm\_ss<Duration>::is\_negative, std::chrono::hh\_mm\_ss<Duration>::hours, std::chrono::hh\_mm\_ss<Duration>::minutes, std::chrono::hh\_mm\_ss<Duration>::seconds, std::chrono::hh\_mm\_ss<Duration>::subseconds ================================================================================================================================================================================================================================ | | | | | --- | --- | --- | | ``` constexpr bool is_negative() const noexcept; ``` | (1) | | | ``` constexpr std::chrono::hours hours() const noexcept; ``` | (2) | | | ``` constexpr std::chrono::minutes minutes() const noexcept; ``` | (3) | | | ``` constexpr std::chrono::seconds seconds() const noexcept; ``` | (4) | | | ``` constexpr precision subseconds() const noexcept; ``` | (5) | | Obtains the components of the stored "broken down" time. ### Return value Let `d` be the represented duration: 1) `true` if `d` is negative, `false` otherwise. 2) `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::hours](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d))`. 3) `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::minutes](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d) - hours())`. 4) `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<[std::chrono::seconds](http://en.cppreference.com/w/cpp/chrono/duration)>(abs(d) - hours() - minutes())`. 5) `abs(d) - hours() - minutes() - seconds()` if `std::chrono::treat_as_floating_point_v<precision::rep>` is true; otherwise `[std::chrono::duration\_cast](http://en.cppreference.com/w/cpp/chrono/duration/duration_cast)<precision>(abs(d) - hours() - minutes() - seconds())`. ### Example cpp std::chrono::tzdb_list::front std::chrono::tzdb\_list::front ============================== | | | | | --- | --- | --- | | ``` const std::chrono::tzdb& front() const noexcept; ``` | | (since C++20) | Obtains a reference to the first `std::chrono::tzdb` in the list. Simultaneous calls to this function and `[std::chrono::reload\_tzdb](http://en.cppreference.com/w/cpp/chrono/tzdb_functions)()` does not introduce a data race. ### Return value A reference to the first `std::chrono::tzdb` in the list. cpp std::chrono::tzdb_list::erase_after std::chrono::tzdb\_list::erase\_after ===================================== | | | | | --- | --- | --- | | ``` const_iterator erase_after( const_iterator p ); ``` | | (since C++20) | Erases the `std::chrono::tzdb` referred to by the iterator following `p`. The behavior is undefined if that iterator is not dereferenceable. No pointers, references, or iterators are invalidated except for those referring to the erased element. ### Return value An iterator pointing to the element following the erased element, or `end()` if no such element exists. ### Notes `tzdb_list` is intended to be implementable as a singly linked list, and its interface resembles that of `[std::forward\_list](../../container/forward_list "cpp/container/forward list")`. It has no `before_begin()`, however, and so it is not possible to erase the first element. cpp std::chrono::tzdb_list::begin std::chrono::tzdb\_list::begin ============================== | | | | | --- | --- | --- | | ``` const_iterator begin() const noexcept; ``` | | (since C++20) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++20) | Returns an iterator referring to the first `std::chrono::tzdb` in the container. ### Return value An iterator referring to the first `std::chrono::tzdb` in the container. cpp std::chrono::tzdb_list::end, std::chrono::tzdb_list::cend std::chrono::tzdb\_list::end, std::chrono::tzdb\_list::cend =========================================================== | | | | | --- | --- | --- | | ``` const_iterator end() const noexcept; ``` | | (since C++20) | | ``` const_iterator cend() const noexcept; ``` | | (since C++20) | Returns the past-the-end iterator of the `tzdb_list`. Attempting to dereference this iterator results in undefined behavior. ### Return value The past-the-end iterator. cpp std::chrono::operator<<(std::chrono::local_time) std::chrono::operator<<(std::chrono::local\_time) ================================================= | | | | | --- | --- | --- | | ``` template <class CharT, class Traits, class Duration> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::chrono::local_time<Duration>& tp); ``` | | (since C++20) | Outputs `tp` into the stream `os`, as if by `os << [std::chrono::sys\_time](http://en.cppreference.com/w/cpp/chrono/system_clock)<Duration>(tp.time\_since\_epoch());` ### Return value `os`. ### See also | | | | --- | --- | | [operator<<(std::chrono::sys\_time)](../system_clock/operator_ltlt "cpp/chrono/system clock/operator ltlt") (C++20) | performs stream output on a sys\_time (function template) | cpp std::chrono::operator==,<,<=,>,>=,<=>(std::chrono::leap_second) std::chrono::operator==,<,<=,>,>=,<=>(std::chrono::leap\_second) ================================================================ | Defined in header `[<chrono>](../../header/chrono "cpp/header/chrono")` | | | | --- | --- | --- | | ``` constexpr bool operator==( const std::chrono::leap_second& x, const std::chrono::leap_second& y ) noexcept; ``` | (1) | (since C++20) | | ``` constexpr std::strong_ordering operator<=>( const std::chrono::leap_second& x, const std::chrono::leap_second& y ) noexcept; ``` | (2) | (since C++20) | | ``` template< class Duration > constexpr bool operator==( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (3) | (since C++20) | | ``` template< class Duration > constexpr bool operator< ( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (4) | (since C++20) | | ``` template< class Duration > constexpr bool operator< ( const std::chrono::sys_time<Duration>& x, const std::chrono::leap_second& y ) noexcept; ``` | (5) | (since C++20) | | ``` template< class Duration > constexpr bool operator> ( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (6) | (since C++20) | | ``` template< class Duration > constexpr bool operator> ( const std::chrono::sys_time<Duration>& x, const std::chrono::leap_second& y ) noexcept; ``` | (7) | (since C++20) | | ``` template< class Duration > constexpr bool operator<=( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (8) | (since C++20) | | ``` template< class Duration > constexpr bool operator<=( const std::chrono::sys_time<Duration>& x, const std::chrono::leap_second& y ) noexcept; ``` | (9) | (since C++20) | | ``` template< class Duration > constexpr bool operator>=( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (10) | (since C++20) | | ``` template< class Duration > constexpr bool operator>=( const std::chrono::sys_time<Duration>& x, const std::chrono::leap_second& y ) noexcept; ``` | (11) | (since C++20) | | ``` template< class Duration > requires std::three_way_comparable_with< std:chrono::sys_seconds, std::chrono::sys_time<Duration>> constexpr auto operator<=>( const std::chrono::leap_second& x, const std::chrono::sys_time<Duration>& y ) noexcept; ``` | (12) | (since C++20) | Compares the date and time represented by the objects `x` and `y`. Return type of (12) is deduced from `x.date() <=> y`, and hence the three-way comparison result type of `[std::chrono::seconds](../duration "cpp/chrono/duration")` and `Duration`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Return value 1) `x.date() == y.date()` 2) `x.date() <=> y.date()` 3) `x.date() == y` 4) `x.date() < y` 5) `x < y.date()` 6) `x.date() > y` 7) `x > y.date()` 8) `x.date() <= y` 9) `x <= y.date()` 10) `x.date() >= y` 11) `x >= y.date()` 12) `x.date() <=> y` cpp std::chrono::leap_second::date std::chrono::leap\_second::date =============================== | | | | | --- | --- | --- | | ``` constexpr std::chrono::sys_seconds date() const noexcept; ``` | | | Obtains the date and time of the leap second insertion. ### Return value A `std::chrono::sys_seconds` representing the date and time at which the leap second was inserted. cpp std::literals::complex_literals Symbol Index std::literals::complex\_literals Symbol Index ============================================= This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::literals::complex_literals::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. ### Notes These operators are declared in the namespace `std::literals::complex_literals`, where both `literals` and `complex_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::complex_literals`, and `using namespace std::literals::complex_literals`. `[I](#I)` ----------- ### I [`i`](../numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") (since C++14) [`if`](../numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") (since C++14) [`il`](../numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") (since C++14) cpp std::filesystem Symbol Index std::filesystem Symbol Index ============================ This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::filesystem::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[A](#A) [B](#B) [C](#C) [D](#D) [E](#E) [F](#F) [H](#H) [I](#I) [L](#L) [P](#P) [R](#R) [S](#S) [T](#T) [U](#U) [W](#W)` ----------------------------------------------------------------------------------------------------------------------------------------- ### A [`absolute()`](../filesystem/absolute "cpp/filesystem/absolute") (since C++17) ### B [`begin()`](../filesystem/directory_iterator/begin "cpp/filesystem/directory iterator/begin") (std::filesystem::directory\_iterator) (since C++17) [`begin()`](../filesystem/recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") (std::filesystem::recursive\_directory\_iterator) (since C++17) ### C [`canonical()`](../filesystem/canonical "cpp/filesystem/canonical") (since C++17) [`copy()`](../filesystem/copy "cpp/filesystem/copy") (since C++17) [`copy_file()`](../filesystem/copy_file "cpp/filesystem/copy file") (since C++17) [`copy_options`](../filesystem/copy_options "cpp/filesystem/copy options") (since C++17) [`copy_symlink()`](../filesystem/copy_symlink "cpp/filesystem/copy symlink") (since C++17) [`create_directory()`](../filesystem/create_directory "cpp/filesystem/create directory") (since C++17) [`create_directory_symlink()`](../filesystem/create_symlink "cpp/filesystem/create symlink") (since C++17) [`create_directories()`](../filesystem/create_directory "cpp/filesystem/create directory") (since C++17) [`create_hard_link()`](../filesystem/create_hard_link "cpp/filesystem/create hard link") (since C++17) [`create_symlink()`](../filesystem/create_symlink "cpp/filesystem/create symlink") (since C++17) [`current_path()`](../filesystem/current_path "cpp/filesystem/current path") (since C++17) ### D [`directory_entry`](../filesystem/directory_entry "cpp/filesystem/directory entry") (since C++17) [`directory_iterator`](../filesystem/directory_iterator "cpp/filesystem/directory iterator") (since C++17) [`directory_options`](../filesystem/directory_options "cpp/filesystem/directory options") (since C++17) ### E [`end()`](../filesystem/directory_iterator/begin "cpp/filesystem/directory iterator/begin") (std::filesystem::directory\_iterator) (since C++17) [`end()`](../filesystem/recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") (std::filesystem::recursive\_directory\_iterator) (since C++17) [`equivalent()`](../filesystem/equivalent "cpp/filesystem/equivalent") (since C++17) [`exists()`](../filesystem/exists "cpp/filesystem/exists") (since C++17) ### F [`file_size()`](../filesystem/file_size "cpp/filesystem/file size") (since C++17) [`file_status`](../filesystem/file_status "cpp/filesystem/file status") (since C++17) [`filesystem_error`](../filesystem/filesystem_error "cpp/filesystem/filesystem error") (since C++17) [`file_time_type`](../filesystem/file_time_type "cpp/filesystem/file time type") (since C++17) [`file_type`](../filesystem/file_type "cpp/filesystem/file type") (since C++17) ### H [`hard_link_count()`](../filesystem/hard_link_count "cpp/filesystem/hard link count") (since C++17) [`hash_value()`](../filesystem/path/hash_value "cpp/filesystem/path/hash value") (since C++17) ### I [`is_block_file()`](../filesystem/is_block_file "cpp/filesystem/is block file") (since C++17) [`is_character_file()`](../filesystem/is_character_file "cpp/filesystem/is character file") (since C++17) [`is_directory()`](../filesystem/is_directory "cpp/filesystem/is directory") (since C++17) [`is_empty()`](../filesystem/is_empty "cpp/filesystem/is empty") (since C++17) [`is_fifo()`](../filesystem/is_fifo "cpp/filesystem/is fifo") (since C++17) [`is_other()`](../filesystem/is_other "cpp/filesystem/is other") (since C++17) [`is_regular_file()`](../filesystem/is_regular_file "cpp/filesystem/is regular file") (since C++17) [`is_socket()`](../filesystem/is_socket "cpp/filesystem/is socket") (since C++17) [`is_symlink()`](../filesystem/is_symlink "cpp/filesystem/is symlink") (since C++17) ### L [`last_write_time()`](../filesystem/last_write_time "cpp/filesystem/last write time") (since C++17) ### P [`path`](../filesystem/path "cpp/filesystem/path") (since C++17) [`permissions()`](../filesystem/permissions "cpp/filesystem/permissions") (since C++17) [`perms`](../filesystem/perms "cpp/filesystem/perms") (since C++17) [`perm_options`](../filesystem/perm_options "cpp/filesystem/perm options") (since C++17) [`proximate()`](../filesystem/relative "cpp/filesystem/relative") (since C++17) ### R [`read_symlink()`](../filesystem/read_symlink "cpp/filesystem/read symlink") (since C++17) [`recursive_directory_iterator`](../filesystem/recursive_directory_iterator "cpp/filesystem/recursive directory iterator") (since C++17) [`relative()`](../filesystem/relative "cpp/filesystem/relative") (since C++17) [`remove()`](../filesystem/remove "cpp/filesystem/remove") (since C++17) [`remove_all()`](../filesystem/remove "cpp/filesystem/remove") (since C++17) [`rename()`](../filesystem/rename "cpp/filesystem/rename") (since C++17) [`resize_file()`](../filesystem/resize_file "cpp/filesystem/resize file") (since C++17) ### S [`space()`](../filesystem/space "cpp/filesystem/space") (since C++17) [`space_info`](../filesystem/space_info "cpp/filesystem/space info") (since C++17) [`status()`](../filesystem/status "cpp/filesystem/status") (since C++17) [`status_known()`](../filesystem/status_known "cpp/filesystem/status known") (since C++17) [`swap()`](../filesystem/path/swap "cpp/filesystem/path/swap") (since C++17) [`symlink_status()`](../filesystem/status "cpp/filesystem/status") (since C++17) ### T [`temp_directory_path()`](../filesystem/temp_directory_path "cpp/filesystem/temp directory path") (since C++17) ### U [`u8path<>()`](../filesystem/path/u8path "cpp/filesystem/path/u8path") (since C++17)(deprecated in C++20) ### W [`weakly_canonical()`](../filesystem/canonical "cpp/filesystem/canonical") (since C++17)
programming_docs
cpp std::execution Symbol Index std::execution Symbol Index =========================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::execution::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[P](#P) [S](#S) [U](#U)` ----------------------------- ### P [`par`](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") (since C++17) [`par_unseq`](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") (since C++17) [`parallel_policy`](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") (since C++17) [`parallel_unsequenced_policy`](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") (since C++17) ### S [`seq`](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") (since C++17) [`sequenced_policy`](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") (since C++17) ### U [`unseq`](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") (since C++20) [`unsequenced_policy`](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") (since C++20) cpp std::literals Symbol Index std::literals Symbol Index ========================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::literals::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[C](#C) [S](#S)` -------------------- ### C ▶ [`chrono_literals`](chrono_literals "cpp/symbol index/chrono literals") (since C++14) ▶ [`complex_literals`](complex_literals "cpp/symbol index/complex literals") (since C++14) ### S ▶ [`string_literals`](string_literals "cpp/symbol index/string literals") (since C++14) ▶ [`string_view_literals`](string_view_literals "cpp/symbol index/string view literals") (since C++17) cpp std::placeholders Symbol Index std::placeholders Symbol Index ============================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::placeholders::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[\_](#.28underscore.29)` --------------------------- ### \_ (underscore) [`_1, _2, ..., _N`](../utility/functional/placeholders "cpp/utility/functional/placeholders") (since C++11) cpp std::numbers Symbol Index std::numbers Symbol Index ========================= This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::numbers::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[E](#E) [I](#I) [L](#L) [P](#P) [S](#S)` ----------------------------------------------- ### E [`e`](../numeric/constants "cpp/numeric/constants") (since C++20) [`e_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`egamma`](../numeric/constants "cpp/numeric/constants") (since C++20) [`egamma_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) ### I [`inv_pi`](../numeric/constants "cpp/numeric/constants") (since C++20) [`inv_pi_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`inv_sqrt3`](../numeric/constants "cpp/numeric/constants") (since C++20) [`inv_sqrt3_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`inv_sqrtpi`](../numeric/constants "cpp/numeric/constants") (since C++20) [`inv_sqrtpi_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) ### L [`ln10`](../numeric/constants "cpp/numeric/constants") (since C++20) [`ln10_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`ln2`](../numeric/constants "cpp/numeric/constants") (since C++20) [`ln2_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`log10e`](../numeric/constants "cpp/numeric/constants") (since C++20) [`log10e_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`log2e`](../numeric/constants "cpp/numeric/constants") (since C++20) [`log2e_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) ### P [`phi`](../numeric/constants "cpp/numeric/constants") (since C++20) [`phi_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`pi`](../numeric/constants "cpp/numeric/constants") (since C++20) [`pi_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) ### S [`sqrt2`](../numeric/constants "cpp/numeric/constants") (since C++20) [`sqrt2_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) [`sqrt3`](../numeric/constants "cpp/numeric/constants") (since C++20) [`sqrt3_v<>`](../numeric/constants "cpp/numeric/constants") (since C++20) cpp std::ranges Symbol Index std::ranges Symbol Index ======================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::ranges::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[A](#A) [B](#B) [C](#C) [D](#D) [E](#E) [F](#F) [G](#G) [I](#I) [J](#J) [K](#K) [L](#L) [M](#M) [N](#N) [O](#O) [P](#P) [R](#R) [S](#S) [T](#T) [U](#U) [V](#V) [W](#W) [Z](#Z)` -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### A [`adjacent_find`](../algorithm/ranges/adjacent_find "cpp/algorithm/ranges/adjacent find") (since C++23) [`adjacent_transform_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/adjacent_transform_view&action=edit&redlink=1 "cpp/ranges/adjacent transform view (page does not exist)") (since C++23) [`adjacent_view<>`](../ranges/adjacent_view "cpp/ranges/adjacent view") (since C++23) [`advance`](../iterator/ranges/advance "cpp/iterator/ranges/advance") (since C++20) [`all_of`](../algorithm/ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (since C++20) [`any_of`](../algorithm/ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (since C++20) [`as_const_view<>`](../ranges/as_const_view "cpp/ranges/as const view") (since C++23) [`as_rvalue_view<>`](../ranges/as_rvalue_view "cpp/ranges/as rvalue view") (since C++23) ### B [`basic_istream_view<>`](../ranges/basic_istream_view "cpp/ranges/basic istream view") (since C++20) [`begin`](../ranges/begin "cpp/ranges/begin") (since C++20) [`bidirectional_range<>`](../ranges/bidirectional_range "cpp/ranges/bidirectional range") (since C++20) [`binary_transform_result<>`](../algorithm/ranges/transform "cpp/algorithm/ranges/transform") (since C++20) [`borrowed_iterator_t<>`](../ranges/borrowed_iterator_t "cpp/ranges/borrowed iterator t") (since C++20) [`borrowed_range<>`](../ranges/borrowed_range "cpp/ranges/borrowed range") (since C++20) [`borrowed_subrange_t<>`](../ranges/borrowed_iterator_t "cpp/ranges/borrowed iterator t") (since C++20) ### C [`cartesian_product_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/cartesian_product_view&action=edit&redlink=1 "cpp/ranges/cartesian product view (page does not exist)") (since C++23) [`cbegin`](../ranges/cbegin "cpp/ranges/cbegin") (since C++20) [`cdata`](../ranges/cdata "cpp/ranges/cdata") (since C++20) [`chunk_by_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_by_view&action=edit&redlink=1 "cpp/ranges/chunk by view (page does not exist)") (since C++23) [`chunk_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_view&action=edit&redlink=1 "cpp/ranges/chunk view (page does not exist)") (since C++23) [`cend`](../ranges/cend "cpp/ranges/cend") (since C++20) [`clamp`](../algorithm/ranges/clamp "cpp/algorithm/ranges/clamp") (since C++20) [`common_range<>`](../ranges/common_range "cpp/ranges/common range") (since C++20) [`common_view<>`](../ranges/common_view "cpp/ranges/common view") (since C++20) [`const_iterator_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++23) [`constant_range<>`](../ranges/constant_range "cpp/ranges/constant range") (since C++23) [`construct_at`](../memory/ranges/construct_at "cpp/memory/ranges/construct at") (since C++20) [`contains`](../algorithm/ranges/contains "cpp/algorithm/ranges/contains") (since C++23) [`contains_subrange`](../algorithm/ranges/contains "cpp/algorithm/ranges/contains") (since C++23) [`contiguous_range<>`](../ranges/contiguous_range "cpp/ranges/contiguous range") (since C++20) [`copy`](../algorithm/ranges/copy "cpp/algorithm/ranges/copy") (since C++20) [`copy_backward`](../algorithm/ranges/copy_backward "cpp/algorithm/ranges/copy backward") (since C++20) [`copy_backward_result<>`](../algorithm/ranges/copy_backward "cpp/algorithm/ranges/copy backward") (since C++20) [`copy_if`](../algorithm/ranges/copy "cpp/algorithm/ranges/copy") (since C++20) [`copy_if_result<>`](../algorithm/ranges/copy "cpp/algorithm/ranges/copy") (since C++20) [`copy_n`](../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n") (since C++20) [`copy_n_result<>`](../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n") (since C++20) [`copy_result<>`](../algorithm/ranges/copy "cpp/algorithm/ranges/copy") (since C++20) [`count`](../algorithm/ranges/count "cpp/algorithm/ranges/count") (since C++20) [`count_if`](../algorithm/ranges/count "cpp/algorithm/ranges/count") (since C++20) [`crbegin`](../ranges/crbegin "cpp/ranges/crbegin") (since C++20) [`crend`](../ranges/crend "cpp/ranges/crend") (since C++20) ### D [`dangling`](../ranges/dangling "cpp/ranges/dangling") (since C++20) [`data`](../ranges/data "cpp/ranges/data") (since C++20) [`destroy`](../memory/ranges/destroy "cpp/memory/ranges/destroy") (since C++20) [`destroy_at`](../memory/ranges/destroy_at "cpp/memory/ranges/destroy at") (since C++20) [`destroy_n`](../memory/ranges/destroy_n "cpp/memory/ranges/destroy n") (since C++20) [`disable_sized_range<>`](../ranges/sized_range "cpp/ranges/sized range") (since C++20) [`distance`](../iterator/ranges/distance "cpp/iterator/ranges/distance") (since C++20) [`drop_view<>`](../ranges/drop_view "cpp/ranges/drop view") (since C++20) [`drop_while_view<>`](../ranges/drop_while_view "cpp/ranges/drop while view") (since C++20) ### E [`elements_view<>`](../ranges/elements_view "cpp/ranges/elements view") (since C++20) [`empty`](../ranges/empty "cpp/ranges/empty") (since C++20) [`empty_view<>`](../ranges/empty_view "cpp/ranges/empty view") (since C++20) [`enable_borrowed_range<>`](../ranges/borrowed_range "cpp/ranges/borrowed range") (since C++20) [`enable_view<>`](../ranges/view "cpp/ranges/view") (since C++20) [`end`](../ranges/end "cpp/ranges/end") (since C++20) [`ends_with`](../algorithm/ranges/ends_with "cpp/algorithm/ranges/ends with") (since C++23) [`equal`](../algorithm/ranges/equal "cpp/algorithm/ranges/equal") (since C++20) [`equal_to`](../utility/functional/ranges/equal_to "cpp/utility/functional/ranges/equal to") (since C++20) ### F [`fill`](../algorithm/ranges/fill "cpp/algorithm/ranges/fill") (since C++20) [`fill_n`](../algorithm/ranges/fill_n "cpp/algorithm/ranges/fill n") (since C++20) [`filter_view<>`](../ranges/filter_view "cpp/ranges/filter view") (since C++20) [`find`](../algorithm/ranges/find "cpp/algorithm/ranges/find") (since C++20) [`find_end`](../algorithm/ranges/find_end "cpp/algorithm/ranges/find end") (since C++20) [`find_first_of`](../algorithm/ranges/find_first_of "cpp/algorithm/ranges/find first of") (since C++20) [`find_if`](../algorithm/ranges/find "cpp/algorithm/ranges/find") (since C++20) [`find_if_not`](../algorithm/ranges/find "cpp/algorithm/ranges/find") (since C++20) [`find_last`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last") (since C++23) [`find_last_if`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last") (since C++23) [`find_last_if_not`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last") (since C++23) [`fold_left`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_left&action=edit&redlink=1 "cpp/algorithm/ranges/fold left (page does not exist)") (since C++23) [`fold_left_first`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_left_first&action=edit&redlink=1 "cpp/algorithm/ranges/fold left first (page does not exist)") (since C++23) [`fold_left_first_with_iter`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_left_first_with_iter&action=edit&redlink=1 "cpp/algorithm/ranges/fold left first with iter (page does not exist)") (since C++23) [`fold_left_with_iter`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_left_with_iter&action=edit&redlink=1 "cpp/algorithm/ranges/fold left with iter (page does not exist)") (since C++23) [`fold_right`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_right&action=edit&redlink=1 "cpp/algorithm/ranges/fold right (page does not exist)") (since C++23) [`fold_right_last`](https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/ranges/fold_right_last&action=edit&redlink=1 "cpp/algorithm/ranges/fold right last (page does not exist)") (since C++23) [`for_each`](../algorithm/ranges/for_each "cpp/algorithm/ranges/for each") (since C++20) [`for_each_n`](../algorithm/ranges/for_each_n "cpp/algorithm/ranges/for each n") (since C++20) [`for_each_n_result<>`](../algorithm/ranges/for_each_n "cpp/algorithm/ranges/for each n") (since C++20) [`for_each_result<>`](../algorithm/ranges/for_each "cpp/algorithm/ranges/for each") (since C++20) [`forward_range<>`](../ranges/forward_range "cpp/ranges/forward range") (since C++20) ### G [`generate`](../algorithm/ranges/generate "cpp/algorithm/ranges/generate") (since C++20) [`generate_n`](../algorithm/ranges/generate_n "cpp/algorithm/ranges/generate n") (since C++20) [`get<>()`](../ranges/subrange/get "cpp/ranges/subrange/get") (std::ranges::subrange) (since C++20) [`greater`](../utility/functional/ranges/greater "cpp/utility/functional/ranges/greater") (since C++20) [`greater_equal`](../utility/functional/ranges/greater_equal "cpp/utility/functional/ranges/greater equal") (since C++20) ### I [`in_found_result<>`](../algorithm/ranges/return_types/in_found_result "cpp/algorithm/ranges/return types/in found result") (since C++20) [`in_fun_result<>`](../algorithm/ranges/return_types/in_fun_result "cpp/algorithm/ranges/return types/in fun result") (since C++20) [`in_in_out_result<>`](../algorithm/ranges/return_types/in_in_out_result "cpp/algorithm/ranges/return types/in in out result") (since C++20) [`in_in_result<>`](../algorithm/ranges/return_types/in_in_result "cpp/algorithm/ranges/return types/in in result") (since C++20) [`in_out_out_result<>`](../algorithm/ranges/return_types/in_out_out_result "cpp/algorithm/ranges/return types/in out out result") (since C++20) [`in_out_result<>`](../algorithm/ranges/return_types/in_out_result "cpp/algorithm/ranges/return types/in out result") (since C++20) [`in_value_result<>`](../algorithm/ranges/return_types/in_value_result "cpp/algorithm/ranges/return types/in value result") (since C++23) [`includes`](../algorithm/ranges/includes "cpp/algorithm/ranges/includes") (since C++20) [`inplace_merge`](../algorithm/ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (since C++20) [`input_range<>`](../ranges/input_range "cpp/ranges/input range") (since C++20) [`iota`](../algorithm/ranges/iota "cpp/algorithm/ranges/iota") (since C++23) [`iota_result<>`](../algorithm/ranges/iota "cpp/algorithm/ranges/iota") (since C++23) [`iota_view<>`](../ranges/iota_view "cpp/ranges/iota view") (since C++20) [`is_heap`](../algorithm/ranges/is_heap "cpp/algorithm/ranges/is heap") (since C++20) [`is_heap_until`](../algorithm/ranges/is_heap_until "cpp/algorithm/ranges/is heap until") (since C++20) [`is_partitioned`](../algorithm/ranges/is_partitioned "cpp/algorithm/ranges/is partitioned") (since C++20) [`is_permutation`](../algorithm/ranges/is_permutation "cpp/algorithm/ranges/is permutation") (since C++20) [`is_sorted`](../algorithm/ranges/is_sorted "cpp/algorithm/ranges/is sorted") (since C++20) [`is_sorted_until`](../algorithm/ranges/is_sorted_until "cpp/algorithm/ranges/is sorted until") (since C++20) [`istream_view<>`](../ranges/basic_istream_view "cpp/ranges/basic istream view") (since C++20) [`iter_move`](../iterator/ranges/iter_move "cpp/iterator/ranges/iter move") (since C++20) [`iter_swap`](../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap") (since C++20) [`iterator_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) ### J [`join_view<>`](../ranges/join_view "cpp/ranges/join view") (since C++20) [`join_with_view<>`](../ranges/join_with_view "cpp/ranges/join with view") (since C++23) . ### K [`keys_view<>`](../ranges/keys_view "cpp/ranges/keys view") (since C++20) ### L [`lazy_split_view<>`](../ranges/lazy_split_view "cpp/ranges/lazy split view") (since C++20) [`less`](../utility/functional/ranges/less "cpp/utility/functional/ranges/less") (since C++20) [`less_equal`](../utility/functional/ranges/less_equal "cpp/utility/functional/ranges/less equal") (since C++20) [`lexicographical_compare`](../algorithm/ranges/lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (since C++20) ### M [`make_heap`](../algorithm/ranges/make_heap "cpp/algorithm/ranges/make heap") (since C++20) [`max`](../algorithm/ranges/max "cpp/algorithm/ranges/max") (since C++20) [`max_element`](../algorithm/ranges/max_element "cpp/algorithm/ranges/max element") (since C++20) [`merge`](../algorithm/ranges/merge "cpp/algorithm/ranges/merge") (since C++20) [`merge_result<>`](../algorithm/ranges/merge "cpp/algorithm/ranges/merge") (since C++20) [`min`](../algorithm/ranges/min "cpp/algorithm/ranges/min") (since C++20) [`min_element`](../algorithm/ranges/min_element "cpp/algorithm/ranges/min element") (since C++20) [`min_max_result<>`](../algorithm/ranges/return_types/min_max_result "cpp/algorithm/ranges/return types/min max result") (since C++20) [`minmax`](../algorithm/ranges/minmax "cpp/algorithm/ranges/minmax") (since C++20) [`minmax_element`](../algorithm/ranges/minmax_element "cpp/algorithm/ranges/minmax element") (since C++20) [`minmax_element_result<>`](../algorithm/ranges/minmax_element "cpp/algorithm/ranges/minmax element") (since C++20) [`minmax_result<>`](../algorithm/ranges/minmax "cpp/algorithm/ranges/minmax") (since C++20) [`mismatch`](../algorithm/ranges/mismatch "cpp/algorithm/ranges/mismatch") (since C++20) [`mismatch_result<>`](../algorithm/ranges/mismatch "cpp/algorithm/ranges/mismatch") (since C++20) [`move`](../algorithm/ranges/move "cpp/algorithm/ranges/move") (since C++20) [`move_backward`](../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward") (since C++20) [`move_backward_result<>`](../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward") (since C++20) [`move_result<>`](../algorithm/ranges/move "cpp/algorithm/ranges/move") (since C++20) ### N [`next`](../iterator/ranges/next "cpp/iterator/ranges/next") (since C++20) [`next_permutation`](../algorithm/ranges/next_permutation "cpp/algorithm/ranges/next permutation") (since C++20) [`next_permutation_result<>`](../algorithm/ranges/next_permutation "cpp/algorithm/ranges/next permutation") (since C++20) [`none_of`](../algorithm/ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (since C++20) [`not_equal_to`](../utility/functional/ranges/not_equal_to "cpp/utility/functional/ranges/not equal to") (since C++20) [`nth_element`](../algorithm/ranges/nth_element "cpp/algorithm/ranges/nth element") (since C++20) ### O [`out_value_result<>`](../algorithm/ranges/return_types/out_value_result "cpp/algorithm/ranges/return types/out value result") (since C++23) [`output_range<>`](../ranges/output_range "cpp/ranges/output range") (since C++20) [`owning_view<>`](../ranges/owning_view "cpp/ranges/owning view") (since C++20) ### P [`partial_sort`](../algorithm/ranges/partial_sort "cpp/algorithm/ranges/partial sort") (since C++20) [`partial_sort_copy`](../algorithm/ranges/partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (since C++20) [`partial_sort_copy_result<>`](../algorithm/ranges/partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (since C++20) [`partition`](../algorithm/ranges/partition "cpp/algorithm/ranges/partition") (since C++20) [`partition_copy`](../algorithm/ranges/partition_copy "cpp/algorithm/ranges/partition copy") (since C++20) [`partition_copy_result<>`](../algorithm/ranges/partition_copy "cpp/algorithm/ranges/partition copy") (since C++20) [`partition_point`](../algorithm/ranges/partition_point "cpp/algorithm/ranges/partition point") (since C++20) [`pop_heap`](../algorithm/ranges/pop_heap "cpp/algorithm/ranges/pop heap") (since C++20) [`prev`](../iterator/ranges/prev "cpp/iterator/ranges/prev") (since C++20) [`prev_permutation`](../algorithm/ranges/prev_permutation "cpp/algorithm/ranges/prev permutation") (since C++20) [`prev_permutation_result<>`](../algorithm/ranges/prev_permutation "cpp/algorithm/ranges/prev permutation") (since C++20) [`push_heap`](../algorithm/ranges/push_heap "cpp/algorithm/ranges/push heap") (since C++20) ### R [`random_access_range<>`](../ranges/random_access_range "cpp/ranges/random access range") (since C++20) [`range<>`](../ranges/range "cpp/ranges/range") (since C++20) [`range_adaptor_closure<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/range_adaptor_closure&action=edit&redlink=1 "cpp/ranges/range adaptor closure (page does not exist)") (since C++23) [`range_const_reference_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++23) [`range_difference_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`range_reference_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`range_rvalue_reference_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`range_size_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`range_value_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`rbegin`](../ranges/rbegin "cpp/ranges/rbegin") (since C++20) [`ref_view<>`](../ranges/ref_view "cpp/ranges/ref view") (since C++20) [`remove`](../algorithm/ranges/remove "cpp/algorithm/ranges/remove") (since C++20) [`remove_copy`](../algorithm/ranges/remove_copy "cpp/algorithm/ranges/remove copy") (since C++20) [`remove_copy_if`](../algorithm/ranges/remove_copy "cpp/algorithm/ranges/remove copy") (since C++20) [`remove_copy_if_result<>`](../algorithm/ranges/remove_copy "cpp/algorithm/ranges/remove copy") (since C++20) [`remove_copy_result<>`](../algorithm/ranges/remove_copy "cpp/algorithm/ranges/remove copy") (since C++20) [`remove_if`](../algorithm/ranges/remove "cpp/algorithm/ranges/remove") (since C++20) [`rend`](../ranges/rend "cpp/ranges/rend") (since C++20) [`repeat_view<>`](../ranges/repeat_view "cpp/ranges/repeat view") (since C++23) [`replace`](../algorithm/ranges/replace "cpp/algorithm/ranges/replace") (since C++20) [`replace_copy`](../algorithm/ranges/replace_copy "cpp/algorithm/ranges/replace copy") (since C++20) [`replace_copy_if`](../algorithm/ranges/replace_copy "cpp/algorithm/ranges/replace copy") (since C++20) [`replace_copy_if_result<>`](../algorithm/ranges/replace_copy "cpp/algorithm/ranges/replace copy") (since C++20) [`replace_copy_result<>`](../algorithm/ranges/replace_copy "cpp/algorithm/ranges/replace copy") (since C++20) [`replace_if`](../algorithm/ranges/replace "cpp/algorithm/ranges/replace") (since C++20) [`reverse`](../algorithm/ranges/reverse "cpp/algorithm/ranges/reverse") (since C++20) [`reverse_copy`](../algorithm/ranges/reverse_copy "cpp/algorithm/ranges/reverse copy") (since C++20) [`reverse_copy_result<>`](../algorithm/ranges/reverse_copy "cpp/algorithm/ranges/reverse copy") (since C++20) [`reverse_view<>`](../ranges/reverse_view "cpp/ranges/reverse view") (since C++20) [`rotate`](../algorithm/ranges/rotate "cpp/algorithm/ranges/rotate") (since C++20) [`rotate_copy`](../algorithm/ranges/rotate_copy "cpp/algorithm/ranges/rotate copy") (since C++20) [`rotate_copy_result<>`](../algorithm/ranges/rotate_copy "cpp/algorithm/ranges/rotate copy") (since C++20) ### S [`sample`](../algorithm/ranges/sample "cpp/algorithm/ranges/sample") (since C++20) [`search`](../algorithm/ranges/search "cpp/algorithm/ranges/search") (since C++20) [`search_n`](../algorithm/ranges/search_n "cpp/algorithm/ranges/search n") (since C++20) [`sentinel_t<>`](../ranges/iterator_t "cpp/ranges/iterator t") (since C++20) [`set_difference`](../algorithm/ranges/set_difference "cpp/algorithm/ranges/set difference") (since C++20) [`set_difference_result<>`](../algorithm/ranges/set_difference "cpp/algorithm/ranges/set difference") (since C++20) [`set_intersection`](../algorithm/ranges/set_intersection "cpp/algorithm/ranges/set intersection") (since C++20) [`set_intersection_result<>`](../algorithm/ranges/set_intersection "cpp/algorithm/ranges/set intersection") (since C++20) [`set_symmetric_difference`](../algorithm/ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (since C++20) [`set_symmetric_difference_result<>`](../algorithm/ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (since C++20) [`set_union`](../algorithm/ranges/set_union "cpp/algorithm/ranges/set union") (since C++20) [`set_union_result<>`](../algorithm/ranges/set_union "cpp/algorithm/ranges/set union") (since C++20) [`shift_left`](../algorithm/ranges/shift "cpp/algorithm/ranges/shift") (since C++23) [`shift_right`](../algorithm/ranges/shift "cpp/algorithm/ranges/shift") (since C++23) [`shuffle`](../algorithm/ranges/shuffle "cpp/algorithm/ranges/shuffle") (since C++20) [`single_view<>`](../ranges/single_view "cpp/ranges/single view") (since C++20) [`size`](../ranges/size "cpp/ranges/size") (since C++20) [`sized_range<>`](../ranges/sized_range "cpp/ranges/sized range") (since C++20) [`sort`](../algorithm/ranges/sort "cpp/algorithm/ranges/sort") (since C++20) [`sort_heap`](../algorithm/ranges/sort_heap "cpp/algorithm/ranges/sort heap") (since C++20) [`slide_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/slide_view&action=edit&redlink=1 "cpp/ranges/slide view (page does not exist)") (since C++23) [`split_view<>`](../ranges/split_view "cpp/ranges/split view") (since C++20) [`ssize`](../ranges/ssize "cpp/ranges/ssize") (since C++20) [`stable_partition`](../algorithm/ranges/stable_partition "cpp/algorithm/ranges/stable partition") (since C++20) [`stable_sort`](../algorithm/ranges/stable_sort "cpp/algorithm/ranges/stable sort") (since C++20) [`starts_with`](../algorithm/ranges/starts_with "cpp/algorithm/ranges/starts with") (since C++23) [`stride_view<>`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/stride_view&action=edit&redlink=1 "cpp/ranges/stride view (page does not exist)") (since C++23) [`subrange<>`](../ranges/subrange "cpp/ranges/subrange") (since C++20) [`subrange_kind`](../ranges/subrange_kind "cpp/ranges/subrange kind") (since C++20) [`swap`](../utility/ranges/swap "cpp/utility/ranges/swap") (since C++20) [`swap_ranges`](../algorithm/ranges/swap_ranges "cpp/algorithm/ranges/swap ranges") (since C++20) [`swap_ranges_result<>`](../algorithm/ranges/swap_ranges "cpp/algorithm/ranges/swap ranges") (since C++20) ### T [`take_view<>`](../ranges/take_view "cpp/ranges/take view") (since C++20) [`take_while_view<>`](../ranges/take_while_view "cpp/ranges/take while view") (since C++20) [`transform`](../algorithm/ranges/transform "cpp/algorithm/ranges/transform") (since C++20) [`to<>`](../ranges/to "cpp/ranges/to") (since C++23) [`transform_view<>`](../ranges/transform_view "cpp/ranges/transform view") (since C++20) ### U [`unary_transform_result<>`](../algorithm/ranges/transform "cpp/algorithm/ranges/transform") (since C++20) [`uninitialized_copy`](../memory/ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy") (since C++20) [`uninitialized_copy_n`](../memory/ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n") (since C++20) [`uninitialized_copy_n_result<>`](../memory/ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n") (since C++20) [`uninitialized_copy_result<>`](../memory/ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy") (since C++20) [`uninitialized_default_construct`](../memory/ranges/uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct") (since C++20) [`uninitialized_default_construct_n`](../memory/ranges/uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n") (since C++20) [`uninitialized_fill`](../memory/ranges/uninitialized_fill "cpp/memory/ranges/uninitialized fill") (since C++20) [`uninitialized_fill_n`](../memory/ranges/uninitialized_fill_n "cpp/memory/ranges/uninitialized fill n") (since C++20) [`uninitialized_move`](../memory/ranges/uninitialized_move "cpp/memory/ranges/uninitialized move") (since C++20) [`uninitialized_move_n`](../memory/ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n") (since C++20) [`uninitialized_move_n_result<>`](../memory/ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n") (since C++20) [`uninitialized_move_result<>`](../memory/ranges/uninitialized_move "cpp/memory/ranges/uninitialized move") (since C++20) [`uninitialized_value_construct`](../memory/ranges/uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct") (since C++20) [`uninitialized_value_construct_n`](../memory/ranges/uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n") (since C++20) [`unique`](../algorithm/ranges/unique "cpp/algorithm/ranges/unique") (since C++20) [`unique_copy`](../algorithm/ranges/unique_copy "cpp/algorithm/ranges/unique copy") (since C++20) [`unique_copy_result<>`](../algorithm/ranges/unique_copy "cpp/algorithm/ranges/unique copy") (since C++20) ### V [`values_view<>`](../ranges/values_view "cpp/ranges/values view") (since C++20) [`view<>`](../ranges/view "cpp/ranges/view") (since C++20) [`view_base`](../ranges/view "cpp/ranges/view") (since C++20) [`view_interface<>`](../ranges/view_interface "cpp/ranges/view interface") (since C++20) [`viewable_range<>`](../ranges/viewable_range "cpp/ranges/viewable range") (since C++20) ▶ [`views`](views "cpp/symbol index/views") (since C++20) ### W [`wistream_view<>`](../ranges/basic_istream_view "cpp/ranges/basic istream view") (since C++20) ### Z [`zip_transform_view<>`](../ranges/zip_transform_view "cpp/ranges/zip transform view") (since C++23) [`zip_view<>`](../ranges/zip_view "cpp/ranges/zip view") (since C++23)
programming_docs
cpp std::literals::string_literals Symbol Index std::literals::string\_literals Symbol Index ============================================ This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::literals::string_literals::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. ### Notes These operators are declared in the namespace `std::literals::string_literals`, where both `literals` and `string_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::string_literals`, and `using namespace std::literals::string_literals`. `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` also defines `operator""s`, to represent literal seconds, but it is an arithmetic literal: `10.0s` and `10s` is ten seconds, but `"10"s` is a string. `[S](#S)` ----------- ### S [`s`](../string/basic_string/operator%22%22s "cpp/string/basic string/operator\"\"s") (since C++14) cpp std::regex_constants Symbol Index std::regex\_constants Symbol Index ================================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::regex_constants::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[A](#A) [B](#B) [C](#C) [E](#E) [F](#F) [G](#G) [I](#I) [M](#M) [N](#N) [O](#O) [S](#S)` ----------------------------------------------------------------------------------------------------- ### A [`awk`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### B [`basic`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### C [`collate`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### E [`ECMAScript`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) [`egrep`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) [`error_backref`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_badbrace`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_badrepeat`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_brace`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_brack`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_collate`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_complexity`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_ctype`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_escape`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_paren`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_range`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_space`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_stack`](../regex/error_type "cpp/regex/error type") (since C++11) [`error_type`](../regex/error_type "cpp/regex/error type") (since C++11) [`extended`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### F [`format_default`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`format_first_only`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`format_no_copy`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`format_sed`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) ### G [`grep`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### I [`icase`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### M [`match_any`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_continuous`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_default`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_flag_type`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_not_bol`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_not_bow`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_not_eol`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_not_eow`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_not_null`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`match_prev_avail`](../regex/match_flag_type "cpp/regex/match flag type") (since C++11) [`multiline`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++17) ### N [`nosubs`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### O [`optimize`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) ### S [`syntax_option_type`](../regex/syntax_option_type "cpp/regex/syntax option type") (since C++11) cpp std::literals::chrono_literals Symbol Index std::literals::chrono\_literals Symbol Index ============================================ This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::literals::chrono_literals::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. ### Notes These operators are declared in the namespace `std::literals::chrono_literals`, where both `literals` and `chrono_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::chrono_literals`, and `using namespace std::literals::chrono_literals`. In addition, within the namespace `std::chrono`, the directive `using namespace literals::chrono_literals;` is provided by the standard library, so that if a programmer uses `using namespace std::chrono;` to gain access to the classes in the chrono library, the corresponding literal operators become visible as well. `[D](#D) [H](#H) [M](#M) [N](#N) [S](#S) [U](#U) [Y](#Y)` ----------------------------------------------------------------- ### D [`d`](../chrono/operator%22%22d "cpp/chrono/operator\"\"d") (since C++20) ### H [`h`](../chrono/operator%22%22h "cpp/chrono/operator\"\"h") (since C++14) ### M [`min`](../chrono/operator%22%22min "cpp/chrono/operator\"\"min") (since C++14) [`ms`](../chrono/operator%22%22ms "cpp/chrono/operator\"\"ms") (since C++14) ### N [`ns`](../chrono/operator%22%22ns "cpp/chrono/operator\"\"ns") (since C++14) ### S [`s`](../chrono/operator%22%22s "cpp/chrono/operator\"\"s") (since C++14) ### U [`us`](../chrono/operator%22%22us "cpp/chrono/operator\"\"us") (since C++14) ### Y [`y`](../chrono/operator%22%22y "cpp/chrono/operator\"\"y") (since C++20) cpp Macro Symbol Index Macro Symbol Index ================== This page tries to list all the macro symbols that are available from the *Standard Library*. The symbols are written as follows: * Function-like macros with `()`. `[\_](#.28underscore.29) [A](#A) [B](#B) [C](#C) [D](#D) [E](#E) [F](#F) [H](#H) [I](#I) [K](#K) [L](#L) [M](#M) [N](#N) [O](#O) [P](#P) [R](#R) [S](#S) [T](#T) [U](#U) [V](#V) [W](#W)` --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### \_ (underscore) [`__alignas_is_defined`](../types "cpp/types") (since C++11) [`__bool_true_false_are_defined`](../types "cpp/types") (since C++11) [`__cpp_lib_adaptor_iterator_pair_constructor`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_addressof_constexpr`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_algorithm_iterator_requirements`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_allocate_at_least`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_allocator_traits_is_always_equal`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_any`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_apply`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_array_constexpr`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_as_const`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_associative_heterogeneous_erasure`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_assume_aligned`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_flag_test`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_float`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_is_always_lock_free`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_lock_free_type_aliases`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_ref`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_shared_ptr`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_value_initialization`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_atomic_wait`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_barrier`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_bind_back`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_bind_front`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_bit_cast`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_bitops`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_bool_constant`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_bounded_array_traits`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_boyer_moore_searcher`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_byte`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_byteswap`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_char8_t`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_chrono`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_chrono_udls`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_clamp`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_complex_udls`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_concepts`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_constexpr_algorithms`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_bitset`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_constexpr_charconv`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_constexpr_cmath`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_constexpr_complex`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_dynamic_alloc`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_functional`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_iterator`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_memory`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_constexpr_numeric`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_string`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_string_view`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_tuple`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_typeinfo`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_constexpr_utility`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_constexpr_vector`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_containers_ranges`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_coroutine`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_destroying_delete`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_enable_shared_from_this`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_endian`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_erase_if`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_exchange_function`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_execution`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_expected`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_filesystem`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_find_last`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_flat_map`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_format`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_forward_like`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_gcd_lcm`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_generator`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_generic_associative_lookup`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_generic_unordered_lookup`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_hardware_interference_size`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_has_unique_object_representations`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_hypot`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_incomplete_container_elements`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_integer_comparison_functions`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_int_pow2`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_integer_sequence`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_integral_constant_callable`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_interpolate`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_invoke`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_invoke_r`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ios_noreplace`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_is_aggregate`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_constant_evaluated`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_final`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_invocable`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_layout_compatible`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_nothrow_convertible`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_null_pointer`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_pointer_interconvertible`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_is_scoped_enum`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_is_swappable`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_jthread`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_latch`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_launder`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_list_remove_return_type`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_logical_traits`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_make_from_tuple`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_make_reverse_iterator`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_make_unique`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_map_try_emplace`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_math_constants`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_math_special_functions`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_mdspan`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_memory_resource`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_move_iterator_concept`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_move_only_function`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_node_extract`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_nonmember_container_access`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_not_fn`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_null_iterators`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_optional`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_out_ptr`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_parallel_algorithm`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_polymorphic_allocator`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_print`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_quoted_string_io`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_ranges`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_ranges_as_const`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_as_rvalue`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_cartesian_product`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_chunk`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_chunk_by`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_contains`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_fold`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_iota`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_join_with`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_repeat`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_slide`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_starts_ends_with`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_stride`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_to_container`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ranges_zip`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_raw_memory_algorithms`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_reference_from_temporary`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_remove_cvref`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_result_of_sfinae`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_robust_nonmodifying_seq_ops`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_sample`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_scoped_lock`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_semaphore`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_shared_mutex`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_shared_ptr_arrays`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_shared_ptr_weak_type`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_shared_timed_mutex`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_shift`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_smart_ptr_for_overwrite`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_source_location`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_span`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_spanstream`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_ssize`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_stacktrace`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_start_lifetime_as`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_starts_ends_with`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_stdatomic_h`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_string_contains`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_string_resize_and_overwrite`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_string_udls`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_string_view`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_syncbuf`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_three_way_comparison`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_to_address`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_to_array`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_to_chars`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_to_underlying`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_transformation_trait_aliases`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_transparent_operators`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_tuple_element_t`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_tuple_like`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_tuples_by_type`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_type_identity`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_type_trait_variable_templates`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_uncaught_exceptions`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_unordered_map_try_emplace`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_unreachable`](../utility/feature_test "cpp/utility/feature test") (since C++23) [`__cpp_lib_unwrap_ref`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`__cpp_lib_variant`](../utility/feature_test "cpp/utility/feature test") (since C++20)(updated in C++23) [`__cpp_lib_void_t`](../utility/feature_test "cpp/utility/feature test") (since C++20) [`_Atomic()`](../atomic/atomic "cpp/atomic/atomic") (since C++23) [`_IOFBF`](../io/c "cpp/io/c") [`_IOLBF`](../io/c "cpp/io/c") [`_IONBF`](../io/c "cpp/io/c") ### A [`assert()`](../error/assert "cpp/error/assert") [`ATOMIC_BOOL_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_CHAR_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_CHAR16_T_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_CHAR32_T_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_CHAR8_T_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++20) [`ATOMIC_FLAG_INIT`](../atomic/atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT") (since C++11)(deprecated in C++20) [`ATOMIC_INT_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_LLONG_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_LONG_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_POINTER_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_SHORT_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) [`ATOMIC_VAR_INIT()`](../atomic/atomic_var_init "cpp/atomic/ATOMIC VAR INIT") (since C++11)(deprecated in C++20) [`ATOMIC_WCHAR_T_LOCK_FREE`](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (since C++11) ### B [`BUFSIZ`](../io/c "cpp/io/c") ### C [`CHAR_BIT`](../types/climits "cpp/types/climits") [`CHAR_MAX`](../types/climits "cpp/types/climits") [`CHAR_MIN`](../types/climits "cpp/types/climits") [`CLOCKS_PER_SEC`](../chrono/c/clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC") ### D [`DBL_DECIMAL_DIG`](../types/climits "cpp/types/climits") (since C++17) [`DBL_DIG`](../types/climits "cpp/types/climits") [`DBL_EPSILON`](../types/climits "cpp/types/climits") [`DBL_HAS_SUBNORM`](../types/climits "cpp/types/climits") (since C++17) [`DBL_MANT_DIG`](../types/climits "cpp/types/climits") [`DBL_MAX`](../types/climits "cpp/types/climits") [`DBL_MAX_10_EXP`](../types/climits "cpp/types/climits") [`DBL_MAX_EXP`](../types/climits "cpp/types/climits") [`DBL_MIN`](../types/climits "cpp/types/climits") [`DBL_MIN_10_EXP`](../types/climits "cpp/types/climits") [`DBL_MIN_EXP`](../types/climits "cpp/types/climits") [`DBL_TRUE_MIN`](../types/climits "cpp/types/climits") (since C++17) [`DECIMAL_DIG`](../types/climits "cpp/types/climits") (since C++11) ### E [`E2BIG`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EACCES`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EADDRINUSE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EADDRNOTAVAIL`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EAFNOSUPPORT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EAGAIN`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EALREADY`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EBADF`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EBADMSG`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EBUSY`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ECANCELED`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ECHILD`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ECONNABORTED`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ECONNREFUSED`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ECONNRESET`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EDEADLK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EDESTADDRREQ`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EDOM`](../error/errno_macros "cpp/error/errno macros") [`EEXIST`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EFAULT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EFBIG`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EHOSTUNREACH`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EIDRM`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EILSEQ`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EINPROGRESS`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EINTR`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EINVAL`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EIO`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EISCONN`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EISDIR`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ELOOP`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EMFILE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EMLINK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EMSGSIZE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENAMETOOLONG`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENETDOWN`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENETRESET`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENETUNREACH`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENFILE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOBUFS`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENODATA`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENODEV`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOENT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOEXEC`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOLCK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOLINK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOMEM`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOMSG`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOPROTOOPT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOSPC`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOSR`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOSTR`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOSYS`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTCONN`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTDIR`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTEMPTY`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTRECOVERABLE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTSOCK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTSUP`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENOTTY`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ENXIO`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EOF`](../io/c "cpp/io/c") [`EOPNOTSUPP`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EOVERFLOW`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EOWNERDEAD`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EPERM`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EPIPE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EPROTO`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EPROTONOSUPPORT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EPROTOTYPE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ERANGE`](../error/errno_macros "cpp/error/errno macros") [`EROFS`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`errno`](../error/errno "cpp/error/errno") [`ESPIPE`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ESRCH`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ETIME`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ETIMEDOUT`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`ETXTBSY`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EWOULDBLOCK`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EXDEV`](../error/errno_macros "cpp/error/errno macros") (since C++11) [`EXIT_FAILURE`](../utility/program/exit_status "cpp/utility/program/EXIT status") [`EXIT_SUCCESS`](../utility/program/exit_status "cpp/utility/program/EXIT status") ### F [`FE_ALL_EXCEPT`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_DFL_ENV`](../numeric/fenv/fe_dfl_env "cpp/numeric/fenv/FE DFL ENV") (since C++11) [`FE_DIVBYZERO`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_DOWNWARD`](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") (since C++11) [`FE_INEXACT`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_INVALID`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_OVERFLOW`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_TONEAREST`](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") (since C++11) [`FE_TOWARDZERO`](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") (since C++11) [`FE_UNDERFLOW`](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions") (since C++11) [`FE_UPWARD`](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") (since C++11) [`FILENAME_MAX`](../io/c "cpp/io/c") [`FLT_DECIMAL_DIG`](../types/climits "cpp/types/climits") (since C++17) [`FLT_DIG`](../types/climits "cpp/types/climits") [`FLT_EPSILON`](../types/climits "cpp/types/climits") [`FLT_EVAL_METHOD`](../types/climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD") (since C++11) [`FLT_HAS_SUBNORM`](../types/climits "cpp/types/climits") (since C++17) [`FLT_MANT_DIG`](../types/climits "cpp/types/climits") [`FLT_MAX`](../types/climits "cpp/types/climits") [`FLT_MAX_10_EXP`](../types/climits "cpp/types/climits") [`FLT_MAX_EXP`](../types/climits "cpp/types/climits") [`FLT_MIN`](../types/climits "cpp/types/climits") [`FLT_MIN_10_EXP`](../types/climits "cpp/types/climits") [`FLT_MIN_EXP`](../types/climits "cpp/types/climits") [`FLT_RADIX`](../types/climits "cpp/types/climits") [`FLT_ROUNDS`](../types/climits/flt_rounds "cpp/types/climits/FLT ROUNDS") [`FLT_TRUE_MIN`](../types/climits "cpp/types/climits") (since C++17) [`FOPEN_MAX`](../io/c "cpp/io/c") [`FP_FAST_FMA`](../numeric/math/fma "cpp/numeric/math/fma") (since C++11) [`FP_FAST_FMAF`](../numeric/math/fma "cpp/numeric/math/fma") (since C++11) [`FP_FAST_FMAL`](../numeric/math/fma "cpp/numeric/math/fma") (since C++11) [`FP_ILOGB0`](../numeric/math/ilogb "cpp/numeric/math/ilogb") (since C++11) [`FP_ILOGBNAN`](../numeric/math/ilogb "cpp/numeric/math/ilogb") (since C++11) [`FP_SUBNORMAL`](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (since C++11) [`FP_ZERO`](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (since C++11) [`FP_INFINITE`](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (since C++11) [`FP_NAN`](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (since C++11) [`FP_NORMAL`](../numeric/math/fp_categories "cpp/numeric/math/FP categories") (since C++11) ### H [`HUGE_VAL`](../numeric/math/huge_val "cpp/numeric/math/HUGE VAL") [`HUGE_VALF`](../numeric/math/huge_val "cpp/numeric/math/HUGE VAL") (since C++11) [`HUGE_VALL`](../numeric/math/huge_val "cpp/numeric/math/HUGE VAL") (since C++11) ### I [`INFINITY`](../numeric/math/infinity "cpp/numeric/math/INFINITY") (since C++11) [`INT_FAST16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST16_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST32_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST64_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_FAST8_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST16_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST32_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST64_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT_LEAST8_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT_MAX`](../types/climits "cpp/types/climits") [`INT_MIN`](../types/climits "cpp/types/climits") [`INT16_C()`](../types/integer "cpp/types/integer") (since C++11) [`INT16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT16_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT32_C()`](../types/integer "cpp/types/integer") (since C++11) [`INT32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT32_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT64_C()`](../types/integer "cpp/types/integer") (since C++11) [`INT64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT64_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INT8_C()`](../types/integer "cpp/types/integer") (since C++11) [`INT8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INT8_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INTMAX_C()`](../types/integer "cpp/types/integer") (since C++11) [`INTMAX_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INTMAX_MIN`](../types/integer "cpp/types/integer") (since C++11) [`INTPTR_MAX`](../types/integer "cpp/types/integer") (since C++11) [`INTPTR_MIN`](../types/integer "cpp/types/integer") (since C++11) ### L [`L_tmpnam`](../io/c "cpp/io/c") [`LC_ALL`](../locale/lc_categories "cpp/locale/LC categories") [`LC_COLLATE`](../locale/lc_categories "cpp/locale/LC categories") [`LC_CTYPE`](../locale/lc_categories "cpp/locale/LC categories") [`LC_MONETARY`](../locale/lc_categories "cpp/locale/LC categories") [`LC_NUMERIC`](../locale/lc_categories "cpp/locale/LC categories") [`LC_TIME`](../locale/lc_categories "cpp/locale/LC categories") [`LDBL_DECIMAL_DIG`](../types/climits "cpp/types/climits") (since C++17) [`LDBL_DIG`](../types/climits "cpp/types/climits") [`LDBL_EPSILON`](../types/climits "cpp/types/climits") [`LDBL_HAS_SUBNORM`](../types/climits "cpp/types/climits") (since C++17) [`LDBL_MANT_DIG`](../types/climits "cpp/types/climits") [`LDBL_MAX`](../types/climits "cpp/types/climits") [`LDBL_MAX_10_EXP`](../types/climits "cpp/types/climits") [`LDBL_MAX_EXP`](../types/climits "cpp/types/climits") [`LDBL_MIN`](../types/climits "cpp/types/climits") [`LDBL_MIN_10_EXP`](../types/climits "cpp/types/climits") [`LDBL_MIN_EXP`](../types/climits "cpp/types/climits") [`LDBL_TRUE_MIN`](../types/climits "cpp/types/climits") (since C++17) [`LLONG_MAX`](../types/climits "cpp/types/climits") (since C++11) [`LLONG_MIN`](../types/climits "cpp/types/climits") (since C++11) [`LONG_MAX`](../types/climits "cpp/types/climits") [`LONG_MIN`](../types/climits "cpp/types/climits") ### M [`MATH_ERREXCEPT`](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling") (since C++11) [`math_errhandling`](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling") (since C++11) [`MATH_ERRNO`](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling") (since C++11) [`MB_CUR_MAX`](../string/multibyte "cpp/string/multibyte") [`MB_LEN_MAX`](../string/multibyte "cpp/string/multibyte") ### N [`NAN`](../numeric/math/nan "cpp/numeric/math/NAN") (since C++11) [`NULL`](../types/null "cpp/types/NULL") ### O [`offsetof()`](../types/offsetof "cpp/types/offsetof") [`ONCE_FLAG_INIT`](../thread/call_once "cpp/thread/call once") (since C++11) ### P [`PRId16`](../types/integer "cpp/types/integer") (since C++11) [`PRId32`](../types/integer "cpp/types/integer") (since C++11) [`PRId64`](../types/integer "cpp/types/integer") (since C++11) [`PRId8`](../types/integer "cpp/types/integer") (since C++11) [`PRIdFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIdFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIdFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIdFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIdLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIdLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIdLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIdLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIdMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIdPTR`](../types/integer "cpp/types/integer") (since C++11) [`PRIi16`](../types/integer "cpp/types/integer") (since C++11) [`PRIi32`](../types/integer "cpp/types/integer") (since C++11) [`PRIi64`](../types/integer "cpp/types/integer") (since C++11) [`PRIi8`](../types/integer "cpp/types/integer") (since C++11) [`PRIiFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIiFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIiFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIiFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIiLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIiLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIiLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIiLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIiMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIiPTR`](../types/integer "cpp/types/integer") (since C++11) [`PRIo16`](../types/integer "cpp/types/integer") (since C++11) [`PRIo32`](../types/integer "cpp/types/integer") (since C++11) [`PRIo64`](../types/integer "cpp/types/integer") (since C++11) [`PRIo8`](../types/integer "cpp/types/integer") (since C++11) [`PRIoFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIoFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIoFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIoFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIoLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIoLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIoLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIoLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIoMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIoPTR`](../types/integer "cpp/types/integer") (since C++11) [`PRIu16`](../types/integer "cpp/types/integer") (since C++11) [`PRIu32`](../types/integer "cpp/types/integer") (since C++11) [`PRIu64`](../types/integer "cpp/types/integer") (since C++11) [`PRIu8`](../types/integer "cpp/types/integer") (since C++11) [`PRIuFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIuFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIuFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIuFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIuLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIuLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIuLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIuLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIuMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIuPTR`](../types/integer "cpp/types/integer") (since C++11) [`PRIx16`](../types/integer "cpp/types/integer") (since C++11) [`PRIX16`](../types/integer "cpp/types/integer") (since C++11) [`PRIx32`](../types/integer "cpp/types/integer") (since C++11) [`PRIX32`](../types/integer "cpp/types/integer") (since C++11) [`PRIx64`](../types/integer "cpp/types/integer") (since C++11) [`PRIX64`](../types/integer "cpp/types/integer") (since C++11) [`PRIx8`](../types/integer "cpp/types/integer") (since C++11) [`PRIX8`](../types/integer "cpp/types/integer") (since C++11) [`PRIxFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIXFAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIxFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIXFAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIxFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIXFAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIxFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIXFAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIxLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIXLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`PRIxLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIXLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`PRIxLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIXLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`PRIxLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIXLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`PRIxMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIXMAX`](../types/integer "cpp/types/integer") (since C++11) [`PRIxPTR`](../types/integer "cpp/types/integer") (since C++11) [`PRIXPTR`](../types/integer "cpp/types/integer") (since C++11) [`PTRDIFF_MAX`](../types/climits "cpp/types/climits") (since C++11) [`PTRDIFF_MIN`](../types/climits "cpp/types/climits") (since C++11) ### R [`RAND_MAX`](../numeric/random/rand_max "cpp/numeric/random/RAND MAX") ### S [`SCHAR_MAX`](../types/climits "cpp/types/climits") [`SCHAR_MIN`](../types/climits "cpp/types/climits") [`SCNd16`](../types/integer "cpp/types/integer") (since C++11) [`SCNd32`](../types/integer "cpp/types/integer") (since C++11) [`SCNd64`](../types/integer "cpp/types/integer") (since C++11) [`SCNd8`](../types/integer "cpp/types/integer") (since C++11) [`SCNdFAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNdFAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNdFAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNdFAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNdLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNdLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNdLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNdLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNdMAX`](../types/integer "cpp/types/integer") (since C++11) [`SCNdPTR`](../types/integer "cpp/types/integer") (since C++11) [`SCNi16`](../types/integer "cpp/types/integer") (since C++11) [`SCNi32`](../types/integer "cpp/types/integer") (since C++11) [`SCNi64`](../types/integer "cpp/types/integer") (since C++11) [`SCNi8`](../types/integer "cpp/types/integer") (since C++11) [`SCNiFAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNiFAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNiFAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNiFAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNiLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNiLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNiLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNiLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNiMAX`](../types/integer "cpp/types/integer") (since C++11) [`SCNiPTR`](../types/integer "cpp/types/integer") (since C++11) [`SCNo16`](../types/integer "cpp/types/integer") (since C++11) [`SCNo32`](../types/integer "cpp/types/integer") (since C++11) [`SCNo64`](../types/integer "cpp/types/integer") (since C++11) [`SCNo8`](../types/integer "cpp/types/integer") (since C++11) [`SCNoFAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNoFAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNoFAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNoFAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNoLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNoLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNoLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNoLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNoMAX`](../types/integer "cpp/types/integer") (since C++11) [`SCNoPTR`](../types/integer "cpp/types/integer") (since C++11) [`SCNu16`](../types/integer "cpp/types/integer") (since C++11) [`SCNu32`](../types/integer "cpp/types/integer") (since C++11) [`SCNu64`](../types/integer "cpp/types/integer") (since C++11) [`SCNu8`](../types/integer "cpp/types/integer") (since C++11) [`SCNuFAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNuFAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNuFAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNuFAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNuLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNuLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNuLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNuLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNuMAX`](../types/integer "cpp/types/integer") (since C++11) [`SCNuPTR`](../types/integer "cpp/types/integer") (since C++11) [`SCNx16`](../types/integer "cpp/types/integer") (since C++11) [`SCNx32`](../types/integer "cpp/types/integer") (since C++11) [`SCNx64`](../types/integer "cpp/types/integer") (since C++11) [`SCNx8`](../types/integer "cpp/types/integer") (since C++11) [`SCNxFAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNxFAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNxFAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNxFAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNxLEAST16`](../types/integer "cpp/types/integer") (since C++11) [`SCNxLEAST32`](../types/integer "cpp/types/integer") (since C++11) [`SCNxLEAST64`](../types/integer "cpp/types/integer") (since C++11) [`SCNxLEAST8`](../types/integer "cpp/types/integer") (since C++11) [`SCNxMAX`](../types/integer "cpp/types/integer") (since C++11) [`SCNxPTR`](../types/integer "cpp/types/integer") (since C++11) [`SEEK_CUR`](../io/c "cpp/io/c") [`SEEK_END`](../io/c "cpp/io/c") [`SEEK_SET`](../io/c "cpp/io/c") [`setjmp()`](../utility/program/setjmp "cpp/utility/program/setjmp") [`SHRT_MAX`](../types/climits "cpp/types/climits") [`SHRT_MIN`](../types/climits "cpp/types/climits") [`SIG_ATOMIC_MAX`](../types/climits "cpp/types/climits") (since C++11) [`SIG_ATOMIC_MIN`](../types/climits "cpp/types/climits") (since C++11) [`SIG_DFL`](../utility/program/sig_strategies "cpp/utility/program/SIG strategies") [`SIG_ERR`](../utility/program/sig_err "cpp/utility/program/SIG ERR") [`SIG_IGN`](../utility/program/sig_strategies "cpp/utility/program/SIG strategies") [`SIGABRT`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIGFPE`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIGILL`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIGINT`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIGSEGV`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIGTERM`](../utility/program/sig_types "cpp/utility/program/SIG types") [`SIZE_MAX`](../types/climits "cpp/types/climits") (since C++11) [`stderr`](../io/c/std_streams "cpp/io/c/std streams") [`stdin`](../io/c/std_streams "cpp/io/c/std streams") [`stdout`](../io/c/std_streams "cpp/io/c/std streams") ### T [`TIME_UTC`](../chrono/c/timespec_get "cpp/chrono/c/timespec get") (since C++17) [`TMP_MAX`](../io/c "cpp/io/c") ### U [`UCHAR_MAX`](../types/climits "cpp/types/climits") [`UINT_FAST16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_FAST32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_FAST64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_FAST8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_LEAST16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_LEAST32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_LEAST64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_LEAST8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT_MAX`](../types/climits "cpp/types/climits") [`UINT16_C()`](../types/integer "cpp/types/integer") (since C++11) [`UINT16_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT32_C()`](../types/integer "cpp/types/integer") (since C++11) [`UINT32_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT64_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINT64_C()`](../types/integer "cpp/types/integer") (since C++11) [`UINT8_C()`](../types/integer "cpp/types/integer") (since C++11) [`UINT8_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINTMAX_C()`](../types/integer "cpp/types/integer") (since C++11) [`UINTMAX_MAX`](../types/integer "cpp/types/integer") (since C++11) [`UINTPTR_MAX`](../types/integer "cpp/types/integer") (since C++11) [`ULLONG_MAX`](../types/climits "cpp/types/climits") (since C++11) [`ULONG_MAX`](../types/climits "cpp/types/climits") [`USHRT_MAX`](../types/climits "cpp/types/climits") ### V [`va_arg()`](../utility/variadic/va_arg "cpp/utility/variadic/va arg") [`va_copy()`](../utility/variadic/va_copy "cpp/utility/variadic/va copy") (since C++11) [`va_end()`](../utility/variadic/va_end "cpp/utility/variadic/va end") [`va_start()`](../utility/variadic/va_start "cpp/utility/variadic/va start") ### W [`WCHAR_MAX`](../types/climits "cpp/types/climits") (since C++11) [`WCHAR_MIN`](../types/climits "cpp/types/climits") (since C++11) [`WEOF`](../string/wide "cpp/string/wide") [`WINT_MAX`](../types/climits "cpp/types/climits") (since C++11) [`WINT_MIN`](../types/climits "cpp/types/climits") (since C++11) ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/symbol_index/macro "c/symbol index/macro") for Macro Symbol Index |
programming_docs
cpp std::literals::string_view_literals Symbol Index std::literals::string\_view\_literals Symbol Index ================================================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::literals::string_view_literals::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. ### Notes These operators are declared in the namespace `std::literals::string_view_literals`, where both `literals` and `string_view_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::string_view_literals`, and `using namespace std::literals::string_view_literals`. `[S](#S)` ----------- ### S [`sv`](../string/basic_string_view/operator%22%22sv "cpp/string/basic string view/operator\"\"sv") (since C++17) cpp std::rel_ops Symbol Index std::rel\_ops Symbol Index ========================== There are no identifiers available from the *Standard Library* in the namespace `std::rel_ops::`. The namespace exists for automatic generation of comparison operators, and is deprecated in C++20 because of [the three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison"). ### See also | | | | --- | --- | | [operator!=operator>operator<=operator>=](../utility/rel_ops/operator_cmp "cpp/utility/rel ops/operator cmp") (deprecated in C++20) | automatically generates comparison operators based on user-defined `operator==` and `operator<` (function template) | cpp Symbol Index (removed) Symbol Index (removed) ====================== This page tries to list all the symbols that were available from the *Standard Library* in the namespace `std::` or in the scope of a scoped enumeration or a class, but removed in following standards. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. Member names that are still available in other types are not listed here. ### Removed in C++14 [`gets()`](../io/c/gets "cpp/io/c/gets") (deprecated in C++11)(removed in C++14) ### Removed in C++17 [`auto_ptr<>`](../memory/auto_ptr "cpp/memory/auto ptr") (deprecated in C++11)(removed in C++17) [`binary_function<>`](../utility/functional/binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) [`bind1st<>()`](../utility/functional/bind12 "cpp/utility/functional/bind12") (deprecated in C++11)(removed in C++17) [`bind2nd<>()`](../utility/functional/bind12 "cpp/utility/functional/bind12") (deprecated in C++11)(removed in C++17) [`binder1st<>`](../utility/functional/binder12 "cpp/utility/functional/binder12") (deprecated in C++11)(removed in C++17) [`binder2nd<>`](../utility/functional/binder12 "cpp/utility/functional/binder12") (deprecated in C++11)(removed in C++17) [`const_mem_fun_ref_t<>`](../utility/functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) [`const_mem_fun_t<>`](../utility/functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) [`const_mem_fun1_ref_t<>`](../utility/functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) [`const_mem_fun1_t<>`](../utility/functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) [`get_unexpected()`](../error/exception/get_unexpected "cpp/error/exception/get unexpected") (since C++11)(deprecated in C++11)(removed in C++17) [`mem_fun<>()`](../utility/functional/mem_fun "cpp/utility/functional/mem fun") (deprecated in C++11)(removed in C++17) [`mem_fun_ref<>()`](../utility/functional/mem_fun_ref "cpp/utility/functional/mem fun ref") (deprecated in C++11)(removed in C++17) [`mem_fun_ref_t<>`](../utility/functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) [`mem_fun_t<>`](../utility/functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) [`mem_fun1_ref_t<>`](../utility/functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) [`mem_fun1_t<>`](../utility/functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) [`pointer_to_binary_function<>`](../utility/functional/pointer_to_binary_function "cpp/utility/functional/pointer to binary function") (deprecated in C++11)(removed in C++17) [`pointer_to_unary_function<>`](../utility/functional/pointer_to_unary_function "cpp/utility/functional/pointer to unary function") (deprecated in C++11)(removed in C++17) [`ptr_fun<>()`](../utility/functional/ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) [`random_shuffle<>()`](../algorithm/random_shuffle "cpp/algorithm/random shuffle") (removed in C++17) [`set_unexpected()`](../error/exception/set_unexpected "cpp/error/exception/set unexpected") (deprecated in C++11)(removed in C++17) [`unary_function<>`](../utility/functional/unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) [`unexpected_handler`](../error/exception/unexpected_handler "cpp/error/exception/unexpected handler") (deprecated in C++11)(removed in C++17) #### Member names [`io_state`](../io/ios_base "cpp/io/ios base") (removed in C++17) [`open_mode`](../io/ios_base "cpp/io/ios base") (removed in C++17) [`seek_dir`](../io/ios_base "cpp/io/ios base") (removed in C++17) [`stossc()`](../io/basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) ### Removed in C++20 [`binary_negate<>`](../utility/functional/binary_negate "cpp/utility/functional/binary negate") (removed in C++20) [`get_temporary_buffer<>()`](../memory/get_temporary_buffer "cpp/memory/get temporary buffer") (removed in C++20) [`is_literal_type<>`](../types/is_literal_type "cpp/types/is literal type") (since C++11)(deprecated in C++17)(removed in C++20) [`is_literal_type_v<>`](../types/is_literal_type "cpp/types/is literal type") (since C++17)(deprecated in C++17)(removed in C++20) [`not1<>()`](../utility/functional/not1 "cpp/utility/functional/not1") (removed in C++20) [`not2<>()`](../utility/functional/not2 "cpp/utility/functional/not2") (removed in C++20) [`raw_storage_iterator<>`](../memory/raw_storage_iterator "cpp/memory/raw storage iterator") (removed in C++20) [`result_of<>`](../types/result_of "cpp/types/result of") (since C++11)(deprecated in C++17)(removed in C++20) [`result_of_t<>`](../types/result_of "cpp/types/result of") (since C++14)(deprecated in C++17)(removed in C++20) [`return_temporary_buffer<>()`](../memory/return_temporary_buffer "cpp/memory/return temporary buffer") (removed in C++20) [`unary_negate<>`](../utility/functional/unary_negate "cpp/utility/functional/unary negate") (removed in C++20) [`uncaught_exception()`](../error/exception/uncaught_exception "cpp/error/exception/uncaught exception") (removed in C++20) #### Member names [`argument_type`](../utility/functional "cpp/utility/functional") (removed in C++20) [`first_argument_type`](../utility/functional "cpp/utility/functional") (removed in C++20) [`second_argument_type`](../utility/functional "cpp/utility/functional") (removed in C++20) ### Removed in C++23 [`declare_no_pointers()`](../memory/gc/declare_no_pointers "cpp/memory/gc/declare no pointers") (since C++11)(removed in C++23) [`declare_reachable()`](../memory/gc/declare_reachable "cpp/memory/gc/declare reachable") (since C++11)(removed in C++23) [`get_pointer_safety()`](../memory/gc/get_pointer_safety "cpp/memory/gc/get pointer safety") (since C++11)(removed in C++23) [`pointer_safety`](../memory/gc/pointer_safety "cpp/memory/gc/pointer safety") (since C++11)(removed in C++23) [`undeclare_no_pointers()`](../memory/gc/undeclare_no_pointers "cpp/memory/gc/undeclare no pointers") (since C++11)(removed in C++23) [`undeclare_reachable<>()`](../memory/gc/undeclare_reachable "cpp/memory/gc/undeclare reachable") (since C++11)(removed in C++23) #### Member names [`preferred`](../memory/gc/pointer_safety "cpp/memory/gc/pointer safety") (since C++11)(removed in C++23) [`strict`](../memory/gc/pointer_safety "cpp/memory/gc/pointer safety") (since C++11)(removed in C++23) cpp std::chrono Symbol Index std::chrono Symbol Index ======================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::chrono::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[A](#A) [C](#C) [D](#D) [F](#F) [G](#G) [H](#H) [I](#I) [J](#J) [L](#L) [M](#M) [N](#N) [O](#O) [P](#P) [R](#R) [S](#S) [T](#T) [U](#U) [W](#W) [Y](#Y) [Z](#Z)` -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### A [`abs<>()`](../chrono/duration/abs "cpp/chrono/duration/abs") (since C++17) [`ambiguous_local_time`](../chrono/ambiguous_local_time "cpp/chrono/ambiguous local time") (since C++20) [`April`](../chrono/month "cpp/chrono/month") (since C++20) [`August`](../chrono/month "cpp/chrono/month") (since C++20) ### C [`ceil<>()`](../chrono/duration/ceil "cpp/chrono/duration/ceil") (std::chrono::duration) (since C++17) [`ceil<>()`](../chrono/time_point/ceil "cpp/chrono/time point/ceil") (std::chrono::time\_point) (since C++17) [`choose`](../chrono/choose "cpp/chrono/choose") (since C++20) [`clock_cast<>()`](../chrono/clock_cast "cpp/chrono/clock cast") (since C++20) [`clock_time_conversion<>`](../chrono/clock_time_conversion "cpp/chrono/clock time conversion") (since C++20) [`current_zone()`](../chrono/current_zone "cpp/chrono/current zone") (since C++20) ### D [`day`](../chrono/day "cpp/chrono/day") (since C++20) [`December`](../chrono/month "cpp/chrono/month") (since C++20) [`duration<>`](../chrono/duration "cpp/chrono/duration") (since C++11) [`duration_cast<>()`](../chrono/duration/duration_cast "cpp/chrono/duration/duration cast") (since C++11) [`duration_values<>`](../chrono/duration_values "cpp/chrono/duration values") (since C++11) ### F [`February`](../chrono/month "cpp/chrono/month") (since C++20) [`file_clock`](../chrono/file_clock "cpp/chrono/file clock") (since C++20) [`file_seconds`](../chrono/file_clock "cpp/chrono/file clock") (since C++20) [`file_time`](../chrono/file_clock "cpp/chrono/file clock") (since C++20) [`floor<>()`](../chrono/duration/floor "cpp/chrono/duration/floor") (std::chrono::duration) (since C++17) [`floor<>()`](../chrono/time_point/floor "cpp/chrono/time point/floor") (std::chrono::time\_point) (since C++17) [`Friday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`from_stream<>()`](../chrono/day/from_stream "cpp/chrono/day/from stream") (std::chrono::day) (since C++20) [`from_stream<>()`](../chrono/file_clock/from_stream "cpp/chrono/file clock/from stream") (std::chrono::file\_time) (since C++20) [`from_stream<>()`](../chrono/gps_clock/from_stream "cpp/chrono/gps clock/from stream") (std::chrono::gps\_time) (since C++20) [`from_stream<>()`](../chrono/local_t/from_stream "cpp/chrono/local t/from stream") (std::chrono::local\_time) (since C++20) [`from_stream<>()`](../chrono/month/from_stream "cpp/chrono/month/from stream") (std::chrono::month) (since C++20) [`from_stream<>()`](../chrono/month_day/from_stream "cpp/chrono/month day/from stream") (std::chrono::month\_day) (since C++20) [`from_stream<>()`](../chrono/system_clock/from_stream "cpp/chrono/system clock/from stream") (std::chrono::sys\_time) (since C++20) [`from_stream<>()`](../chrono/tai_clock/from_stream "cpp/chrono/tai clock/from stream") (std::chrono::tai\_time) (since C++20) [`from_stream<>()`](../chrono/utc_clock/from_stream "cpp/chrono/utc clock/from stream") (std::chrono::utc\_time) (since C++20) [`from_stream<>()`](../chrono/weekday/from_stream "cpp/chrono/weekday/from stream") (std::chrono::weekday) (since C++20) [`from_stream<>()`](../chrono/year/from_stream "cpp/chrono/year/from stream") (std::chrono::year) (since C++20) [`from_stream<>()`](../chrono/year_month/from_stream "cpp/chrono/year month/from stream") (std::chrono::year\_month) (since C++20) [`from_stream<>()`](../chrono/year_month_day/from_stream "cpp/chrono/year month day/from stream") (std::chrono::year\_month\_day) (since C++20) ### G [`get_leap_second_info`](../chrono/utc_clock/get_leap_second_info "cpp/chrono/utc clock/get leap second info") (since C++20) [`get_tzdb()`](../chrono/tzdb_functions "cpp/chrono/tzdb functions") (since C++20) [`get_tzdb_list()`](../chrono/tzdb_functions "cpp/chrono/tzdb functions") (since C++20) [`gps_clock`](../chrono/gps_clock "cpp/chrono/gps clock") (since C++20) [`gps_seconds`](../chrono/gps_clock "cpp/chrono/gps clock") (since C++20) [`gps_time`](../chrono/gps_clock "cpp/chrono/gps clock") (since C++20) ### H [`hh_mm_ss<>`](../chrono/hh_mm_ss "cpp/chrono/hh mm ss") (since C++20) [`high_resolution_clock`](../chrono/high_resolution_clock "cpp/chrono/high resolution clock") (since C++11) [`hours`](../chrono/duration "cpp/chrono/duration") (since C++11) ### I [`is_am`](../chrono/hour_fun "cpp/chrono/hour fun") (since C++20) [`is_clock<>`](../chrono/is_clock "cpp/chrono/is clock") (since C++20) [`is_clock_v<>`](../chrono/is_clock "cpp/chrono/is clock") (since C++20) [`is_pm`](../chrono/hour_fun "cpp/chrono/hour fun") (since C++20) ### J [`January`](../chrono/month "cpp/chrono/month") (since C++20) [`July`](../chrono/month "cpp/chrono/month") (since C++20) [`June`](../chrono/month "cpp/chrono/month") (since C++20) ### L [`last`](../chrono/last_spec "cpp/chrono/last spec") (since C++20) [`last_spec`](../chrono/last_spec "cpp/chrono/last spec") (since C++20) [`leap_second`](../chrono/leap_second "cpp/chrono/leap second") (since C++20) [`leap_second_info`](../chrono/utc_clock/leap_second_info "cpp/chrono/utc clock/leap second info") (since C++20) [`local_info`](../chrono/local_info "cpp/chrono/local info") (since C++20) [`local_seconds`](../chrono/local_t "cpp/chrono/local t") (since C++20) [`local_t`](../chrono/local_t "cpp/chrono/local t") (since C++20) [`local_time`](../chrono/local_t "cpp/chrono/local t") (since C++20) [`local_time_format<>()`](../chrono/local_t/formatter "cpp/chrono/local t/formatter") (since C++20) [`locate_zone()`](../chrono/locate_zone "cpp/chrono/locate zone") (since C++20) ### M [`make12`](../chrono/hour_fun "cpp/chrono/hour fun") (since C++20) [`make24`](../chrono/hour_fun "cpp/chrono/hour fun") (since C++20) [`March`](../chrono/month "cpp/chrono/month") (since C++20) [`May`](../chrono/month "cpp/chrono/month") (since C++20) [`microseconds`](../chrono/duration "cpp/chrono/duration") (since C++11) [`milliseconds`](../chrono/duration "cpp/chrono/duration") (since C++11) [`minutes`](../chrono/duration "cpp/chrono/duration") (since C++11) [`Monday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`month`](../chrono/month "cpp/chrono/month") (since C++20) [`month_day`](../chrono/month_day "cpp/chrono/month day") (since C++20) [`month_day_last`](../chrono/month_day_last "cpp/chrono/month day last") (since C++20) [`month_weekday`](../chrono/month_weekday "cpp/chrono/month weekday") (since C++20) [`month_weekday_last`](../chrono/month_weekday_last "cpp/chrono/month weekday last") (since C++20) ### N [`nanoseconds`](../chrono/duration "cpp/chrono/duration") (since C++11) [`nonexistent_local_time`](../chrono/nonexistent_local_time "cpp/chrono/nonexistent local time") (since C++20) [`November`](../chrono/month "cpp/chrono/month") (since C++20) ### O [`October`](../chrono/month "cpp/chrono/month") (since C++20) ### P [`parse<>()`](../chrono/parse "cpp/chrono/parse") (since C++20) ### R [`reload_tzdb()`](../chrono/tzdb_functions "cpp/chrono/tzdb functions") (since C++20) [`remote_version()`](../chrono/tzdb_functions "cpp/chrono/tzdb functions") (since C++20) [`round<>()`](../chrono/duration/round "cpp/chrono/duration/round") (std::chrono::duration) (since C++17) [`round<>()`](../chrono/time_point/round "cpp/chrono/time point/round") (std::chrono::time\_point) (since C++17) ### S [`Saturday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`seconds`](../chrono/duration "cpp/chrono/duration") (since C++11) [`September`](../chrono/month "cpp/chrono/month") (since C++20) [`steady_clock`](../chrono/steady_clock "cpp/chrono/steady clock") (since C++11) [`Sunday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`sys_info`](../chrono/sys_info "cpp/chrono/sys info") (since C++20) [`sys_days`](../chrono/system_clock "cpp/chrono/system clock") (since C++20) [`sys_seconds`](../chrono/system_clock "cpp/chrono/system clock") (since C++20) [`sys_time`](../chrono/system_clock "cpp/chrono/system clock") (since C++20) [`system_clock`](../chrono/system_clock "cpp/chrono/system clock") (since C++11) ### T [`tai_clock`](../chrono/tai_clock "cpp/chrono/tai clock") (since C++20) [`tai_seconds`](../chrono/tai_clock "cpp/chrono/tai clock") (since C++20) [`tai_time`](../chrono/tai_clock "cpp/chrono/tai clock") (since C++20) [`Thursday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`time_point<>`](../chrono/time_point "cpp/chrono/time point") (since C++11) [`time_point_cast<>()`](../chrono/time_point/time_point_cast "cpp/chrono/time point/time point cast") (since C++11) [`time_zone()`](../chrono/time_zone "cpp/chrono/time zone") (since C++20) [`time_zone_link`](../chrono/time_zone_link "cpp/chrono/time zone link") (since C++20) [`treat_as_floating_point<>`](../chrono/treat_as_floating_point "cpp/chrono/treat as floating point") (since C++11) [`treat_as_floating_point_v<>`](../chrono/treat_as_floating_point "cpp/chrono/treat as floating point") (since C++17) [`Tuesday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`tzdb`](../chrono/tzdb "cpp/chrono/tzdb") (since C++20) [`tzdb_list`](../chrono/tzdb_list "cpp/chrono/tzdb list") (since C++20) ### U [`utc_clock`](../chrono/utc_clock "cpp/chrono/utc clock") (since C++20) [`utc_seconds`](../chrono/utc_clock "cpp/chrono/utc clock") (since C++20) [`utc_time`](../chrono/utc_clock "cpp/chrono/utc clock") (since C++20) ### W [`Wednesday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`weekday`](../chrono/weekday "cpp/chrono/weekday") (since C++20) [`weekday_indexed`](../chrono/weekday_indexed "cpp/chrono/weekday indexed") (since C++20) [`weekday_last`](../chrono/weekday_last "cpp/chrono/weekday last") (since C++20) ### Y [`year`](../chrono/year "cpp/chrono/year") (since C++20) [`year_month`](../chrono/year_month "cpp/chrono/year month") (since C++20) [`year_month_day`](../chrono/year_month_day "cpp/chrono/year month day") (since C++20) [`year_month_day_last`](../chrono/year_month_day_last "cpp/chrono/year month day last") (since C++20) [`year_month_weekday`](../chrono/year_month_weekday "cpp/chrono/year month weekday") (since C++20) [`year_month_weekday_last`](../chrono/year_month_weekday_last "cpp/chrono/year month weekday last") (since C++20) ### Z [`zoned_seconds`](../chrono/zoned_time "cpp/chrono/zoned time") (since C++20) [`zoned_time<>`](../chrono/zoned_time "cpp/chrono/zoned time") (since C++20) [`zoned_traits<>`](../chrono/zoned_traits "cpp/chrono/zoned traits") (since C++20)
programming_docs
cpp std::this_thread Symbol Index std::this\_thread Symbol Index ============================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::this_thread::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[G](#G) [S](#S) [Y](#Y)` ----------------------------- ### G [`get_id()`](../thread/get_id "cpp/thread/get id") (since C++11) ### S [`sleep_for<>()`](../thread/sleep_for "cpp/thread/sleep for") (since C++11) [`sleep_until<>()`](../thread/sleep_until "cpp/thread/sleep until") (since C++11) ### Y [`yield()`](../thread/yield "cpp/thread/yield") (since C++11) cpp std::pmr Symbol Index std::pmr Symbol Index ===================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::pmr::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. `[B](#B) [D](#D) [F](#F) [G](#G) [L](#L) [M](#M) [N](#N) [P](#P) [S](#S) [U](#U) [V](#V) [W](#W)` -------------------------------------------------------------------------------------------------------------- ### B [`basic_string<>`](../string/basic_string "cpp/string/basic string") (since C++17) ### C [`cmatch`](../regex/match_results "cpp/regex/match results") (since C++17) ### D [`deque<>`](../container/deque "cpp/container/deque") (since C++17) ### F [`forward_list<>`](../container/forward_list "cpp/container/forward list") (since C++17) ### G [`get_default_resource()`](../memory/get_default_resource "cpp/memory/get default resource") (since C++17) ### L [`list<>`](../container/list "cpp/container/list") (since C++17) ### M [`map<>`](../container/map "cpp/container/map") (since C++17) [`match_results<>`](../regex/match_results "cpp/regex/match results") (since C++17) [`memory_resource`](../memory/memory_resource "cpp/memory/memory resource") (since C++17) [`monotonic_buffer_resource`](../memory/monotonic_buffer_resource "cpp/memory/monotonic buffer resource") (since C++17) [`multimap<>`](../container/multimap "cpp/container/multimap") (since C++17) [`multiset<>`](../container/multiset "cpp/container/multiset") (since C++17) ### N [`new_delete_resource()`](../memory/new_delete_resource "cpp/memory/new delete resource") (since C++17) [`null_memory_resource()`](../memory/null_memory_resource "cpp/memory/null memory resource") (since C++17) ### P [`polymorphic_allocator<>`](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator") (since C++17) [`pool_options`](../memory/pool_options "cpp/memory/pool options") (since C++17) ### S [`set<>`](../container/set "cpp/container/set") (since C++17) [`set_default_resource()`](../memory/set_default_resource "cpp/memory/set default resource") (since C++17) [`smatch`](../regex/match_results "cpp/regex/match results") (since C++17) [`stacktrace`](../utility/basic_stacktrace "cpp/utility/basic stacktrace") (since C++23) [`string`](../string/basic_string "cpp/string/basic string") (since C++17) [`synchronized_pool_resource`](../memory/synchronized_pool_resource "cpp/memory/synchronized pool resource") (since C++17) ### U [`u16string<>`](../string/basic_string "cpp/string/basic string") (since C++17) [`u32string<>`](../string/basic_string "cpp/string/basic string") (since C++17) [`u8string<>`](../string/basic_string "cpp/string/basic string") (since C++17) [`unordered_map<>`](../container/unordered_map "cpp/container/unordered map") (since C++17) [`unordered_multimap<>`](../container/unordered_multimap "cpp/container/unordered multimap") (since C++17) [`unordered_multiset<>`](../container/unordered_multiset "cpp/container/unordered multiset") (since C++17) [`unordered_set<>`](../container/unordered_set "cpp/container/unordered set") (since C++17) [`unsynchronized_pool_resource`](../memory/unsynchronized_pool_resource "cpp/memory/unsynchronized pool resource") (since C++17) ### V [`vector<>`](../container/vector "cpp/container/vector") (since C++17) ### W [`wcmatch`](../regex/match_results "cpp/regex/match results") (since C++17) [`wsmatch`](../regex/match_results "cpp/regex/match results") (since C++17) [`wstring`](../string/basic_string "cpp/string/basic string") (since C++17) cpp std::ranges::views Symbol Index std::ranges::views Symbol Index =============================== This page tries to list all the symbols that are available from the *Standard Library* in the namespace `std::ranges::views::`. The symbols are written as follows: * Function names with `()`. * Templates with `<>`. ### Notes `std::ranges::views` can be accessed as `std::views`. `[A](#A) [C](#C) [D](#D) [E](#E) [F](#F) [I](#I) [J](#J) [K](#K) [L](#L) [R](#R) [S](#S) [T](#T) [V](#V) [Z](#Z)` -------------------------------------------------------------------------------------------------------------------------------- ### A [`adjacent`](../ranges/adjacent_view "cpp/ranges/adjacent view") (since C++23) [`adjacent_transform`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/adjacent_transform_view&action=edit&redlink=1 "cpp/ranges/adjacent transform view (page does not exist)") (since C++23) [`all`](../ranges/all_view "cpp/ranges/all view") (since C++20) [`all_t`](../ranges/all_view "cpp/ranges/all view") (since C++20) [`as_const`](../ranges/as_const_view "cpp/ranges/as const view") (since C++23) [`as_rvalue`](../ranges/as_rvalue_view "cpp/ranges/as rvalue view") (since C++23) ### C [`cartesian_product`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/cartesian_product_view&action=edit&redlink=1 "cpp/ranges/cartesian product view (page does not exist)") (since C++23) [`chunk`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_view&action=edit&redlink=1 "cpp/ranges/chunk view (page does not exist)") (since C++23) [`chunk_by`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_by_view&action=edit&redlink=1 "cpp/ranges/chunk by view (page does not exist)") (since C++23) [`common`](../ranges/common_view "cpp/ranges/common view") (since C++20) [`counted`](../ranges/view_counted "cpp/ranges/view counted") (since C++20) ### D [`drop`](../ranges/drop_view "cpp/ranges/drop view") (since C++20) [`drop_while`](../ranges/drop_while_view "cpp/ranges/drop while view") (since C++20) ### E [`elements<>`](../ranges/elements_view "cpp/ranges/elements view") (since C++20) [`empty<>`](../ranges/empty_view "cpp/ranges/empty view") (since C++20) ### F [`filter`](../ranges/filter_view "cpp/ranges/filter view") (since C++20) ### I [`iota`](../ranges/iota_view "cpp/ranges/iota view") (since C++20) [`istream<>`](../ranges/basic_istream_view "cpp/ranges/basic istream view") (since C++20) ### J [`join`](../ranges/join_view "cpp/ranges/join view") (since C++20) [`join_with`](../ranges/join_with_view "cpp/ranges/join with view") (since C++23) ### K [`keys`](../ranges/keys_view "cpp/ranges/keys view") (since C++20) ### L [`lazy_split`](../ranges/lazy_split_view "cpp/ranges/lazy split view") (since C++20) ### R [`repeat`](../ranges/repeat_view "cpp/ranges/repeat view") (since C++23) [`reverse`](../ranges/reverse_view "cpp/ranges/reverse view") (since C++20) ### S [`single`](../ranges/single_view "cpp/ranges/single view") (since C++20) [`slide`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/slide_view&action=edit&redlink=1 "cpp/ranges/slide view (page does not exist)") (since C++23) [`split`](../ranges/split_view "cpp/ranges/split view") (since C++20) [`stride`](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/stride_view&action=edit&redlink=1 "cpp/ranges/stride view (page does not exist)") (since C++23) ### T [`take`](../ranges/take_view "cpp/ranges/take view") (since C++20) [`take_while`](../ranges/take_while_view "cpp/ranges/take while view") (since C++20) [`transform`](../ranges/transform_view "cpp/ranges/transform view") (since C++20) ### V [`values`](../ranges/values_view "cpp/ranges/values view") (since C++20) ### Z [`zip`](../ranges/zip_view "cpp/ranges/zip view") (since C++23) [`zip_transform`](../ranges/zip_transform_view "cpp/ranges/zip transform view") (since C++23) cpp std::ios_base std::ios\_base ============== | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` class ios_base; ``` | | | The class `ios_base` is a multipurpose class that serves as the base class for all I/O stream classes. It maintains several kinds of data: 1) state information: stream status flags. 2) control information: flags that control formatting of both input and output sequences and the imbued locale. 3) private storage: indexed extensible data structure that allows both `long` and `void*` members, which may be implemented as two arbitrary-length arrays or a single array of two-element structs or another container. 4) callbacks: arbitrary number of user-defined functions to be called from [`imbue()`](ios_base/imbue "cpp/io/ios base/imbue"), [`std::basic_ios::copyfmt()`](basic_ios/copyfmt "cpp/io/basic ios/copyfmt"), and [`~ios_base()`](ios_base/~ios_base "cpp/io/ios base/~ios base"). Typical implementation holds member constants corresponding to all values of [`fmtflags`](ios_base/fmtflags "cpp/io/ios base/fmtflags"), [`iostate`](ios_base/iostate "cpp/io/ios base/iostate"), [`openmode`](ios_base/openmode "cpp/io/ios base/openmode"), and [`seekdir`](ios_base/seekdir "cpp/io/ios base/seekdir") shown below, member variables to maintain current precision, width, and formatting flags, the exception mask, the buffer error state, a resizeable container holding the callbacks, the currently imbued locale, the private storage, and a static integer variable for [`xalloc()`](ios_base/xalloc "cpp/io/ios base/xalloc"). ### Member functions | | | | --- | --- | | [(constructor)](ios_base/ios_base "cpp/io/ios base/ios base") | constructs the object (protected member function) | | [(destructor)](ios_base/~ios_base "cpp/io/ios base/~ios base") [virtual] | destructs the object (virtual public member function) | | [operator=](ios_base/operator= "cpp/io/ios base/operator=") | assigns to the stream (public member function) | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | --- | | Deprecated member types | | Type | Explanation | | `io_state` (deprecated) | integer type that may be used like `iostate` | | `open_mode` (deprecated) | integer type that may be used like `openmode` | | `seek_dir` (deprecated) | integer type that may be used like `seekdir` | | `streamoff` (deprecated) | unspecified type that may be used like `off_type`, not necessarily `[std::streamoff](streamoff "cpp/io/streamoff")` | | `streampos` (deprecated) | unspecified type that may be used like `pos_type`, not necessarily `[std::streampos](fpos "cpp/io/fpos")` | | (until C++17) | ### See also | | | | --- | --- | | [basic\_ios](basic_ios "cpp/io/basic ios") | manages an arbitrary stream buffer (class template) | cpp std::iostream_category std::iostream\_category ======================= | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` const std::error_category& iostream_category() noexcept; ``` | | (since C++11) | Obtains a reference to the static error category object for iostream errors. The object is required to override the virtual function `error_category::name()` to return a pointer to the string `"iostream"`. It is used to identify error codes provided in the exceptions of type `[std::ios\_base::failure](ios_base/failure "cpp/io/ios base/failure")`. ### Parameters (none). ### Return value A reference to the static object of unspecified runtime type, derived from `[std::error\_category](../error/error_category "cpp/error/error category")`. ### Example ``` #include <iostream> #include <fstream> int main() { std::ifstream f("doesn't exist"); try { f.exceptions(f.failbit); } catch (const std::ios_base::failure& e) { std::cout << "Caught an ios_base::failure.\n" << "Error code: " << e.code().value() << " (" << e.code().message() << ")\n" << "Error category: " << e.code().category().name() << '\n'; } } ``` Possible output: ``` Caught an ios_base::failure. Error code: 1 (unspecified iostream_category error) Error category: iostream ``` ### See also | | | | --- | --- | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [io\_errc](io_errc "cpp/io/io errc") (C++11) | the IO stream error codes (enum) |
programming_docs
cpp std::clog, std::wclog std::clog, std::wclog ===================== | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | | | --- | --- | --- | | ``` extern std::ostream clog; ``` | (1) | | | ``` extern std::wostream wclog; ``` | (2) | | The global objects `std::clog` and `std::wclog` control output to a stream buffer of implementation-defined type (derived from `[std::streambuf](basic_streambuf "cpp/io/basic streambuf")`), associated with the standard C output stream `[stderr](c/std_streams "cpp/io/c/std streams")`, but, unlike `[std::cerr](cerr "cpp/io/cerr")`/`[std::wcerr](cerr "cpp/io/cerr")`, these streams are not automatically flushed and cout is not automatically tie()'d with these streams. These objects are guaranteed to be initialized during or before the first time an object of type `[std::ios\_base::Init](ios_base/init "cpp/io/ios base/Init")` is constructed and are available for use in the constructors and destructors of static objects with [ordered initialization](../language/initialization#Non-local_variables "cpp/language/initialization") (as long as [`<iostream>`](../header/iostream "cpp/header/iostream") is included before the object is defined). Unless `std::ios_base::sync_with_stdio(false)` has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output. ### Notes The 'c' in the name refers to "character" ([stroustrup.com FAQ](http://www.stroustrup.com/bs_faq2.html#cout)); `clog` means "character log" and `wclog` means "wide character log" ### Example ``` #include <iostream> struct Foo { int n; Foo() { std::clog << "static constructor\n"; } ~Foo() { std::clog << "static destructor\n"; } }; Foo f; // static object int main() { std::clog << "main function\n"; } ``` Output: ``` static constructor main function static destructor ``` ### See also | | | | --- | --- | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | [cerrwcerr](cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [coutwcout](cout "cpp/io/cout") | writes to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`(global object) | | [stdinstdoutstderr](c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | cpp C-style file input/output C-style file input/output ========================= The C I/O subset of the C++ standard library implements C-style stream input/output operations. The [`<cstdio>`](../header/cstdio "cpp/header/cstdio") header provides generic file operation support and supplies functions with narrow and multibyte character input/output capabilities, and the [`<cwchar>`](../header/cwchar "cpp/header/cwchar") header provides functions with wide character input/output capabilities. C streams are denoted by objects of type `[std::FILE](c/file "cpp/io/c/FILE")` that can only be accessed and manipulated through pointers of type `[std::FILE](http://en.cppreference.com/w/cpp/io/c/FILE)\*`. Each C stream is associated with an external physical device (file, standard input stream, printer, serial port, etc). ### Types | Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | --- | | [FILE](c/file "cpp/io/c/FILE") | object type, capable of holding all information needed to control a C I/O stream (typedef) | | [fpos\_t](c/fpos_t "cpp/io/c/fpos t") | complete non-array object type, capable of uniquely specifying a position in a file, including its multibyte parse state (typedef) | ### Predefined standard streams | Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | --- | | [stdinstdoutstderr](c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | ### Functions | Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | --- | | File access | | [fopen](c/fopen "cpp/io/c/fopen") | opens a file (function) | | [freopen](c/freopen "cpp/io/c/freopen") | open an existing stream with a different name (function) | | [fclose](c/fclose "cpp/io/c/fclose") | closes a file (function) | | [fflush](c/fflush "cpp/io/c/fflush") | synchronizes an output stream with the actual file (function) | | [fwide](c/fwide "cpp/io/c/fwide") | switches a file stream between wide character I/O and narrow character I/O (function) | | [setbuf](c/setbuf "cpp/io/c/setbuf") | sets the buffer for a file stream (function) | | [setvbuf](c/setvbuf "cpp/io/c/setvbuf") | sets the buffer and its size for a file stream (function) | | Direct input/output | | [fread](c/fread "cpp/io/c/fread") | reads from a file (function) | | [fwrite](c/fwrite "cpp/io/c/fwrite") | writes to a file (function) | | Unformatted input/output | | Byte/multibyte character | | [fgetcgetc](c/fgetc "cpp/io/c/fgetc") | gets a character from a file stream (function) | | [fgets](c/fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [fputcputc](c/fputc "cpp/io/c/fputc") | writes a character to a file stream (function) | | [fputs](c/fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [getchar](c/getchar "cpp/io/c/getchar") | reads a character from `[stdin](c/std_streams "cpp/io/c/std streams")` (function) | | [gets](c/gets "cpp/io/c/gets") (deprecated in C++11)(removed in C++14) | reads a character string from `[stdin](c/std_streams "cpp/io/c/std streams")` (function) | | [putchar](c/putchar "cpp/io/c/putchar") | writes a character to `[stdout](c/std_streams "cpp/io/c/std streams")` (function) | | [puts](c/puts "cpp/io/c/puts") | writes a character string to `[stdout](c/std_streams "cpp/io/c/std streams")` (function) | | [ungetc](c/ungetc "cpp/io/c/ungetc") | puts a character back into a file stream (function) | | Wide character | | [fgetwcgetwc](c/fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [fgetws](c/fgetws "cpp/io/c/fgetws") | gets a wide string from a file stream (function) | | [fputwcputwc](c/fputwc "cpp/io/c/fputwc") | writes a wide character to a file stream (function) | | [fputws](c/fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [getwchar](c/getwchar "cpp/io/c/getwchar") | reads a wide character from `[stdin](c/std_streams "cpp/io/c/std streams")` (function) | | [putwchar](c/putwchar "cpp/io/c/putwchar") | writes a wide character to `[stdout](c/std_streams "cpp/io/c/std streams")` (function) | | [ungetwc](c/ungetwc "cpp/io/c/ungetwc") | puts a wide character back into a file stream (function) | | Formatted input/output | | Byte/multibyte character | | [scanffscanfsscanf](c/fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vscanfvfscanfvsscanf](c/vfscanf "cpp/io/c/vfscanf") (C++11)(C++11)(C++11) | reads formatted input from `[stdin](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [printffprintfsprintfsnprintf](c/fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vprintfvfprintfvsprintfvsnprintf](c/vfprintf "cpp/io/c/vfprintf") (C++11) | prints formatted output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | Wide character | | [wscanffwscanfswscanf](c/fwscanf "cpp/io/c/fwscanf") | reads formatted wide character input from `[stdin](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vwscanfvfwscanfvswscanf](c/vfwscanf "cpp/io/c/vfwscanf") (C++11)(C++11)(C++11) | reads formatted wide character input from `[stdin](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [wprintffwprintfswprintf](c/fwprintf "cpp/io/c/fwprintf") | prints formatted wide character output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vwprintfvfwprintfvswprintf](c/vfwprintf "cpp/io/c/vfwprintf") | prints formatted wide character output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | File positioning | | [ftell](c/ftell "cpp/io/c/ftell") | returns the current file position indicator (function) | | [fgetpos](c/fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [fseek](c/fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [fsetpos](c/fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [rewind](c/rewind "cpp/io/c/rewind") | moves the file position indicator to the beginning in a file (function) | | Error handling | | [clearerr](c/clearerr "cpp/io/c/clearerr") | clears errors (function) | | [feof](c/feof "cpp/io/c/feof") | checks for the end-of-file (function) | | [ferror](c/ferror "cpp/io/c/ferror") | checks for a file error (function) | | [perror](c/perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](c/std_streams "cpp/io/c/std streams")` (function) | | Operations on files | | [remove](c/remove "cpp/io/c/remove") | erases a file (function) | | [rename](c/rename "cpp/io/c/rename") | renames a file (function) | | [tmpfile](c/tmpfile "cpp/io/c/tmpfile") | creates and opens a temporary, auto-removing file (function) | | [tmpnam](c/tmpnam "cpp/io/c/tmpnam") | returns a unique filename (function) | ### Macro constants | Defined in header `[<cstdio>](../header/cstdio "cpp/header/cstdio")` | | --- | | EOF | integer constant expression of type `int` and negative value (macro constant) | | FOPEN\_MAX | number of files that can be open simultaneously (macro constant) | | FILENAME\_MAX | size needed for an array of `char` to hold the longest supported file name (macro constant) | | BUFSIZ | size of the buffer used by `[std::setbuf](c/setbuf "cpp/io/c/setbuf")` (macro constant) | | \_IOFBF\_IOLBF\_IONBF | argument to `[std::setbuf](c/setbuf "cpp/io/c/setbuf")` indicating fully buffered I/Oargument to `[std::setbuf](c/setbuf "cpp/io/c/setbuf")` indicating line buffered I/Oargument to `[std::setbuf](c/setbuf "cpp/io/c/setbuf")` indicating unbuffered I/O (macro constant) | | SEEK\_SETSEEK\_CURSEEK\_END | argument to `[std::fseek](c/fseek "cpp/io/c/fseek")` indicating seeking from beginning of the fileargument to `[std::fseek](c/fseek "cpp/io/c/fseek")` indicating seeking from the current file positionargument to `[std::fseek](c/fseek "cpp/io/c/fseek")` indicating seeking from end of the file (macro constant) | | TMP\_MAX | maximum number of unique filenames that is guaranteed to be generatable by `[std::tmpnam](c/tmpnam "cpp/io/c/tmpnam")` (macro constant) | | L\_tmpnam | size needed for an array of `char` to hold the result of `[std::tmpnam](c/tmpnam "cpp/io/c/tmpnam")` (macro constant) | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/io "c/io") for File input/output | cpp std::vprint_unicode std::vprint\_unicode ==================== | Defined in header `[<print>](../header/print "cpp/header/print")` | | | | --- | --- | --- | | ``` void vprint_unicode( std::FILE* stream, std::string_view fmt, std::format_args args ); ``` | (1) | (since C++23) | | ``` void vprint_unicode( std::string_view fmt, std::format_args args ); ``` | (2) | (since C++23) | Format `args` according to the format string `fmt`, and writes the result to the stream. Let `out` be a temporary `[string](../string/basic_string "cpp/string/basic string")` produced by formatting the arguments in `args` with `[std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(fmt, args)`. 1) If `stream` [refers to a terminal](#Notes) capable of displaying Unicode, writes `out` to this terminal using [the native Unicode API](#Notes). Otherwise, writes unmodified `out` to the `stream`. 2) same as (1) when `stream` is equal to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`, i.e. ``` std::vprint_unicode(stdout, fmt, args); ``` The behavior is undefined if: * `stream` is not a valid pointer to a C stream; * `out` contains invalid Unicode [code units](https://en.wikipedia.org/wiki/Character_encoding#Terminology "enwiki:Character encoding"). ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](../utility/format/formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args | - | arguments to be formatted | ### Return value (none). ### Exceptions * `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. * `[std::system\_error](../error/system_error "cpp/error/system error")`, if writing to the stream fails. * Propagate exception thrown by any [formatter](../utility/format/formatter "cpp/utility/format/formatter"), e.g. `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")`. ### Notes The C++ standard encourages the implementers to produce a diagnostic message if `out` contains invalid Unicode code units. On POSIX, the stream refers to a terminal if the expression `isatty(fileno(stream)) != 0` holds true (see POSIX documentation for [`isatty`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/isatty.html), and [`fileno`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fileno.html)). On Windows, the stream refers to a terminal if the expression `GetConsoleMode(_get_osfhandle(_fileno(stream)))` returns nonzero (see Windows documentation for [`GetConsoleMode`](https://docs.microsoft.com/en-us/windows/console/getconsolemode), [`_get_osfhandle`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle), and [`_fileno`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fileno)). The native Unicode API on Windows is [`WriteConsoleW`](https://docs.microsoft.com/en-us/windows/console/writeconsole). If invoking the native Unicode API requires transcoding, the invalid code units are substituted with `U+FFFD` REPLACEMENT CHARACTER (see "The Unicode Standard Version 14.0 - Core Specification", [Chapter 3.9](#External_links)). | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_print`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ### See also | | | | --- | --- | | [vprint\_nonunicode](vprint_nonunicode "cpp/io/vprint nonunicode") (C++23) | prints to `[stdout](c/std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_unicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_unicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint unicode (page does not exist)") (C++23) | performs Unicode aware output using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [print](print "cpp/io/print") (C++23) | prints to `[stdout](c/std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [format](../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | ### External links * [Unicode](https://en.wikipedia.org/wiki/Unicode "enwiki:Unicode") * [The Unicode Standard Version 14.0 - Core Specification](https://www.unicode.org/versions/Unicode14.0.0/UnicodeStandard-14.0.pdf) cpp std::basic_syncbuf std::basic\_syncbuf =================== | Defined in header `[<syncstream>](../header/syncstream "cpp/header/syncstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_syncbuf : public std::basic_streambuf<CharT, Traits> ``` | | (since C++20) | `std::basic_syncbuf` is a wrapper for a `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` (provided at construction time as a pointer). It accumulates output in its own internal buffer, and atomically transmits its entire contents to the wrapped buffer on destruction and when explicitly requested, so that they appear as a contiguous sequence of characters. It guarantees that there are no data races and no interleaving of characters sent to the wrapped buffer as long as all other outputs made to the same buffer are made through, possibly different, instances of `std::basic_syncbuf`. Typical implementation of `std::basic_syncbuf` holds a pointer to the wrapped `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")`, a boolean flag indicating whether the buffer will transmit its contents to the wrapped buffer on sync (flush), a boolean flag indicating a pending flush when the policy is to not emit on sync, an internal buffer that uses `Allocator` (such as std::string), and a pointer to a mutex used to synchronize emit between multiple threads accessing the same wrapped stream buffer (these mutexes may be in a hash map with pointers to basic\_streambuf objects used as keys). Like other streambuf classes, `std::basic_syncbuf` is normally only accessed through the corresponding stream, [`std::osyncstream`](basic_osyncstream "cpp/io/basic osyncstream"), not directly. Two specializations for common character types are also defined: | Defined in header `[<syncstream>](../header/syncstream "cpp/header/syncstream")` | | --- | | Type | Definition | | `syncbuf` | `basic_syncbuf<char>` | | `wsyncbuf` | `basic_syncbuf<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | | `streambuf_type` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<CharT, Traits>` | ### Member functions | | | --- | | Public member functions | | [(constructor)](basic_syncbuf/basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function) | | [operator=](basic_syncbuf/operator= "cpp/io/basic syncbuf/operator=") | assigns a basic\_syncbuf object (public member function) | | [swap](basic_syncbuf/swap "cpp/io/basic syncbuf/swap") | swaps two basic\_syncbuf objects (public member function) | | [(destructor)](basic_syncbuf/~basic_syncbuf "cpp/io/basic syncbuf/~basic syncbuf") | destroys the basic\_syncbuf and emits its internal buffer (public member function) | | [emit](basic_syncbuf/emit "cpp/io/basic syncbuf/emit") | atomically transmits the entire internal buffer to the wrapped streambuf (public member function) | | [get\_wrapped](basic_syncbuf/get_wrapped "cpp/io/basic syncbuf/get wrapped") | retrieves the wrapped streambuf pointer (public member function) | | [get\_allocator](basic_syncbuf/get_allocator "cpp/io/basic syncbuf/get allocator") | retrieves the allocator used by this basic\_syncbuf (public member function) | | [set\_emit\_on\_sync](basic_syncbuf/set_emit_on_sync "cpp/io/basic syncbuf/set emit on sync") | changes the current emit-on-sync policy (public member function) | | Protected member functions | | [sync](basic_syncbuf/sync "cpp/io/basic syncbuf/sync") | either emits, or records a pending flush, depending on the current emit-on-sync policy (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_syncbuf)](basic_syncbuf/swap2 "cpp/io/basic syncbuf/swap2") (C++20) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf") ---------------------------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function of `std::basic_streambuf<CharT,Traits>`) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | ### Protected member functions | | | | --- | --- | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) |
programming_docs
cpp std::streamsize std::streamsize =============== | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` typedef /*implementation-defined*/ streamsize; ``` | | | The type `std::streamsize` is an implementation-defined signed integral type used to represent the number of characters transferred in an I/O operation or the size of an I/O buffer. It is used as a signed counterpart of `[std::size\_t](../types/size_t "cpp/types/size t")`, similar to the POSIX type `ssize_t`. Except in the constructors of `[std::strstreambuf](strstreambuf "cpp/io/strstreambuf")`, negative values of `std::streamsize` are never used. ### See also | | | | --- | --- | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::strstream std::strstream ============== | Defined in header `[<strstream>](../header/strstream "cpp/header/strstream")` | | | | --- | --- | --- | | ``` class strstream : public std::iostream ``` | | (deprecated in C++98) | The class `strstream` implements input and output operations on array-backed streams. It essentially wraps a raw array I/O device implementation (`[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`) into the higher-level interface of `[std::basic\_iostream](basic_iostream "cpp/io/basic iostream")`. The typical implementation of `strstream` holds only one non-derived data member: an object of type `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`. ### Notes After any call to `str()`, a call to `freeze(false)` is required to allow the destructor to deallocate the buffer as necessary. Before any call to `str()` that uses the result as a C string, the buffer must be null-terminated, typically with `[std::ends](manip/ends "cpp/io/manip/ends")`. `strstream` has been deprecated since C++98, `[std::stringstream](basic_stringstream "cpp/io/basic stringstream")` and [boost::iostreams::array](http://www.boost.org/doc/libs/release/libs/iostreams/doc/classes/array.html#array) are the recommended replacements. ### Member functions | | | | --- | --- | | [(constructor)](strstream/strstream "cpp/io/strstream/strstream") | constructs an strstream, optionally allocating the buffer (public member function) | | [(destructor)](strstream/~strstream "cpp/io/strstream/~strstream") [virtual] | destructs a strstream, optionally deallocating the buffer (virtual public member function) | | [rdbuf](strstream/rdbuf "cpp/io/strstream/rdbuf") | obtains a pointer to the associated strstreambuf (public member function) | | [str](strstream/str "cpp/io/strstream/str") | accesses the output buffer (public member function) | | [freeze](strstream/freeze "cpp/io/strstream/freeze") | disables/enables automatic reallocation (public member function) | | [pcount](strstream/pcount "cpp/io/strstream/pcount") | obtains the number of characters written (public member function) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | cpp std::basic_ispanstream std::basic\_ispanstream ======================= | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ispanstream; ``` | | (since C++23) | The class template `std::basic_ispantream` implements input operations on streams based on fixed buffers. At the low level, the class essentially wraps a raw device implementation of `std::basic_spanbuf` into a higher-level interface of `[std::basic\_istream](basic_istream "cpp/io/basic istream")`. The complete interface to unique `std::basic_spanbuf` members is provided. Typical implementations of `std::basic_ispantream` only add one member subobject: the wrapped `std::basic_spanbuf`. ![std-basic ispanstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | --- | | Type | Definition | | `ispanstream` | `ispanstream<char>` | | `wispanstream` | `ispanstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ispanstream/basic_ispanstream "cpp/io/basic ispanstream/basic ispanstream") (C++23) | constructs the `basic_ispanstream` (public member function) | | **(destructor)** [virtual] (C++23) | destroys the `basic_ispanstream` (virtual public member function) | | [operator=](basic_ispanstream/operator= "cpp/io/basic ispanstream/operator=") (C++23) | move-assignments the `basic_ispanstream` (public member function) | | [swap](basic_ispanstream/swap "cpp/io/basic ispanstream/swap") (C++23) | swaps two `basic_ispanstream` objects (public member function) | | [rdbuf](basic_ispanstream/rdbuf "cpp/io/basic ispanstream/rdbuf") (C++23) | obtains the address of the wrapped raw `span` device object (public member function) | | Underlying buffer operations | | [span](basic_ispanstream/span "cpp/io/basic ispanstream/span") (C++23) | gets or sets the underlying buffer of the wrapped `span` device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_ispanstream)](basic_ispanstream/swap2 "cpp/io/basic ispanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::basic_ostringstream std::basic\_ostringstream ========================= | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_ostringstream; ``` | | | The class template `std::basic_ostringstream` implements output operations on string based streams. It effectively stores an instance of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` and performs output operations to it. At the low level, the class essentially wraps a raw string device implementation of `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` into a higher-level interface of `[std::basic\_ostream](basic_ostream "cpp/io/basic ostream")`. The complete interface to unique `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` members is provided. ![std-basic ostringstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | --- | | Type | Definition | | `ostringstream` | `basic_ostringstream<char>` | | `wostringstream` | `basic_ostringstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ostringstream/basic_ostringstream "cpp/io/basic ostringstream/basic ostringstream") | constructs the string stream (public member function) | | [operator=](basic_ostringstream/operator= "cpp/io/basic ostringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](basic_ostringstream/swap "cpp/io/basic ostringstream/swap") (C++11) | swaps two string streams (public member function) | | [rdbuf](basic_ostringstream/rdbuf "cpp/io/basic ostringstream/rdbuf") | returns the underlying raw string device object (public member function) | | String operations | | [str](basic_ostringstream/str "cpp/io/basic ostringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [view](basic_ostringstream/view "cpp/io/basic ostringstream/view") (C++20) | obtains a view over the contents of underlying string device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_ostringstream)](basic_ostringstream/swap2 "cpp/io/basic ostringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | cpp std::ostrstream std::ostrstream =============== | Defined in header `[<strstream>](../header/strstream "cpp/header/strstream")` | | | | --- | --- | --- | | ``` class ostrstream : public std::ostream ``` | | (deprecated in C++98) | The class `ostrstream` implements output operations on array-backed streams. It essentially wraps a raw array I/O device implementation (`[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`) into the higher-level interface of `[std::basic\_ostream](basic_ostream "cpp/io/basic ostream")`. The typical implementation of `ostrstream` holds only one non-derived data member: an object of type `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`. ### Notes After any call to `str()`, a call to `freeze(false)` is required to allow the destructor to deallocate the buffer as necessary. Before any call to `str()` that uses the result as a C string, the buffer must be null-terminated, typically with `[std::ends](manip/ends "cpp/io/manip/ends")`. `ostrstream` has been deprecated since C++98, `[std::ostringstream](basic_ostringstream "cpp/io/basic ostringstream")` and [boost::iostreams::array\_sink](http://www.boost.org/doc/libs/release/libs/iostreams/doc/classes/array.html#array_sink) are the recommended replacements. ### Member functions | | | | --- | --- | | [(constructor)](ostrstream/ostrstream "cpp/io/ostrstream/ostrstream") | constructs an strstream, optionally allocating the buffer (public member function) | | [(destructor)](ostrstream/~ostrstream "cpp/io/ostrstream/~ostrstream") [virtual] | destructs a strstream, optionally deallocating the buffer (virtual public member function) | | [rdbuf](ostrstream/rdbuf "cpp/io/ostrstream/rdbuf") | obtains a pointer to the associated strstreambuf (public member function) | | [str](ostrstream/str "cpp/io/ostrstream/str") | accesses the output buffer (public member function) | | [freeze](ostrstream/freeze "cpp/io/ostrstream/freeze") | disables/enables automatic reallocation (public member function) | | [pcount](ostrstream/pcount "cpp/io/ostrstream/pcount") | obtains the number of characters written (public member function) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::basic_iostream std::basic\_iostream ==================== | Defined in header `[<istream>](../header/istream "cpp/header/istream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_iostream; ``` | | | The class template `basic_iostream` provides support for high level input/output operations on streams. The supported operations include sequential reading or writing and formatting. This functionality is implemented over the interface provided by the `basic_streambuf` class. It is accessed through `basic_ios` class. ![std-basic iostream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are defined: | Defined in header `[<istream>](../header/istream "cpp/header/istream")` | | --- | | Type | Definition | | `iostream` | `basic_iostream<char>` | | `wiostream` | `basic_iostream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_iostream/basic_iostream "cpp/io/basic iostream/basic iostream") | constructs the object (public member function) | | [(destructor)](basic_iostream/~basic_iostream "cpp/io/basic iostream/~basic iostream") [virtual] | destructs the object (virtual public member function) | ### Protected member functions | | | | --- | --- | | [operator=](basic_iostream/operator= "cpp/io/basic iostream/operator=") (C++11) | move-assigns another `basic_iostream` (protected member function) | | [swap](basic_iostream/swap "cpp/io/basic iostream/swap") (C++11) | exchanges the state with another `basic_iostream` (public member function) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### See also [Input/output manipulators](manip "cpp/io/manip"). cpp std::basic_ostream std::basic\_ostream =================== | Defined in header `[<ostream>](../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ostream : virtual public std::basic_ios<CharT, Traits> ``` | | | The class template `basic_ostream` provides support for high level output operations on character streams. The supported operations include formatted output (e.g. integer values) and unformatted output (e.g. raw characters and character arrays). This functionality is implemented in terms of the interface provided by the `basic_streambuf` class, accessed through the `basic_ios` base class. In typical implementations, `basic_ostream` has no non-inherited data members. ![std-basic ostream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<ostream>](../header/ostream "cpp/header/ostream")` | | --- | | Type | Definition | | `ostream` | `basic_ostream<char>` | | `wostream` | `basic_ostream<wchar_t>` | ### Global objects Six global basic\_ostream objects are provided by the standard library. | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | --- | | [coutwcout](cout "cpp/io/cout") | writes to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`(global object) | | [cerrwcerr](cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [clogwclog](clog "cpp/io/clog") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`(global object) | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ostream/basic_ostream "cpp/io/basic ostream/basic ostream") | constructs the object (public member function) | | [(destructor)](basic_ostream/~basic_ostream "cpp/io/basic ostream/~basic ostream") [virtual] | destructs the object (virtual public member function) | | [operator=](basic_ostream/operator= "cpp/io/basic ostream/operator=") (C++11) | move-assigns from another `basic_ostream` (protected member function) | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function) | | [swap](basic_ostream/swap "cpp/io/basic ostream/swap") (C++11) | swaps stream objects, except for the associated buffer (protected member function) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class) | ### Non-member functions | | | | --- | --- | | [operator<<(std::basic\_ostream)](basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [print](basic_ostream/print "cpp/io/basic ostream/print") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [println](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/println&action=edit&redlink=1 "cpp/io/basic ostream/println (page does not exist)") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments with appended `'\n'` (function template) | | [vprint\_unicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_unicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint unicode (page does not exist)") (C++23) | performs Unicode aware output using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_nonunicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_nonunicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint nonunicode (page does not exist)") (C++23) | outputs character data using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp Input/output manipulators Input/output manipulators ========================= Manipulators are helper functions that make it possible to control input/output streams using `operator<<` or `operator>>`. The manipulators that are invoked without arguments (e.g. `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << [std::boolalpha](http://en.cppreference.com/w/cpp/io/manip/boolalpha);` or `[std::cin](http://en.cppreference.com/w/cpp/io/cin) >> [std::hex](http://en.cppreference.com/w/cpp/io/manip/hex);`) are implemented as functions that take a reference to a stream as their only argument. The special overloads of [`basic_ostream::operator<<`](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") and [`basic_istream::operator>>`](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") accept pointers to these functions. These functions (or instantiations of function templates) are the only [addressable functions](../language/extending_std#Addressable_functions "cpp/language/extending std") in the standard library. (since C++20). The manipulators that are invoked with arguments (e.g. `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << [std::setw](http://en.cppreference.com/w/cpp/io/manip/setw)(10);`) are implemented as functions returning objects of unspecified type. These manipulators define their own `operator<<` or `operator>>` which perform the requested manipulation. | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | --- | | [boolalphanoboolalpha](manip/boolalpha "cpp/io/manip/boolalpha") | switches between textual and numeric representation of booleans (function) | | [showbasenoshowbase](manip/showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | | [showpointnoshowpoint](manip/showpoint "cpp/io/manip/showpoint") | controls whether decimal point is always included in floating-point representation (function) | | [showposnoshowpos](manip/showpos "cpp/io/manip/showpos") | controls whether the `+` sign used with non-negative numbers (function) | | [skipwsnoskipws](manip/skipws "cpp/io/manip/skipws") | controls whether leading whitespace is skipped on input (function) | | [uppercasenouppercase](manip/uppercase "cpp/io/manip/uppercase") | controls whether uppercase characters are used with some output formats (function) | | [unitbufnounitbuf](manip/unitbuf "cpp/io/manip/unitbuf") | controls whether output is flushed after each operation (function) | | [internalleftright](manip/left "cpp/io/manip/left") | sets the placement of fill characters (function) | | [dechexoct](manip/hex "cpp/io/manip/hex") | changes the base used for integer I/O (function) | | [fixedscientifichexfloatdefaultfloat](manip/fixed "cpp/io/manip/fixed") (C++11)(C++11) | changes formatting used for floating-point I/O (function) | | Defined in header `[<istream>](../header/istream "cpp/header/istream")` | | [ws](manip/ws "cpp/io/manip/ws") | consumes whitespace (function template) | | Defined in header `[<ostream>](../header/ostream "cpp/header/ostream")` | | [ends](manip/ends "cpp/io/manip/ends") | outputs `'\0'` (function template) | | [flush](manip/flush "cpp/io/manip/flush") | flushes the output stream (function template) | | [endl](manip/endl "cpp/io/manip/endl") | outputs `'\n'` and flushes the output stream (function template) | | [emit\_on\_flushnoemit\_on\_flush](manip/emit_on_flush "cpp/io/manip/emit on flush") (C++20) | controls whether a stream's [`basic_syncbuf`](basic_syncbuf "cpp/io/basic syncbuf") emits on flush (function template) | | [flush\_emit](manip/flush_emit "cpp/io/manip/flush emit") (C++20) | flushes a stream and emits the content if it is using a [`basic_syncbuf`](basic_syncbuf "cpp/io/basic syncbuf") (function template) | | Defined in header `[<iomanip>](../header/iomanip "cpp/header/iomanip")` | | [resetiosflags](manip/resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](manip/setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | | [setbase](manip/setbase "cpp/io/manip/setbase") | changes the base used for integer I/O (function) | | [setfill](manip/setfill "cpp/io/manip/setfill") | changes the fill character (function template) | | [setprecision](manip/setprecision "cpp/io/manip/setprecision") | changes floating-point precision (function) | | [setw](manip/setw "cpp/io/manip/setw") | changes the width of the next input/output field (function) | | [get\_money](manip/get_money "cpp/io/manip/get money") (C++11) | parses a monetary value (function template) | | [put\_money](manip/put_money "cpp/io/manip/put money") (C++11) | formats and outputs a monetary value (function template) | | [get\_time](manip/get_time "cpp/io/manip/get time") (C++11) | parses a date/time value of specified format (function template) | | [put\_time](manip/put_time "cpp/io/manip/put time") (C++11) | formats and outputs a date/time value according to the specified format (function template) | | [quoted](manip/quoted "cpp/io/manip/quoted") (C++14) | inserts and extracts quoted strings with embedded spaces (function template) | cpp std::basic_stringstream std::basic\_stringstream ======================== | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_stringstream; ``` | | | The class template `std::basic_stringstream` implements input and output operations on string based streams. It effectively stores an instance of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` and performs the input and output operations on it. At the low level, the class essentially wraps a raw string device implementation of `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` into a higher-level interface of `[std::basic\_iostream](basic_iostream "cpp/io/basic iostream")`. The complete interface to unique `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` members is provided. ![std-basic stringstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | --- | | Type | Definition | | `stringstream` | `basic_stringstream<char>` | | `wstringstream` | `basic_stringstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | ### Member functions | | | | --- | --- | | [(constructor)](basic_stringstream/basic_stringstream "cpp/io/basic stringstream/basic stringstream") | constructs the string stream (public member function) | | [operator=](basic_stringstream/operator= "cpp/io/basic stringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](basic_stringstream/swap "cpp/io/basic stringstream/swap") (C++11) | swaps two string streams (public member function) | | [rdbuf](basic_stringstream/rdbuf "cpp/io/basic stringstream/rdbuf") | returns the underlying raw string device object (public member function) | | String operations | | [str](basic_stringstream/str "cpp/io/basic stringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [view](basic_stringstream/view "cpp/io/basic stringstream/view") (C++20) | obtains a view over the contents of underlying string device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_istringstream)](basic_istringstream/swap2 "cpp/io/basic istringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::print std::print ========== | Defined in header `[<print>](../header/print "cpp/header/print")` | | | | --- | --- | --- | | ``` template< class... Args > void print( std::FILE* stream, std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++23) | | ``` template< class... Args > void print( std::format_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++23) | Format `args` according to the format string `fmt`, and print the result to a stream. 1) if [ordinary literal encoding](../language/charset "cpp/language/charset") of `fmt` or any parameter in `args...` is UTF-8 (where applicable), equivalent to: ``` std::vprint_unicode(stream, fmt.get(), std::make_format_args(std::forward<Args>(args)...)); ``` Otherwise, equivalent to: ``` std::vprint_nonunicode(stream, fmt.get(), std::make_format_args(std::forward<Args>(args)...)); ``` 2) same as (1) when `stream` is equal to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`, i.e. ``` std::print(stdout, fmt, std::forward<Args>(args)...); ``` The behavior is undefined if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, char>` does not model `std::formattable` for any `Ti` in `Args` (as required by `[std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)`). ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](../utility/format/formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | ### Return value (none). ### Exceptions * `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. * `[std::system\_error](../error/system_error "cpp/error/system error")`, if writing to the stream fails. * Propagate exception thrown by any [formatter](../utility/format/formatter "cpp/utility/format/formatter"), e.g. `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")`. ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_print`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ``` #include <cstdio> #include <filesystem> #include <print> int main() { std::print("{0} {2}{1}!\n", "Hello", 23, "C++"); // overload (1) const auto tmp {std::filesystem::temp_directory_path() / "test.txt"}; if (std::FILE* stream {std::fopen(tmp.c_str(), "w")}) { std::print(stream, "File: {}", tmp.string()); // overload (2) std::fclose(stream); } } ``` Output: ``` Hello C++23! ``` ### See also | | | | --- | --- | | [println](println "cpp/io/println") (C++23) | same as `std::print` except that each print is terminated by additional new line (function template) | | [print](basic_ostream/print "cpp/io/basic ostream/print") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [format](../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [printffprintfsprintfsnprintf](c/fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | cpp std::basic_streambuf std::basic\_streambuf ===================== | Defined in header `[<streambuf>](../header/streambuf "cpp/header/streambuf")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_streambuf; ``` | | | The class `basic_streambuf` controls input and output to a character sequence. It includes and provides access to. 1. The *controlled character sequence*, also called the *buffer*, which may contain *input sequence* (also called *get area*) for buffering the input operations and/or *output sequence* (also called *put area*) for buffering the output operations. 2. The *associated character sequence*, also called *source* (for input) or *sink* (for output). This may be an entity that is accessed through OS API (file, TCP socket, serial port, other character device), or it may be an object (std::vector, array, string literal), that can be interpreted as a character source or sink. The I/O stream objects `[std::basic\_istream](basic_istream "cpp/io/basic istream")` and `[std::basic\_ostream](basic_ostream "cpp/io/basic ostream")`, as well as all objects derived from them (`[std::ofstream](basic_ofstream "cpp/io/basic ofstream")`, `[std::stringstream](basic_stringstream "cpp/io/basic stringstream")`, etc), are implemented entirely in terms of `std::basic_streambuf`. The controlled character sequence is an array of `CharT` which, at all times, represents a subsequence, or a "window" into the associated character sequence. Its state is described by three pointers: 1. The *beginning pointer*, always points at the lowest element of the buffer 2. The *next pointer*, points at the element that is the next candidate for reading or writing 3. The *end pointer*, points one past the end of the buffer. A `basic_streambuf` object may support input (in which case the buffer described by the beginning, next, and end pointers is called *get area*), output (*put area*), or input and output simultaneously. In latter case, six pointers are tracked, which may all point to elements of the same character array or two individual arrays. If the next pointer is less than the end pointer in the put area, a *write position* is available. The next pointer can be dereferenced and assigned to. If the next pointer is less than the end pointer in the get area, a *read position* is available. The next pointer can be dereferenced and read from. If the next pointer is greater than the beginning pointer in a get area, a *putback position* is available, and the next pointer may be decremented, dereferenced, and assigned to, in order to put a character back into the get area. The character representation and encoding in the controlled sequence may be different from the character representations in the associated sequence, in which case a `[std::codecvt](../locale/codecvt "cpp/locale/codecvt")` locale facet is typically used to perform the conversion. Common examples are UTF-8 (or other multibyte) files accessed through `[std::wfstream](basic_fstream "cpp/io/basic fstream")` objects: the controlled sequence consists of `wchar_t` characters, but the associated sequence consists of bytes. Typical implementation of the `std::basic_streambuf` base class holds only the six `CharT*` pointers and a copy of `[std::locale](../locale/locale "cpp/locale/locale")` as data members. In addition, implementations may keep cached copies of locale facets, which are invalidated whenever `imbue()` is called. The concrete buffers such as `[std::basic\_filebuf](basic_filebuf "cpp/io/basic filebuf")` or `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` are derived from `std::basic_streambuf`. ![std-streambuf.svg]() Two convenience typedefs are provided by the standard library. | Defined in header `[<streambuf>](../header/streambuf "cpp/header/streambuf")` | | --- | | Type | Definition | | `streambuf` | `basic_streambuf<char>` | | `wstreambuf` | `basic_streambuf<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function) | | Protected member functions | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function) | ### See also | | | | --- | --- | | [FILE](c/file "cpp/io/c/FILE") | object type, capable of holding all information needed to control a C I/O stream (typedef) | cpp std::basic_filebuf std::basic\_filebuf =================== | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_filebuf : public std::basic_streambuf<CharT, Traits> ``` | | | `std::basic_filebuf` is a `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` whose associated character sequence is a file. Both the input sequence and the output sequence are associated with the same file, and a joint file position is maintained for both operations. The functions underflow() and overflow()/sync() perform the actual I/O between the file and the get and put areas of the buffer. When `CharT` is not `char`, most implementations store multibyte characters in the file and a `[std::codecvt](../locale/codecvt "cpp/locale/codecvt")` facet is used to perform wide/multibyte character conversion. Two specializations for common character types are also defined: | Defined in header `[<streambuf>](../header/streambuf "cpp/header/streambuf")` | | --- | | Type | Definition | | `filebuf` | `basic_filebuf<char>` | | `wfilebuf` | `basic_filebuf<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` which is required to be `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<Traits::state\_type>` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | Public member functions | | [(constructor)](basic_filebuf/basic_filebuf "cpp/io/basic filebuf/basic filebuf") | constructs a basic\_filebuf object (public member function) | | [operator=](basic_filebuf/operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function) | | [swap](basic_filebuf/swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function) | | [(destructor)](basic_filebuf/~basic_filebuf "cpp/io/basic filebuf/~basic filebuf") [virtual] | destructs a basic\_filebuf object and closes the file if it is open (virtual public member function) | | [is\_open](basic_filebuf/is_open "cpp/io/basic filebuf/is open") | checks if the associated file is open (public member function) | | [open](basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function) | | [close](basic_filebuf/close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function) | | Protected member functions | | [showmanyc](basic_filebuf/showmanyc "cpp/io/basic filebuf/showmanyc") [virtual] | optionally provides the number of characters available for input from the file (virtual protected member function) | | [underflow](basic_filebuf/underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function) | | [uflow](basic_filebuf/uflow "cpp/io/basic filebuf/uflow") [virtual] | reads from the associated file and advances the next pointer in the get area (virtual protected member function) | | [pbackfail](basic_filebuf/pbackfail "cpp/io/basic filebuf/pbackfail") [virtual] | backs out the input sequence to unget a character, not affecting the associated file (virtual protected member function) | | [overflow](basic_filebuf/overflow "cpp/io/basic filebuf/overflow") [virtual] | writes characters to the associated file from the put area (virtual protected member function) | | [setbuf](basic_filebuf/setbuf "cpp/io/basic filebuf/setbuf") [virtual] | provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function) | | [seekoff](basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function) | | [seekpos](basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function) | | [sync](basic_filebuf/sync "cpp/io/basic filebuf/sync") [virtual] | writes characters to the associated file from the put area (virtual protected member function) | | [imbue](basic_filebuf/imbue "cpp/io/basic filebuf/imbue") [virtual] | changes the associated locale (virtual protected member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_filebuf)](basic_filebuf/swap2 "cpp/io/basic filebuf/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf") ---------------------------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function of `std::basic_streambuf<CharT,Traits>`) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | ### Protected member functions | | | | --- | --- | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | ### See also | | | | --- | --- | | [FILE](c/file "cpp/io/c/FILE") | object type, capable of holding all information needed to control a C I/O stream (typedef) |
programming_docs
cpp std::basic_spanstream std::basic\_spanstream ====================== | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_spanstream; ``` | | (since C++23) | The class template `std::basic_spanstream` implements input and output operations on streams based on fixed buffers. At the low level, the class essentially wraps a raw device implementation of `std::basic_spanbuf` into a higher-level interface of `[std::basic\_iostream](basic_iostream "cpp/io/basic iostream")`. The complete interface to unique `std::basic_spanbuf` members is provided. Typical implementations of `std::basic_spantream` only add one member subobject: the wrapped `std::basic_spanbuf`. ![std-basic spanstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | --- | | Type | Definition | | `spanstream` | `basic_spanstream<char>` | | `wspanstream` | `basic_spanstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_spanstream/basic_spanstream "cpp/io/basic spanstream/basic spanstream") (C++23) | constructs the `basic_spanstream` (public member function) | | **(destructor)** [virtual] (C++23) | destroys the `basic_spanstream` (virtual public member function) | | [operator=](basic_spanstream/operator= "cpp/io/basic spanstream/operator=") (C++23) | move-assignments the `basic_spanstream` (public member function) | | [swap](basic_spanstream/swap "cpp/io/basic spanstream/swap") (C++23) | swaps two `basic_spanstream` objects (public member function) | | [rdbuf](basic_spanstream/rdbuf "cpp/io/basic spanstream/rdbuf") (C++23) | obtains the address of the wrapped raw `span` device object (public member function) | | Underlying buffer operations | | [span](basic_spanstream/span "cpp/io/basic spanstream/span") (C++23) | gets or sets the underlying buffer of the wrapped `span` device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_spanstream)](basic_spanstream/swap2 "cpp/io/basic spanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_spanstream`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | cpp std::basic_ospanstream std::basic\_ospanstream ======================= | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ospanstream; ``` | | (since C++23) | The class template `std::basic_ospanstream` implements output operations on streams based on fix buffers. At the low level, the class essentially wraps a raw device implementation of `std::basic_spanbuf` into a higher-level interface of `[std::basic\_ostream](basic_ostream "cpp/io/basic ostream")`. The complete interface to unique `std::basic_spanbuf` members is provided. Typical implementations of `std::basic_ospantream` only add one member subobject: the wrapped `std::basic_spanbuf`. ![std-basic ospanstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | --- | | Type | Definition | | `ospanstream` | `basic_ospanstream<char>` | | `wospanstream` | `basic_ospanstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ospanstream/basic_ospanstream "cpp/io/basic ospanstream/basic ospanstream") (C++23) | constructs the `basic_ospanstream` (public member function) | | **(destructor)** [virtual] (C++23) | destroys the `basic_ospanstream` (virtual public member function) | | [operator=](basic_ospanstream/operator= "cpp/io/basic ospanstream/operator=") (C++23) | move-assignments the `basic_ospanstream` (public member function) | | [swap](basic_ospanstream/swap "cpp/io/basic ospanstream/swap") (C++23) | swaps two `basic_ospanstream` objects (public member function) | | [rdbuf](basic_ospanstream/rdbuf "cpp/io/basic ospanstream/rdbuf") (C++23) | obtains the address of the wrapped raw `span` device object (public member function) | | Underlying buffer operations | | [span](basic_ospanstream/span "cpp/io/basic ospanstream/span") (C++23) | gets or sets the underlying buffer of the wrapped `span` device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_ospanstream)](basic_ospanstream/swap2 "cpp/io/basic ospanstream/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::fpos std::fpos ========= | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` template< class State > class fpos; ``` | | | Specializations of the class template `std::fpos` identify absolute positions in a stream or in a file. Each object of type `fpos` holds the byte position in the stream (typically as a private member of type `[std::streamoff](streamoff "cpp/io/streamoff")`) and the current shift state, a value of type `State` (typically `[std::mbstate\_t](../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t")`). The following typedef names for `std::fpos<[std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` are provided (although they are spelled differently in the standard, they denote the same type): | Defined in header `[<iosfwd>](../header/iosfwd "cpp/header/iosfwd")` | | --- | | Type | Definition | | `streampos` | `std::fpos<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char>::state\_type>` | | `wstreampos` | `std::fpos<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<wchar\_t>::state\_type>` | | `u8streampos` (C++20) | `std::fpos<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char8_t>::state\_type>` | | `u16streampos` (C++11) | `std::fpos<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char16\_t>::state\_type>` | | `u32streampos` (C++11) | `std::fpos<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char32\_t>::state\_type>` | All specializations of `fpos` meet the [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), [Destructible](../named_req/destructible "cpp/named req/Destructible"), and [EqualityComparable](../named_req/equalitycomparable "cpp/named req/EqualityComparable") requirements. If `State` is trivially copy constructible, `fpos` has a trivial copy constructor. If `State` is trivially copy assignable, `fpos` has a trivial copy assignment operator. If `State` is trivially destructible, `fpos` has a trivial destructor. ### Template parameter | | | | | --- | --- | --- | | State | - | the type representing the shift state | | Type requirements | | -`State` must meet the requirements of [Destructible](../named_req/destructible "cpp/named req/Destructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | ### Member functions | | | | --- | --- | | [state](fpos/state "cpp/io/fpos/state") | gets/sets the value of the shift state (public member function) | In addition, member and non-member functions are provided to support the following operations: * A default constructor that stores an offset of zero and value-initializes the state object. * A non-explicit constructor that accepts an argument of type (possibly const) `[std::streamoff](streamoff "cpp/io/streamoff")`, which stores that offset and and value-initializes the state object. This constructor must also accept the special value `[std::streamoff](http://en.cppreference.com/w/cpp/io/streamoff)(-1)`: the `std::fpos` constructed in this manner is returned by some stream operations to indicate errors. * Explicit conversion from (possibly const) `fpos` to `[std::streamoff](streamoff "cpp/io/streamoff")`. The result is the stored offset. * `operator==` and `operator!=` that compare two objects of type (possibly const) `std::fpos` and returns a value of type convertible to `bool`. `p != q` is equivalent to `!(p == q)`. * `operator+` and `operator-` such that, for an object `p` of type (possibly const) `fpos<State>` and an object `o` of type (possibly const) `[std::streamoff](streamoff "cpp/io/streamoff")` + `p + o` has type `fpos<State>` and stores an offset that is the result of adding `o` to the offset of `p` + `o + p` has a type convertible to `fpos<State>` and the result of the conversion is equal to `p + o` + `p - o` has type `fpos<State>` and stores an offset that is the result of subtracting `o` from the offset of `p` * `operator+=` and `operator-=` which can accept a (possibly const) `[std::streamoff](streamoff "cpp/io/streamoff")` and adds/subtracts it from the stored offset, respectively. * `operator-` which can subtract two objects of type (possibly const) `std::fpos` producing an `[std::streamoff](streamoff "cpp/io/streamoff")`, such that for two such objects `p` and `q`, `p == q + (p - q)` ### Notes Some of the [I/O streams member functions](../io "cpp/io") return and manipulate objects of member typedef `pos_type`. For streams, these member typedefs are provided by the template parameter `Traits`, which defaults to `[std::char\_traits](../string/char_traits "cpp/string/char traits")`, which define their `pos_type`s to be specializations of `std::fpos`. The behavior of the I/O streams library is implementation-defined when `Traits::pos_type` is not `std::fpos<[std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` (aka `std::streampos`, `std::wstreampos`, etc.). ### 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 57](https://cplusplus.github.io/LWG/issue57) | C++98 | `streampos` and `wstreampos` were contradictionally allowed to be differentwhiled required to be same | clarified to be same | | [P0759R1](https://wg21.link/P0759R1) | C++98 | specification was unclear and incomplete | cleaned up | | [P1148R0](https://wg21.link/P1148R0) | C++11 | unclear what and in which header the definition `u16streampos` and `u32streampos` are | made clear | ### See also | | | | --- | --- | | [streamoff](streamoff "cpp/io/streamoff") | represents relative file/stream position (offset from fpos), sufficient to represent any file size (typedef) | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [fgetpos](c/fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | cpp std::basic_osyncstream std::basic\_osyncstream ======================= | Defined in header `[<syncstream>](../header/syncstream "cpp/header/syncstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_osyncstream: public std::basic_ostream<CharT, Traits> ``` | | (since C++20) | The class template `std::basic_osyncstream` is a convenience wrapper for [`std::basic_syncbuf`](basic_syncbuf "cpp/io/basic syncbuf"). It provides a mechanism to synchronize threads writing to the same stream. It can be used with a named variable: ``` { std::osyncstream synced_out(std::cout); // synchronized wrapper for std::cout synced_out << "Hello, "; synced_out << "World!"; synced_out << std::endl; // flush is noted, but not yet performed synced_out << "and more!\n"; } // characters are transferred and std::cout is flushed ``` as well as with a temporary: ``` std::osyncstream(std::cout) << "Hello, " << "World!" << '\n'; ``` It provides the guarantee that all output made to the same final destination buffer (std::cout in the examples above) will be free of data races and will not be interleaved or garbled in any way, as long as every write to the that final destination buffer is made through (possibly different) instances of `std::basic_osyncstream`. Typical implementation of `std::basic_osyncstream` holds only one member: the wrapped `std::basic_syncbuf`. ![std-basic osyncstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<syncstream>](../header/syncstream "cpp/header/syncstream")` | | --- | | Type | Definition | | `osyncstream` | `basic_osyncstream<char>` | | `wosyncstream` | `basic_osyncstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | | `streambuf_type` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<CharT, Traits>` | | `syncbuf_type` | `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)<CharT, Traits, Allocator>` | ### Member functions | | | | --- | --- | | [(constructor)](basic_osyncstream/basic_osyncstream "cpp/io/basic osyncstream/basic osyncstream") | constructs a basic\_osyncstream (public member function) | | [operator=](basic_osyncstream/operator= "cpp/io/basic osyncstream/operator=") | assigns a basic\_osyncstream (public member function) | | [(destructor)](basic_osyncstream/~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function) | | [rdbuf](basic_osyncstream/rdbuf "cpp/io/basic osyncstream/rdbuf") | obtains a pointer to the underlying basic\_syncbuf (public member function) | | [get\_wrapped](basic_osyncstream/get_wrapped "cpp/io/basic osyncstream/get wrapped") | obtains a pointer to the final destination stream buffer (public member function) | | [emit](basic_osyncstream/emit "cpp/io/basic osyncstream/emit") | calls emit on the underlying basic\_syncbuf to transmit its internal data to the final destination (public member function) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::basic_istream std::basic\_istream =================== | Defined in header `[<istream>](../header/istream "cpp/header/istream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_istream : virtual public std::basic_ios<CharT, Traits> ``` | | | The class template `basic_istream` provides support for high level input operations on character streams. The supported operations include formatted input (e.g. integer values or whitespace-separated characters and characters strings) and unformatted input (e.g. raw characters and character arrays). This functionality is implemented in terms of the interface provided by the underlying `basic_streambuf` class, accessed through the `basic_ios` base class. The only non-inherited data member of `basic_istream`, in most implementations, is the value returned by [`basic_istream::gcount()`](basic_istream/gcount "cpp/io/basic istream/gcount"). ![std-basic istream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are defined: | Defined in header `[<istream>](../header/istream "cpp/header/istream")` | | --- | | Type | Definition | | `istream` | `basic_istream<char>` | | `wistream` | `basic_istream<wchar_t>` | ### Global objects Two global basic\_istream objects are provided by the standard library. | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | --- | | [cinwcin](cin "cpp/io/cin") | reads from the standard C input stream `[stdin](c/std_streams "cpp/io/c/std streams")` (global object) | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_istream/basic_istream "cpp/io/basic istream/basic istream") | constructs the object (public member function) | | [(destructor)](basic_istream/~basic_istream "cpp/io/basic istream/~basic istream") [virtual] | destructs the object (virtual public member function) | | [operator=](basic_istream/operator= "cpp/io/basic istream/operator=") (C++11) | move-assigns from another `basic_istream` (protected member function) | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function) | | [swap](basic_istream/swap "cpp/io/basic istream/swap") (C++11) | swaps stream objects, except for the associated buffer (protected member function) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class) | ### Non-member functions | | | | --- | --- | | [operator>>(std::basic\_istream)](basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | cpp std::istrstream std::istrstream =============== | Defined in header `[<strstream>](../header/strstream "cpp/header/strstream")` | | | | --- | --- | --- | | ``` class istrstream : public std::istream ``` | | (deprecated in C++98) | The class `istrstream` implements input operations on array-backed streams. It essentially wraps a raw array I/O device implementation (`[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`) into the higher-level interface of `[std::basic\_istream](basic_istream "cpp/io/basic istream")`. The typical implementation of `istrstream` holds only one non-derived data member: an object of type `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`. ### Notes `istrstream` has been deprecated since C++98. `[std::istringstream](basic_istringstream "cpp/io/basic istringstream")` and [boost::iostreams::array\_source](http://www.boost.org/doc/libs/release/libs/iostreams/doc/classes/array.html#array_source) are the recommended replacements. ### Member functions | | | | --- | --- | | [(constructor)](istrstream/istrstream "cpp/io/istrstream/istrstream") | constructs an strstream, optionally allocating the buffer (public member function) | | [(destructor)](istrstream/~istrstream "cpp/io/istrstream/~istrstream") [virtual] | destructs a strstream, optionally deallocating the buffer (virtual public member function) | | [rdbuf](istrstream/rdbuf "cpp/io/istrstream/rdbuf") | obtains a pointer to the associated strstreambuf (public member function) | | [str](istrstream/str "cpp/io/istrstream/str") | accesses the output buffer (public member function) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::cout, std::wcout std::cout, std::wcout ===================== | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | | | --- | --- | --- | | ``` extern std::ostream cout; ``` | (1) | | | ``` extern std::wostream wcout; ``` | (2) | | The global objects `std::cout` and `std::wcout` control output to a stream buffer of implementation-defined type (derived from `[std::streambuf](basic_streambuf "cpp/io/basic streambuf")`), associated with the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`. These objects are guaranteed to be initialized during or before the first time an object of type `[std::ios\_base::Init](ios_base/init "cpp/io/ios base/Init")` is constructed and are available for use in the constructors and destructors of static objects with [ordered initialization](../language/initialization#Non-local_variables "cpp/language/initialization") (as long as [`<iostream>`](../header/iostream "cpp/header/iostream") is included before the object is defined). Unless `std::ios_base::sync_with_stdio(false)` has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output. By specification of `[std::cin](cin "cpp/io/cin")`, `[std::cin](http://en.cppreference.com/w/cpp/io/cin).tie()` returns `&std::cout`. This means that any input operation on `std::cin` executes `std::cout.flush()` (via `[std::basic\_istream::sentry](basic_istream/sentry "cpp/io/basic istream/sentry")`'s constructor). Similarly, `[std::wcin](http://en.cppreference.com/w/cpp/io/cin).tie()` returns `&std::wcout`. By specification of `[std::cerr](cerr "cpp/io/cerr")`, `[std::cerr](http://en.cppreference.com/w/cpp/io/cerr).tie()` returns `&std::cout`. This means that any output operation on `std::cerr` executes `std::cout.flush()` (via `[std::basic\_ostream::sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry")`'s constructor). Similarly, `[std::wcerr](http://en.cppreference.com/w/cpp/io/cerr).tie()` returns `&std::wcout`. (since C++11). ### Notes The 'c' in the name refers to "character" ([stroustrup.com FAQ](http://www.stroustrup.com/bs_faq2.html#cout)); `cout` means "character output" and `wcout` means "wide character output". Because [dynamic initialization](../language/initialization#Dynamic_initialization "cpp/language/initialization") of [templated](../language/templates#Templated_entity "cpp/language/templates") variables are unordered, it is not guaranteed that `std::cout` has been initialized to a usable state before the initialization of such variables begins, unless an object of type `[std::ios\_base::Init](ios_base/init "cpp/io/ios base/Init")` has been constructed. ### Example ``` #include <iostream> struct Foo { int n; Foo() { std::cout << "static constructor\n"; } ~Foo() { std::cout << "static destructor\n"; } }; Foo f; // static object int main() { std::cout << "main function\n"; } ``` Output: ``` static constructor main function static destructor ``` ### See also | | | | --- | --- | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | [cerrwcerr](cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [clogwclog](clog "cpp/io/clog") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`(global object) | | [stdinstdoutstderr](c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | cpp std::basic_ios std::basic\_ios =============== | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ios : public std::ios_base ``` | | | The class `std::basic_ios` provides facilities for interfacing with objects that have `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` interface. Several `std::basic_ios` objects can refer to one actual `std::basic_streambuf` object. ![std-basic ios-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also provided: | Type | Definition | | --- | --- | | `ios` | `basic_ios<char>` | | `wios` | `basic_ios<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Public member functions | | | | --- | --- | | [(constructor)](basic_ios/basic_ios "cpp/io/basic ios/basic ios") | constructs the object (public member function) | | [(destructor)](basic_ios/~basic_ios "cpp/io/basic ios/~basic ios") [virtual] | destructs the object (virtual public member function) | | operator= | the copy assignment operator is deleted (public member function) | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function) | ### Protected member functions | | | | --- | --- | | [init](basic_ios/init "cpp/io/basic ios/init") | initializes a default-constructed `std::basic_ios` (protected member function) | | [move](basic_ios/move "cpp/io/basic ios/move") (C++11) | moves from another `std::basic_ios` except for `rdbuf` (protected member function) | | [swap](basic_ios/swap "cpp/io/basic ios/swap") (C++11) | swaps with another `std::basic_ios` except for `rdbuf` (protected member function) | | [set\_rdbuf](basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf") | replaces the `rdbuf` without clearing its error state (protected member function) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### Notes Straightforward implementation of `std::basic_ios` stores only the following members (which all depend on the template parameters and thus cannot be part of `[std::ios\_base](ios_base "cpp/io/ios base")`): * the fill character (see [`fill()`](basic_ios/fill "cpp/io/basic ios/fill")) * the tied stream pointer (see [`tie()`](basic_ios/tie "cpp/io/basic ios/tie")) * the associated stream buffer pointer (see [`rdbuf()`](basic_ios/rdbuf "cpp/io/basic ios/rdbuf")) Actual implementations vary: Microsoft Visual Studio stores just those three members. LLVM libc++ stores 1 less member: it maintains the rdbuf pointer as a void\* member of ios\_base. GNU libstdc++ stores 4 additional members: three cached facets and a flag to indicate that fill was initialized. cpp std::basic_ofstream std::basic\_ofstream ==================== | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ofstream : public std::basic_ostream<CharT, Traits> ``` | | | The class template `basic_ofstream` implements high-level output operations on file based streams. It interfaces a file-based streambuffer (`[std::basic\_filebuf](basic_filebuf "cpp/io/basic filebuf")`) with the high-level interface of (`[std::basic\_ostream](basic_ostream "cpp/io/basic ostream")`). A typical implementation of `std::basic_ofstream` holds only one non-derived data member: an instance of `[std::basic\_filebuf](http://en.cppreference.com/w/cpp/io/basic_filebuf)<CharT, Traits>`. ![std-basic ofstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | --- | | Type | Definition | | `ofstream` | `basic_ofstream<char>` | | `wofstream` | `basic_ofstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ofstream/basic_ofstream "cpp/io/basic ofstream/basic ofstream") | constructs the file stream (public member function) | | (destructor) [virtual] (implicitly declared) | destructs the basic\_ofstream and the associated buffer, closes the file (virtual public member function) | | [operator=](basic_ofstream/operator= "cpp/io/basic ofstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](basic_ofstream/swap "cpp/io/basic ofstream/swap") (C++11) | swaps two file streams (public member function) | | [rdbuf](basic_ofstream/rdbuf "cpp/io/basic ofstream/rdbuf") | returns the underlying raw file device object (public member function) | | File operations | | [is\_open](basic_ofstream/is_open "cpp/io/basic ofstream/is open") | checks if the stream has an associated file (public member function) | | [open](basic_ofstream/open "cpp/io/basic ofstream/open") | opens a file and associates it with the stream (public member function) | | [close](basic_ofstream/close "cpp/io/basic ofstream/close") | closes the associated file (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_ofstream)](basic_ofstream/swap2 "cpp/io/basic ofstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### Example ``` #include <iostream> #include <fstream> #include <string> int main() { std::string filename = "Test.b"; { std::ofstream ostrm(filename, std::ios::binary); double d = 3.14; ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output ostrm << 123 << "abc" << '\n'; // text output } // read back std::ifstream istrm(filename, std::ios::binary); double d; istrm.read(reinterpret_cast<char*>(&d), sizeof d); int n; std::string s; istrm >> n >> s; std::cout << " read back: " << d << " " << n << " " << s << '\n'; } ``` Output: ``` read back: 3.14 123 abc ```
programming_docs
cpp std::cin, std::wcin std::cin, std::wcin =================== | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | | | --- | --- | --- | | ``` extern std::istream cin; ``` | (1) | | | ``` extern std::wistream wcin; ``` | (2) | | The global objects `std::cin` and `std::wcin` control input from a stream buffer of implementation-defined type (derived from `[std::streambuf](basic_streambuf "cpp/io/basic streambuf")`), associated with the standard C input stream `[stdin](c/std_streams "cpp/io/c/std streams")`. These objects are guaranteed to be initialized during or before the first time an object of type `[std::ios\_base::Init](ios_base/init "cpp/io/ios base/Init")` is constructed and are available for use in the constructors and destructors of static objects with [ordered initialization](../language/initialization#Non-local_variables "cpp/language/initialization") (as long as `<iostream>` is included before the object is defined). Unless `sync_with_stdio(false)` has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted input. Once `std::cin` is constructed, `std::cin.tie()` returns `&[std::cout](http://en.cppreference.com/w/cpp/io/cout)`, and likewise, `std::wcin.tie()` returns `&[std::wcout](http://en.cppreference.com/w/cpp/io/cout)`. This means that any formatted input operation on `std::cin` forces a call to `[std::cout](http://en.cppreference.com/w/cpp/io/cout).flush()` if any characters are pending for output. ### Notes The 'c' in the name refers to "character" ([stroustrup.com FAQ](http://www.stroustrup.com/bs_faq2.html#cout)); `cin` means "character input" and `wcin` means "wide character input" ### Example ``` #include <iostream> struct Foo { int n; Foo() { std::cout << "Enter n: "; // no flush needed std::cin >> n; } }; Foo f; // static object int main() { std::cout << "f.n is " << f.n << '\n'; } ``` Possible output: ``` Enter n: 10 f.n is 10 ``` ### See also | | | | --- | --- | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | [coutwcout](cout "cpp/io/cout") | writes to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`(global object) | | [stdinstdoutstderr](c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | cpp std::basic_stringbuf std::basic\_stringbuf ===================== | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_stringbuf : public std::basic_streambuf<CharT, Traits> ``` | | | `std::basic_stringbuf` is a `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` whose associated character sequence is a memory-resident sequence of arbitrary characters, which can be initialized from or made available as an instance of `[std::basic\_string](../string/basic_string "cpp/string/basic string")`. Typical implementations of `std::basic_stringbuf` hold an object of type `[std::basic\_string](../string/basic_string "cpp/string/basic string")` or equivalent resizeable sequence container directly as a data member and use it as both the controlled character sequence (the array where the six pointers of `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` are pointing to) and as the associated character sequence (the source of characters for all input operations and the target for the output). In addition, a typical implementation holds a data member of type `[std::ios\_base::openmode](ios_base/openmode "cpp/io/ios base/openmode")` to indicate the status of the stream (input-only, output-only, input/output, at-end, etc). | | | | --- | --- | | if over-allocation strategy is used by `[overflow()](basic_stringbuf/overflow "cpp/io/basic stringbuf/overflow")`, an additional high-watermark pointer may be stored to track the last initialized character. | (since C++11) | Two specializations for common character types are also defined: | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | --- | | Type | Definition | | `stringbuf` | `basic_stringbuf<char>` | | `wstringbuf` | `basic_stringbuf<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | ### Member functions | | | --- | | Public member functions | | [(constructor)](basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function) | | [operator=](basic_stringbuf/operator= "cpp/io/basic stringbuf/operator=") (C++11) | assigns a basic\_stringbuf object (public member function) | | [swap](basic_stringbuf/swap "cpp/io/basic stringbuf/swap") (C++11) | swaps two basic\_stringbuf objects (public member function) | | (destructor) [virtual] (implicitly declared) | destructs a basic\_stringbuf object and the string it holds (virtual public member function) | | [str](basic_stringbuf/str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function) | | [get\_allocator](basic_stringbuf/get_allocator "cpp/io/basic stringbuf/get allocator") (C++20) | obtains a copy of the allocator associated with the internal sequence container (public member function) | | [view](basic_stringbuf/view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function) | | Protected member functions | | [underflow](basic_stringbuf/underflow "cpp/io/basic stringbuf/underflow") [virtual] | returns the next character available in the input sequence (virtual protected member function) | | [pbackfail](basic_stringbuf/pbackfail "cpp/io/basic stringbuf/pbackfail") [virtual] | puts a character back into the input sequence (virtual protected member function) | | [overflow](basic_stringbuf/overflow "cpp/io/basic stringbuf/overflow") [virtual] | appends a character to the output sequence (virtual protected member function) | | [setbuf](basic_stringbuf/setbuf "cpp/io/basic stringbuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function) | | [seekoff](basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_stringbuf)](basic_stringbuf/swap2 "cpp/io/basic stringbuf/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf") ---------------------------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function of `std::basic_streambuf<CharT,Traits>`) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | ### Protected member functions | | | | --- | --- | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::streamoff std::streamoff ============== | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` typedef /*implementation-defined*/ streamoff; ``` | | | The type `std::streamoff` is an implementation-defined signed integral (since C++11) type of sufficient size to represent the maximum possible file size supported by the operating system. Typically, this is an alias for `long long`. (since C++11). It is used to represent offsets from stream positions (values of type `[std::fpos](fpos "cpp/io/fpos")`). A `std::streamoff` value constructed from `-1` is also used to represent error conditions by some of the I/O library functions. ### Relationship with std::fpos * the difference between two `[std::fpos](fpos "cpp/io/fpos")` objects is a value of type `std::streamoff` * a value of type `std::streamoff` may be added or subtracted from `[std::fpos](fpos "cpp/io/fpos")` yielding a different `[std::fpos](fpos "cpp/io/fpos")`. * a value of type `[std::fpos](fpos "cpp/io/fpos")` is implicitly convertible to `std::streamoff` (the conversion result is the offset from the beginning of the file). * a value of type `[std::fpos](fpos "cpp/io/fpos")` is constructible from a value of type `std::streamoff` ### See also | | | | --- | --- | | [fpos](fpos "cpp/io/fpos") | represents absolute position in a stream or a file (class template) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::println std::println ============ | Defined in header `[<print>](../header/print "cpp/header/print")` | | | | --- | --- | --- | | ``` template< class... Args > void println( std::FILE* stream, std::format_string<Args...> fmt, Args&&... args ); ``` | (1) | (since C++23) | | ``` template< class... Args > void println( std::format_string<Args...> fmt, Args&&... args ); ``` | (2) | (since C++23) | Format `args` according to the format string `fmt` with appended `'\n'` (which means each output ends with new-line), and print the result to a stream. 1) Equivalent to: ``` std::print(stream, "{}\n", std::format(fmt, std::forward<Args>(args)...)); ``` 2) same as (1) when `stream` is equal to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`, i.e. ``` std::println(stdout, fmt, std::forward<Args>(args)...); ``` The behavior is undefined if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, char>` does not model `std::formattable` for any `Ti` in `Args` (as required by `[std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)`). ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](../utility/format/formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | ### Return value (none). ### Exceptions * `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. * `[std::system\_error](../error/system_error "cpp/error/system error")`, if writing to the stream fails. * Propagate exception thrown by any [formatter](../utility/format/formatter "cpp/utility/format/formatter"), e.g. `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")`. ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_print`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ``` #include <print> int main() { // Each call to std::println ends with new-line std::println("Please"); std::println("enter"); std::print("pass"); std::print("word"); std::println(""); // same effect as std::print("\n"); } ``` Output: ``` Please enter password ``` ### See also | | | | --- | --- | | [print](print "cpp/io/print") (C++23) | prints to `[stdout](c/std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [println](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/println&action=edit&redlink=1 "cpp/io/basic ostream/println (page does not exist)") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments with appended `'\n'` (function template) | | [format](../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [printffprintfsprintfsnprintf](c/fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) |
programming_docs
cpp std::strstreambuf std::strstreambuf ================= | Defined in header `[<strstream>](../header/strstream "cpp/header/strstream")` | | | | --- | --- | --- | | ``` class strstreambuf : public std::basic_streambuf<char> ``` | | (deprecated in C++98) | `std::strstreambuf` is a `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` whose associated character sequence is a character array, which may be constant (e.g. a string literal), modifyable but not dynamic (e.g. a stack-allocated array), or dynamic, in which case the `std::strstreambuf` may be allowed to reallocate the array as necessary to accomodate output (e.g. by calling `delete[]` and `new[]` or user-provided functions). Typical implementation of a `std::strstreambuf` holds four private data members: 1) buffer state, a bitmask type which can represent any combination of the four values "allocated" (destructor will deallocate), "constant" (output not allowed), "dynamic" (output may reallocate), or "frozen" (deallocation and reallocation are not allowed) 2) allocated buffer size (the beginning of the buffer does not need a special data member, it may be stored in the inherited pointer `[eback()](basic_streambuf/gptr "cpp/io/basic streambuf/gptr")`) 3) pointer to user-provided allocation function 4) pointer to user-provided deallocation function. ### Notes After any call to `str()` on a stream with a dynamic buffer, a call to `freeze(false)` is required to allow the `strstreambuf` destructor to deallocate the buffer when necessary. ### Member functions | | | --- | | Public member functions | | [(constructor)](strstreambuf/strstreambuf "cpp/io/strstreambuf/strstreambuf") | constructs a strstreambuf object (public member function) | | [(destructor)](strstreambuf/~strstreambuf "cpp/io/strstreambuf/~strstreambuf") [virtual] | destructs a strstreambuf object, optionally deallocating the character array (virtual public member function) | | [freeze](strstreambuf/freeze "cpp/io/strstreambuf/freeze") | sets/clears the frozen state of the buffer (public member function) | | [str](strstreambuf/str "cpp/io/strstreambuf/str") | marks the buffer frozen and returns the beginning pointer of the input sequence (public member function) | | [pcount](strstreambuf/pcount "cpp/io/strstreambuf/pcount") | returns the next pointer minus the beginning pointer in the output sequence: the number of characters written (public member function) | | Protected member functions | | [underflow](strstreambuf/underflow "cpp/io/strstreambuf/underflow") [virtual] | reads a character from the input sequence without advancing the next pointer (virtual protected member function) | | [pbackfail](strstreambuf/pbackfail "cpp/io/strstreambuf/pbackfail") [virtual] | backs out the input sequence to unget a character (virtual protected member function) | | [overflow](strstreambuf/overflow "cpp/io/strstreambuf/overflow") [virtual] | appends a character to the output sequence, may reallocate or initially allocate the buffer if dynamic and not frozen (virtual protected member function) | | [setbuf](strstreambuf/setbuf "cpp/io/strstreambuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function) | | [seekoff](strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](strstreambuf/seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | Inherited from [std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf") ---------------------------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function of `std::basic_streambuf<CharT,Traits>`) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | ### Protected member functions | | | | --- | --- | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::basic_fstream std::basic\_fstream =================== | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_fstream : public std::basic_iostream<CharT, Traits> ``` | | | The class template `basic_fstream` implements high-level input/output operations on file based streams. It interfaces a file-based streambuffer (`[std::basic\_filebuf](basic_filebuf "cpp/io/basic filebuf")`) with the high-level interface of (`[std::basic\_iostream](basic_iostream "cpp/io/basic iostream")`). A typical implementation of `std::basic_fstream` holds only one non-derived data member: an instance of `[std::basic\_filebuf](http://en.cppreference.com/w/cpp/io/basic_filebuf)<CharT, Traits>`. ![std-basic fstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | --- | | Type | Definition | | `fstream` | `basic_fstream<char>` | | `wfstream` | `basic_fstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_fstream/basic_fstream "cpp/io/basic fstream/basic fstream") | constructs the file stream (public member function) | | (destructor) [virtual] (implicitly declared) | destructs the basic\_fstream and the associated buffer, closes the file (virtual public member function) | | [operator=](basic_fstream/operator= "cpp/io/basic fstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](basic_fstream/swap "cpp/io/basic fstream/swap") (C++11) | swaps two file streams (public member function) | | [rdbuf](basic_fstream/rdbuf "cpp/io/basic fstream/rdbuf") | returns the underlying raw file device object (public member function) | | File operations | | [is\_open](basic_fstream/is_open "cpp/io/basic fstream/is open") | checks if the stream has an associated file (public member function) | | [open](basic_fstream/open "cpp/io/basic fstream/open") | opens a file and associates it with the stream (public member function) | | [close](basic_fstream/close "cpp/io/basic fstream/close") | closes the associated file (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_fstream)](basic_fstream/swap2 "cpp/io/basic fstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ostream](basic_ostream "cpp/io/basic ostream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted output | | [operator<<](basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | Unformatted output | | [put](basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) | | [write](basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | Positioning | | [tellp](basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | Miscellaneous | | [flush](basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry") | implements basic logic for preparation of the stream for output operations (public member class of `std::basic_ostream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### See also | | | | --- | --- | | [getline](../string/basic_string/getline "cpp/string/basic string/getline") | read data from an I/O stream into a string (function template) | ### Example ``` #include <iostream> #include <fstream> #include <string> int main() { std::string filename = "test.bin"; std::fstream s(filename, s.binary | s.trunc | s.in | s.out); if (!s.is_open()) { std::cout << "failed to open " << filename << '\n'; } else { // write double d = 3.14; s.write(reinterpret_cast<char*>(&d), sizeof d); // binary output s << 123 << "abc"; // text output // for fstream, this moves the file position pointer (both put and get) s.seekp(0); // read s.read(reinterpret_cast<char*>(&d), sizeof d); // binary input int n; std::string str; if (s >> n >> str) // text input std::cout << "read back from file: " << d << ' ' << n << ' ' << str << '\n'; } } ``` Output: ``` read back from file: 3.14 123 abc ```
programming_docs
cpp std::basic_ifstream std::basic\_ifstream ==================== | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_ifstream : public std::basic_istream<CharT, Traits> ``` | | | The class template `basic_ifstream` implements high-level input operations on file-based streams. It interfaces a file-based streambuffer (`[std::basic\_filebuf](basic_filebuf "cpp/io/basic filebuf")`) with the high-level interface of (`[std::basic\_istream](basic_istream "cpp/io/basic istream")`). A typical implementation of `std::basic_ifstream` holds only one non-derived data member: an instance of `[std::basic\_filebuf](http://en.cppreference.com/w/cpp/io/basic_filebuf)<CharT, Traits>`. ![std-basic ifstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<fstream>](../header/fstream "cpp/header/fstream")` | | --- | | Type | Definition | | `ifstream` | `basic_ifstream<char>` | | `wifstream` | `basic_ifstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(constructor)](basic_ifstream/basic_ifstream "cpp/io/basic ifstream/basic ifstream") | constructs the file stream (public member function) | | (destructor) [virtual] (implicitly declared) | destructs the basic\_ifstream and the associated buffer, closes the file (virtual public member function) | | [operator=](basic_ifstream/operator= "cpp/io/basic ifstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](basic_ifstream/swap "cpp/io/basic ifstream/swap") (C++11) | swaps two file streams (public member function) | | [rdbuf](basic_ifstream/rdbuf "cpp/io/basic ifstream/rdbuf") | returns the underlying raw file device object (public member function) | | File operations | | [is\_open](basic_ifstream/is_open "cpp/io/basic ifstream/is open") | checks if the stream has an associated file (public member function) | | [open](basic_ifstream/open "cpp/io/basic ifstream/open") | opens a file and associates it with the stream (public member function) | | [close](basic_ifstream/close "cpp/io/basic ifstream/close") | closes the associated file (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_ifstream)](basic_ifstream/swap2 "cpp/io/basic ifstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) | ### Example ``` #include <iostream> #include <fstream> #include <string> int main() { std::string filename = "Test.b"; // prepare a file to read double d = 3.14; std::ofstream(filename, std::ios::binary).write(reinterpret_cast<char*>(&d), sizeof d) << 123 << "abc"; // open file for reading std::ifstream istrm(filename, std::ios::binary); if (!istrm.is_open()) { std::cout << "failed to open " << filename << '\n'; } else { double d; istrm.read(reinterpret_cast<char*>(&d), sizeof d); // binary input int n; std::string s; if (istrm >> n >> s) // text input std::cout << "read back from file: " << d << ' ' << n << ' ' << s << '\n'; } } ``` Output: ``` read back from file: 3.14 123 abc ``` cpp std::basic_spanbuf std::basic\_spanbuf =================== | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT> > class basic_spanbuf : public std::basic_streambuf<CharT, Traits> ``` | | (since C++23) | `std::basic_spanbuf` is a `[std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf")` whose associated character sequence is a memory-resident sequence of arbitrary characters, which can be initialized from or made available as an instance of `[std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>`. `std::basic_spanbuf` performs I/O on a fixed buffer, and therefore it does not attempt to obtain a new buffer when the underlying buffer is exhausted. Typical implementations of `std::basic_spanbuf` add two member subobjects: a `[std::ios\_base::openmode](ios_base/openmode "cpp/io/ios base/openmode")` recording the open mode, and a `[std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>` referencing the underlying buffer. Two specializations for common character types are also defined: | Defined in header `[<spanstream>](../header/spanstream "cpp/header/spanstream")` | | --- | | Type | Definition | | `spanbuf` | `basic_spanbuf<char>` | | `wspanbuf` | `basic_spanbuf<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | Public member functions | | [(constructor)](basic_spanbuf/basic_spanbuf "cpp/io/basic spanbuf/basic spanbuf") (C++23) | constructs a `basic_spanbuf` object (public member function) | | **(destructor)** [virtual] (C++23) | destroys the `basic_spanbuf` object (virtual public member function) | | [operator=](basic_spanbuf/operator= "cpp/io/basic spanbuf/operator=") (C++23) | assigns a `basic_spanbuf` object (public member function) | | [swap](basic_spanbuf/swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function) | | [span](basic_spanbuf/span "cpp/io/basic spanbuf/span") (C++23) | obtains or initializes an underlying buffer according to mode (public member function) | | Protected member functions | | [setbuf](basic_spanbuf/setbuf "cpp/io/basic spanbuf/setbuf") [virtual] (C++23) | attempts to replace the controlled character sequence with an array (virtual protected member function) | | [seekoff](basic_spanbuf/seekoff "cpp/io/basic spanbuf/seekoff") [virtual] (C++23) | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](basic_spanbuf/seekpos "cpp/io/basic spanbuf/seekpos") [virtual] (C++23) | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_spanbuf)](basic_spanbuf/swap2 "cpp/io/basic spanbuf/swap2") (C++23) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_streambuf](basic_streambuf "cpp/io/basic streambuf") ---------------------------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | | --- | --- | | [(destructor)](basic_streambuf/~basic_streambuf "cpp/io/basic streambuf/~basic streambuf") [virtual] | destructs the basic\_streambuf object (virtual public member function of `std::basic_streambuf<CharT,Traits>`) | | Locales | | [pubimbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [getloc](basic_streambuf/getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [pubsetbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubseekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [pubsync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [in\_avail](basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [snextc](basic_streambuf/snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sbumpcstossc](basic_streambuf/sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetc](basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Put area | | [sputc](basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | Putback | | [sputbackc](basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | ### Protected member functions | | | | --- | --- | | [(constructor)](basic_streambuf/basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | | [operator=](basic_streambuf/operator= "cpp/io/basic streambuf/operator=") (C++11) | replaces a basic\_streambuf object (protected member function) | | [swap](basic_streambuf/swap "cpp/io/basic streambuf/swap") (C++11) | swaps two basic\_streambuf objects (protected member function) | | Locales | | [imbue](basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Positioning | | [setbuf](basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | Get area | | [showmanyc](basic_streambuf/showmanyc "cpp/io/basic streambuf/showmanyc") [virtual] | obtains the number of characters available for input in the associated input sequence, if known (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [uflow](basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [xsgetn](basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn") [virtual] | reads multiple characters from the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [ebackgptregptr](basic_streambuf/gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | | [gbump](basic_streambuf/gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | | [setg](basic_streambuf/setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | | Put area | | [xsputn](basic_streambuf/sputn "cpp/io/basic streambuf/sputn") [virtual] | writes multiple characters to the output sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [pbasepptrepptr](basic_streambuf/pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | | [pbump](basic_streambuf/pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | | [setp](basic_streambuf/setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | | Putback | | [pbackfail](basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | ### Notes `std::basic_spanbuf` does not own the underlying buffer. It is the responsibility of programmers to ensure the underlying buffer is in its lifetime when used by a `std::basic_spanbuf` object. Additional synchronization may be needed if more than one thread operates the same underlying buffer through different `std::basic_spanbuf` objects. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_spanstream`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | ### See also | | | | --- | --- | | [basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf") | implements raw string device (class template) | | [strstreambuf](strstreambuf "cpp/io/strstreambuf") (deprecated in C++98) | implements raw character array device (class) |
programming_docs
cpp std::cerr, std::wcerr std::cerr, std::wcerr ===================== | Defined in header `[<iostream>](../header/iostream "cpp/header/iostream")` | | | | --- | --- | --- | | ``` extern std::ostream cerr; ``` | (1) | | | ``` extern std::wostream wcerr; ``` | (2) | | The global objects `std::cerr` and `std::wcerr` control output to a stream buffer of implementation-defined type (derived from `[std::streambuf](basic_streambuf "cpp/io/basic streambuf")` and `[std::wstreambuf](basic_streambuf "cpp/io/basic streambuf")`, respectively), associated with the standard C error output stream `[stderr](c/std_streams "cpp/io/c/std streams")`. These objects are guaranteed to be initialized during or before the first time an object of type `[std::ios\_base::Init](ios_base/init "cpp/io/ios base/Init")` is constructed and are available for use in the constructors and destructors of static objects with [ordered initialization](../language/initialization#Non-local_variables "cpp/language/initialization") (as long as [`<iostream>`](../header/iostream "cpp/header/iostream") is included before the object is defined). Unless `std::ios_base::sync_with_stdio(false)` has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output. Once initialized, `(std::cerr.flags() & unitbuf) != 0` (same for `wcerr`) meaning that any output sent to these stream objects is immediately flushed to the OS (via `[std::basic\_ostream::sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry")`'s destructor). In addition, `std::cerr.tie()` returns `&[std::cout](http://en.cppreference.com/w/cpp/io/cout)` (same for `wcerr` and `[std::wcout](cout "cpp/io/cout")`), meaning that any output operation on `std::cerr` first executes `[std::cout](http://en.cppreference.com/w/cpp/io/cout).flush()` (via `[std::basic\_ostream::sentry](basic_ostream/sentry "cpp/io/basic ostream/sentry")`'s constructor) (since C++11). ### Notes The 'c' in the name refers to "character" ([stroustrup.com FAQ](http://www.stroustrup.com/bs_faq2.html#cout)); `cerr` means "character error (stream)" and `wcerr` means "wide character error (stream)". ### Example output to `[stderr](c/std_streams "cpp/io/c/std streams")` via `std::cerr` flushes out the pending output on `[std::cout](cout "cpp/io/cout")`, while output to `[stderr](c/std_streams "cpp/io/c/std streams")` via `[std::clog](clog "cpp/io/clog")` does not. ``` #include <thread> #include <iostream> #include <chrono> void f() { std::cout << "Output from thread..."; std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "...thread calls flush()" << std::endl; } int main() { std::thread t1(f); std::this_thread::sleep_for(std::chrono::seconds(1)); std::clog << "This output from main is not tie()'d to cout\n"; std::cerr << "This output is tie()'d to cout\n"; t1.join(); } ``` Possible output: ``` This output from main is not tie()'d to cout Output from thread...This output is tie()'d to cout ...thread calls flush() ``` ### See also | | | | --- | --- | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | [clogwclog](clog "cpp/io/clog") | writes to the standard C error stream `[stderr](c/std_streams "cpp/io/c/std streams")`(global object) | | [coutwcout](cout "cpp/io/cout") | writes to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`(global object) | | [stdinstdoutstderr](c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | cpp std::basic_istringstream std::basic\_istringstream ========================= | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT> > class basic_istringstream; ``` | | | The class template `std::basic_istringstream` implements input operations on string based streams. It effectively stores an instance of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` and performs input operations on it. At the low level, the class essentially wraps a raw string device implementation of `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` into a higher-level interface of `[std::basic\_istream](basic_istream "cpp/io/basic istream")`. The complete interface to unique `[std::basic\_stringbuf](basic_stringbuf "cpp/io/basic stringbuf")` members is provided. ![std-basic istringstream-inheritance.svg]() Inheritance diagram. Two specializations for common character types are also defined: | Defined in header `[<sstream>](../header/sstream "cpp/header/sstream")` | | --- | | Type | Definition | | `istringstream` | `basic_istringstream<char>` | | `wistringstream` | `basic_istringstream<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits`; the program is ill-formed if `Traits::char_type` is not `CharT`. | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | | `allocator_type` | `Allocator` | ### Member functions | | | | --- | --- | | [(constructor)](basic_istringstream/basic_istringstream "cpp/io/basic istringstream/basic istringstream") | constructs the string stream (public member function) | | [operator=](basic_istringstream/operator= "cpp/io/basic istringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](basic_istringstream/swap "cpp/io/basic istringstream/swap") (C++11) | swaps two string streams (public member function) | | [rdbuf](basic_istringstream/rdbuf "cpp/io/basic istringstream/rdbuf") | returns the underlying raw string device object (public member function) | | String operations | | [str](basic_istringstream/str "cpp/io/basic istringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [view](basic_istringstream/view "cpp/io/basic istringstream/view") (C++20) | obtains a view over the contents of underlying string device object (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_istringstream)](basic_istringstream/swap2 "cpp/io/basic istringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | Inherited from [std::basic\_istream](basic_istream "cpp/io/basic istream") ---------------------------------------------------------------------------- ### Member functions | | | --- | | Formatted input | | [operator>>](basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | Unformatted input | | [get](basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | | [peek](basic_istream/peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function of `std::basic_istream<CharT,Traits>`) | | [unget](basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | | [getline](basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [ignore](basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | | [read](basic_istream/read "cpp/io/basic istream/read") | extracts blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [readsome](basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | | [gcount](basic_istream/gcount "cpp/io/basic istream/gcount") | returns number of characters extracted by last unformatted input operation (public member function of `std::basic_istream<CharT,Traits>`) | | Positioning | | [tellg](basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | Miscellaneous | | [sync](basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | ### Member classes | | | | --- | --- | | [sentry](basic_istream/sentry "cpp/io/basic istream/sentry") | implements basic logic for preparation of the stream for input operations (public member class of `std::basic_istream<CharT,Traits>`) | Inherited from [std::basic\_ios](basic_ios "cpp/io/basic ios") ---------------------------------------------------------------- ### Member types | Member type | Definition | | --- | --- | | `char_type` | `CharT` | | `traits_type` | `Traits` | | `int_type` | `Traits::int_type` | | `pos_type` | `Traits::pos_type` | | `off_type` | `Traits::off_type` | ### Member functions | | | --- | | State functions | | [good](basic_ios/good "cpp/io/basic ios/good") | checks if no error has occurred i.e. I/O operations are available (public member function of `std::basic_ios<CharT,Traits>`) | | [eof](basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [fail](basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [bad](basic_ios/bad "cpp/io/basic ios/bad") | checks if a non-recoverable error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [operator!](basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | | [operator void\*operator bool](basic_ios/operator_bool "cpp/io/basic ios/operator bool") (until C++11)(since C++11) | checks if no error has occurred (synonym of `!fail()`) (public member function of `std::basic_ios<CharT,Traits>`) | | [rdstate](basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) | | Formatting | | [copyfmt](basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [fill](basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | Miscellaneous | | [exceptions](basic_ios/exceptions "cpp/io/basic ios/exceptions") | manages exception mask (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | | [rdbuf](basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | | [tie](basic_ios/tie "cpp/io/basic ios/tie") | manages tied stream (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [widen](basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) | Inherited from [std::ios\_base](ios_base "cpp/io/ios base") ------------------------------------------------------------- ### Member functions | | | --- | | Formatting | | [flags](ios_base/flags "cpp/io/ios base/flags") | manages format flags (public member function of `std::ios_base`) | | [setf](ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [unsetf](ios_base/unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function of `std::ios_base`) | | [precision](ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | | [width](ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | Locales | | [imbue](ios_base/imbue "cpp/io/ios base/imbue") | sets locale (public member function of `std::ios_base`) | | [getloc](ios_base/getloc "cpp/io/ios base/getloc") | returns current locale (public member function of `std::ios_base`) | | Internal extensible array | | [xalloc](ios_base/xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](ios_base/pword "cpp/io/ios base/pword") and [`iword()`](ios_base/iword "cpp/io/ios base/iword") (public static member function of `std::ios_base`) | | [iword](ios_base/iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function of `std::ios_base`) | | [pword](ios_base/pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function of `std::ios_base`) | | Miscellaneous | | [register\_callback](ios_base/register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function of `std::ios_base`) | | [sync\_with\_stdio](ios_base/sync_with_stdio "cpp/io/ios base/sync with stdio") [static] | sets whether C++ and C I/O libraries are interoperable (public static member function of `std::ios_base`) | | Member classes | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | | [Init](ios_base/init "cpp/io/ios base/Init") | initializes standard stream objects (public member class of `std::ios_base`) | | | | --- | | Member types and constants | | Type | Explanation | | [openmode](ios_base/openmode "cpp/io/ios base/openmode") | stream open mode type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`app`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | (typedef) | | [fmtflags](ios_base/fmtflags "cpp/io/ios base/fmtflags") | formatting flags type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`dec`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](manip/hex "cpp/io/manip/hex")` | | [`oct`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](manip/hex "cpp/io/manip/hex")` | | [`hex`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](manip/hex "cpp/io/manip/hex")` | | [`basefield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](manip/left "cpp/io/manip/left")` | | [`right`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](manip/left "cpp/io/manip/left")` | | [`internal`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](manip/left "cpp/io/manip/left")` | | [`adjustfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](ios_base/fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](manip/uppercase "cpp/io/manip/uppercase")` | (typedef) | | [iostate](ios_base/iostate "cpp/io/ios base/iostate") | state of the stream type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`goodbit`](ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | (typedef) | | [seekdir](ios_base/seekdir "cpp/io/ios base/seekdir") | seeking direction type The following constants are also defined: | Constant | Explanation | | --- | --- | | [`beg`](ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | (typedef) | | [event](ios_base/event "cpp/io/ios base/event") | specifies event type (enum) | | [event\_callback](ios_base/event_callback "cpp/io/ios base/event callback") | callback function type (typedef) |
programming_docs
cpp std::vprint_nonunicode std::vprint\_nonunicode ======================= | Defined in header `[<print>](../header/print "cpp/header/print")` | | | | --- | --- | --- | | ``` void vprint_nonunicode( std::FILE* stream, std::string_view fmt, std::format_args args ); ``` | (1) | (since C++23) | | ``` void vprint_nonunicode( std::string_view fmt, std::format_args args ); ``` | (2) | (since C++23) | Format `args` according to the format string `fmt`, and writes the result to the stream. 1) Writes the result of `[std::vformat](http://en.cppreference.com/w/cpp/utility/format/vformat)(fmt, args)` to the stream. The behavior is undefined if `stream` is not a valid pointer to a C stream. 2) same as (1) when `stream` is equal to the standard C output stream `[stdout](c/std_streams "cpp/io/c/std streams")`, i.e. ``` std::vprint_nonunicode(stdout, fmt, args); ``` ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](../utility/format/formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args | - | arguments to be formatted | ### Return value (none). ### Exceptions * `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. * `[std::system\_error](../error/system_error "cpp/error/system error")`, if writing to the stream fails. * Propagate exception thrown by any [formatter](../utility/format/formatter "cpp/utility/format/formatter"), e.g. `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")`. ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_print`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_format`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ### See also | | | | --- | --- | | [vprint\_unicode](vprint_unicode "cpp/io/vprint unicode") (C++23) | prints to Unicode capable `[stdout](c/std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_nonunicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_nonunicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint nonunicode (page does not exist)") (C++23) | outputs character data using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [print](print "cpp/io/print") (C++23) | prints to `[stdout](c/std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [format](../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | cpp std::io_errc std::io\_errc ============= | Defined in header `[<ios>](../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` enum class io_errc { stream = 1, }; ``` | | (since C++11) | The scoped enumeration `std::io_errc` defines the error codes reported by I/O streams in `[std::ios\_base::failure](ios_base/failure "cpp/io/ios base/failure")` exception objects. Only one error code (`std::io_errc::stream`) is required, although the implementation may define additional error codes. Because the appropriate specialization of `[std::is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum")` is provided, values of type `std::io_errc` are implicitly convertible to `[std::error\_code](../error/error_code "cpp/error/error code")`. ### Member constants | Enumeration constant | Value | | --- | --- | | `stream` | `1` | ### Non-member functions | | | | --- | --- | | [make\_error\_code(std::io\_errc)](io_errc/make_error_code "cpp/io/io errc/make error code") (C++11) | constructs an iostream error code (function) | | [make\_error\_condition(std::io\_errc)](io_errc/make_error_condition "cpp/io/io errc/make error condition") (C++11) | constructs an iostream error code (function) | ### Helper classes | | | | --- | --- | | [is\_error\_code\_enum<std::io\_errc>](io_errc/is_error_code_enum "cpp/io/io errc/is error code enum") (C++11) | extends the type trait `[std::is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum")` to identify iostream error codes (class template specialization) | ### Example ``` #include <iostream> #include <fstream> int main() { std::ifstream f("doesn't exist"); try { f.exceptions(f.failbit); } catch (const std::ios_base::failure& e) { std::cout << "Caught an ios_base::failure.\n"; if(e.code() == std::io_errc::stream) std::cout << "The error code is std::io_errc::stream\n"; } } ``` Output: ``` Caught an ios_base::failure. The error code is std::io_errc::stream ``` ### See also | | | | --- | --- | | [error\_code](../error/error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [error\_condition](../error/error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [failure](ios_base/failure "cpp/io/ios base/failure") | stream exception (public member class of `std::ios_base`) | cpp std::basic_ospanstream<CharT,Traits>::rdbuf std::basic\_ospanstream<CharT,Traits>::rdbuf ============================================ | | | | | --- | --- | --- | | ``` std::basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; ``` | | (since C++23) | Returns pointer to the wrapped raw device object. ### Parameters (none). ### Return value Pointer to the wrapped raw device object. ### Example ### See also | | | | --- | --- | | [rdbuf](../basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | cpp std::basic_ospanstream<CharT,Traits>::swap std::basic\_ospanstream<CharT,Traits>::swap =========================================== | | | | | --- | --- | --- | | ``` void swap( basic_ospanstream& other ); ``` | | (since C++23) | Exchanges the state of the stream with those of `other`. This is done by calling `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>::swap(other)` and swapping the wrapped `std::basic_spanbuf` objects (accessible through `*rdbuf()`). ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](../basic_spanbuf/swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::basic_ospanstream<CharT,Traits>::basic_ospanstream std::basic\_ospanstream<CharT,Traits>::basic\_ospanstream ========================================================= | | | | | --- | --- | --- | | ``` explicit basic_ospanstream( std::span<CharT> s, std::ios_base::openmode mode = std::ios_base::out ); ``` | (1) | (since C++23) | | ``` basic_ospanstream( basic_ospanstream&& rhs ); ``` | (2) | (since C++23) | | ``` basic_ospanstream( const basic_ospanstream& ) = delete; ``` | (3) | (since C++23) | Constructs a new `basic_ospanstream`. 1) Uses the storage referenced by `s` as initial underlying buffer of the wrapped `std::basic_spanbuf` device. The wrapped `std::basic_spanbuf` object is constructed as `basic_spanbuf<Char, Traits>(s, mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 2) Move constructor. Move constructs the `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` base subobject and the wrapped `std::basic_spanbuf` from those of `rhs`, and then calls `[set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf")` with the address of the wrapped `std::basic_spanbuf` in `*this` to install it. 3) Copy constructor is deleted. `basic_ospanstream` is not copyable. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as initial underlying buffer of stream | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another `basic_ospanstream` to be moved from | ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [(constructor)](../basic_spanbuf/basic_spanbuf "cpp/io/basic spanbuf/basic spanbuf") (C++23) | constructs a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::swap(std::basic_ospanstream) std::swap(std::basic\_ospanstream) ================================== | Defined in header `[<spanstream>](../../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( std::basic_ospanstream<CharT, Traits>& lhs, std::basic_ospanstream<CharT, Traits>& rhs ); ``` | | (since C++23) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_ospanstream`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ospanstream/swap") (C++23) | swaps two `basic_ospanstream` objects (public member function) | cpp std::basic_ospanstream<CharT,Traits>::operator= std::basic\_ospanstream<CharT,Traits>::operator= ================================================ | | | | | --- | --- | --- | | ``` basic_ospanstream& operator=( basic_ospanstream&& other ); ``` | (1) | (since C++23) | | ``` basic_ospanstream& operator=( const basic_ospanstream& ) = delete; ``` | (2) | (since C++23) | 1) Move assigns the `other` to `*this`, effectively move-assigning both the `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` base class subobject and the wrapped `std::basic_spanbuf`. 2) Copy assignment operator is deleted. `basic_ospanstream` is not copy assignable. Note that move assignment operator of the base class swaps all stream state variables (except for [`rdbuf()`](rdbuf "cpp/io/basic ospanstream/rdbuf")) between `*this` and `other`. It is implementation-defined whether the `std::basic_spanbuf` wrapped in `other` still holds an underlying buffer after the move assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another stream to move from | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](../basic_spanbuf/operator= "cpp/io/basic spanbuf/operator=") (C++23) | assigns a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | | [operator=](../basic_ostream/operator= "cpp/io/basic ostream/operator=") (C++11) | move-assigns from another `basic_ostream` (protected member function) | cpp std::basic_ospanstream<CharT,Traits>::span std::basic\_ospanstream<CharT,Traits>::span =========================================== | | | | | --- | --- | --- | | ``` std::span<CharT> span() const noexcept; ``` | (1) | (since C++23) | | ``` void span( std::span<CharT> s ) noexcept; ``` | (2) | (since C++23) | 1) Gets a `span` referencing the written area if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode of the wrapped `std::basic_spanbuf`, or a `span` referencing the underlying buffer otherwise. 2) Makes the wrapped `std::basic_spanbuf` perform I/O on the buffer referenced by `s`. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as the new underlying buffer of stream | ### Return value 1) A `std::span` referencing the underlying buffer or written area, depending on the open mode of the wrapped `std::basic_spanbuf`. 2) (none) ### Example ### See also | | | | --- | --- | | [span](../basic_spanbuf/span "cpp/io/basic spanbuf/span") (C++23) | obtains or initializes an underlying buffer according to mode (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::strstream::freeze std::strstream::freeze ====================== | | | | | --- | --- | --- | | ``` void freeze(bool flag = true); ``` | | | If the stream is using a dynamically-allocated array for output, disables (`flag == true`) or enables (`flag == false`) automatic allocation/deallocation of the buffer. Effectively calls `rdbuf()->freeze(flag)`. ### Notes After a call to `[str()](str "cpp/io/strstream/str")`, dynamic streams become frozen automatically. A call to `freeze(false)` is required before exiting the scope in which this `strstream` object was created. otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer. ### Parameters | | | | | --- | --- | --- | | flag | - | desired status | ### Return value (none). ### Example ``` #include <strstream> #include <iostream> int main() { std::strstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23; // note: no std::ends to demonstrate appending std::cout << "The output stream contains \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; // the stream is now frozen due to str() dyn << " More text"; // output to a frozen stream may be truncated std::cout << "The output stream contains \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; dyn.freeze(false); // freeze(false) must be called or the destructor will leak std::strstream dyn2; // dynamically-allocated output buffer dyn2 << "Test: " << 1.23; // note: no std::ends std::cout << "The output stream contains \""; std::cout.write(dyn2.str(), dyn2.pcount()) << "\"\n"; dyn2.freeze(false); // unfreeze the stream after str() dyn2 << " More text" << std::ends; // output will not be truncated (buffer grows) std::cout << "The output stream contains \"" << dyn2.str() << "\"\n"; dyn2.freeze(false); // freeze(false) must be called or the destructor will leak } ``` Possible output: ``` The output stream contains "Test: 1.23" The output stream contains "Test: 1.23 More " The output stream contains "Test: 1.23" The output stream contains "Test: 1.23 More text" ``` ### See also | | | | --- | --- | | [freeze](../strstreambuf/freeze "cpp/io/strstreambuf/freeze") | sets/clears the frozen state of the buffer (public member function of `std::strstreambuf`) | cpp std::strstream::rdbuf std::strstream::rdbuf ===================== | | | | | --- | --- | --- | | ``` strstreambuf* rdbuf() const; ``` | | | Returns a pointer to the associated `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`, casting away its constness (despite the const qualifier on the member function). ### Parameters (none). ### Return value Pointer to the associated `std::strsteambuf`, with constness cast away. ### Example ``` #include <strstream> int main() { const std::strstream buf; std::strstreambuf* ptr = buf.rdbuf(); } ``` cpp std::strstream::pcount std::strstream::pcount ====================== | | | | | --- | --- | --- | | ``` int pcount() const; ``` | | | Returns the number of characters that were output in the put area of the associated `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`. Effectively calls `rdbuf()->pcount()`. ### Parameters (none). ### Return value The number of characters in the put area, or zero if nothing was output. ### Example ``` #include <strstream> #include <iostream> int main() { std::strstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23 << std::ends; std::cout << "The size of the output is " << dyn.pcount() << " and it holds \"" << dyn.str() << "\"\n"; dyn.freeze(false); char buf[10]; std::strstream user(buf, 10); // user-provided output buffer user << 1.23; // note: no std::ends std::cout.write(buf, user.pcount()); std::cout << '\n'; } ``` Output: ``` The size of the output is 11 and it holds "Test: 1.23" 1.23 ``` ### See also | | | | --- | --- | | [pcount](../strstreambuf/pcount "cpp/io/strstreambuf/pcount") | returns the next pointer minus the beginning pointer in the output sequence: the number of characters written (public member function of `std::strstreambuf`) | cpp std::strstream::~strstream std::strstream::~strstream ========================== | | | | | --- | --- | --- | | ``` virtual ~strstream(); ``` | | | Destroys a `std::strstream` object, which also destroys the member `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`, which may call the deallocation function if the underlying buffer was dynamically-allocated and not frozen. ### Parameters (none). ### Notes If `[str()](str "cpp/io/strstream/str")` was called on a dynamic strstream and [freeze(false)](freeze "cpp/io/strstream/freeze") was not called after that, this destructor leaks memory. ### Example ``` #include <strstream> #include <iostream> int main() { { std::ostrstream s; // dynamic buffer s << 1.23 << std::ends; std::cout << s.str() << '\n'; s.freeze(false); } // destructor called, buffer deallocated { std::ostrstream s; s << 1.23 << std::ends; std::cout << s.str() << '\n'; // buf.freeze(false); } // destructor called, memory leaked { std::istrstream s("1.23"); // constant buffer double d; s >> d; std::cout << d << '\n'; } // destructor called, nothing to deallocate } ``` Output: ``` 1.23 1.23 1.23 ```
programming_docs
cpp std::strstream::strstream std::strstream::strstream ========================= | | | | | --- | --- | --- | | ``` strstream(); ``` | (1) | | | ``` strstream( char* s, int n, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (2) | | Constructs new input/output strstream and its underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`. 1) Default-constructs the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`, which creates a dynamically growing buffer, and initializes the base class with the address of the strstreambuf member. 2) Initialized the base class with the address of the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` member, which is initialized in one of the two possible ways, both of which use a user-provided fixed-size array: a) if `(mode & app) == 0` (the `app` bit is not set in `mode`), constructs the buffer by calling `strstreambuf(s, n, s)`. The behavior is undefined if there are less than `n` elements in the array whose first element is pointed to by `s`. b) if `(mode & app) != 0` (the `app` bit is set in `mode`), constructs the buffer by calling `strstreambuf(s, n, s + [std::strlen](http://en.cppreference.com/w/cpp/string/byte/strlen)(s))`. The behavior is undefined if there are less than `n` elements in the array whose first element is pointed to by `s` or if the array does not contain a valid null-terminated character sequence. ### Parameters | | | | | --- | --- | --- | | s | - | `char` array to use as the output buffer | | n | - | size of the array to be used for output | | mode | - | specifies stream open mode. It is a bitmask type, the following constants are defined (although only `app` is used): | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Example ``` #include <iostream> #include <strstream> #include <string> int main() { // dynamic buffer std::strstream s1; s1 << 1 << ' ' << 3.14 << " example" << std::ends; std::cout << "Buffer holds: '" << s1.str() << "'\n"; s1.freeze(false); int n; double d; std::string w; s1 >> n >> d >> w; std::cout << "Read back: n = " << n << ", d = " << d << ", w = '" << w << "'\n"; // static buffer char arr[20] = "-1 -3.14 "; std::strstream s2(arr, sizeof arr, std::ios_base::app); s2 << "another" << std::ends; std::cout << "Buffer holds: '" << s2.str() << "'\n"; s2 >> n >> d >> w; std::cout << "Read back: n = " << n << ", d = " << d << ", w = '" << w << "'\n"; } ``` Output: ``` Buffer holds: '1 3.14 example' Read back: n = 1, d = 3.14, w = 'example' Buffer holds: '-1 -3.14 another' Read back: n = -1, d = -3.14, w = 'another' ``` ### 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 115](https://cplusplus.github.io/LWG/issue115) | C++98 | overload (2) only considered the case`mode & app == 0` (`==` has higher precedence than `&`) | considers cases `(mode & app) == 0`and `(mode & app) != 0` | ### See also | | | | --- | --- | | [(constructor)](../strstreambuf/strstreambuf "cpp/io/strstreambuf/strstreambuf") | constructs a strstreambuf object (public member function of `std::strstreambuf`) | | [(constructor)](../istrstream/istrstream "cpp/io/istrstream/istrstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::istrstream`) | | [(constructor)](../ostrstream/ostrstream "cpp/io/ostrstream/ostrstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::ostrstream`) | cpp std::strstream::str std::strstream::str =================== | | | | | --- | --- | --- | | ``` char* str(); ``` | | | Returns the pointer to the beginning of the buffer, after freezing it. Effectively calls `rdbuf()->str()`. ### Parameters (none). ### Return value Pointer to the beginning of the buffer in the associated `std::strsteambuf` or a null pointer if no buffer is available. ### Notes Before a call to `str()` that uses the result as a C string, the stream buffer must be null-terminated. Regular output such as with `stream << 1.2` does not store a null terminator, it must be appended explicitly, typically with the manipulator `[std::ends](../manip/ends "cpp/io/manip/ends")`. After a call to `str()`, dynamic streams become frozen. A call to `freeze(false)` is required before exiting the scope in which this `strstream` object was created. otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer, which may leave the buffer not null-terminated. ### Example ``` #include <strstream> #include <iostream> int main() { std::strstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23; // not adding std::ends to demonstrate append behavior std::cout << "The output stream holds \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; // the stream is now frozen due to str() dyn << " More text" << std::ends; std::cout << "The output stream holds \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; dyn.freeze(false); } ``` Possible output: ``` The stream holds "Test: 1.23" The stream holds "Test: 1.23 More " ``` ### See also | | | | --- | --- | | [str](../strstreambuf/str "cpp/io/strstreambuf/str") | marks the buffer frozen and returns the beginning pointer of the input sequence (public member function of `std::strstreambuf`) | cpp std::basic_ios<CharT,Traits>::setstate std::basic\_ios<CharT,Traits>::setstate ======================================= | | | | | --- | --- | --- | | ``` void setstate( iostate state ); ``` | | | Sets the stream error flags `state` in addition to currently set flags. Essentially calls `clear(rdstate() | state)`. May throw an exception. ### Parameters | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | state | - | stream error state flags to set. It can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`goodbit`](../ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](../ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](../ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](../ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | | ### Return value (none). ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream stream; if (!stream.fail()) { std::cout << "stream is not fail\n"; } stream.setstate(std::ios_base::failbit); if (stream.fail()) { std::cout << "now stream is fail\n"; } if (!stream.good()) { std::cout << "and stream is not good\n"; } } ``` Output: ``` stream is not fail now stream is fail and stream is not good ``` ### See also | | | | --- | --- | | [rdstate](rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function) | | [clear](clear "cpp/io/basic ios/clear") | modifies state flags (public member function) | cpp std::basic_ios<CharT,Traits>::fill std::basic\_ios<CharT,Traits>::fill =================================== | | | | | --- | --- | --- | | ``` CharT fill() const; ``` | (1) | | | ``` CharT fill( CharT ch ); ``` | (2) | | Manages the fill character used to pad the output conversions to the specified field width. 1) returns the current fill character 2) sets the fill character to `ch`, returns previous value of the fill character ### Parameters | | | | | --- | --- | --- | | ch | - | the character to use as fill character | ### Return value the fill character before the call to the function. ### Example ``` #include <iostream> #include <iomanip> int main () { std::cout << "With default setting : [" << std::setw(10) << 40 << "]\n"; char prev = std::cout.fill('x'); std::cout << "Replaced '" << prev << "' with '" << std::cout.fill() << "': [" << std::setw(10) << 40 << "]\n"; } ``` Output: ``` With default setting : [ 40] Replaced ' ' with 'x': [xxxxxxxx40] ``` ### See also | | | | --- | --- | | [setfill](../manip/setfill "cpp/io/manip/setfill") | changes the fill character (function template) | cpp std::basic_ios<CharT,Traits>::fail std::basic\_ios<CharT,Traits>::fail =================================== | | | | | --- | --- | --- | | ``` bool fail() const; ``` | | | Returns `true` if an error has occurred on the associated stream. Specifically, returns `true` if `badbit` or `failbit` is set in `[rdstate()](rdstate "cpp/io/basic ios/rdstate")`. See [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") for the list of conditions that set `failbit` or `badbit`. ### Parameters (none). ### Return value `true` if an error has occurred, `false` otherwise. ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> int main() { std::ifstream file("test.txt"); if(!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for(int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; } ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](good "cpp/io/basic ios/good"), **`fail()`**, etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](good "cpp/io/basic ios/good") | **`fail()`** | [`bad()`](bad "cpp/io/basic ios/bad") | [`eof()`](eof "cpp/io/basic ios/eof") | [`operator bool`](operator_bool "cpp/io/basic ios/operator bool") | [`operator!`](operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | | | | | --- | --- | | [ferror](../c/ferror "cpp/io/c/ferror") | checks for a file error (function) | cpp std::basic_ios<CharT,Traits>::operator! std::basic\_ios<CharT,Traits>::operator! ======================================== | | | | | --- | --- | --- | | ``` bool operator!() const; ``` | | | Returns `true` if an error has occurred on the associated stream. Specifically, returns `true` if `badbit` or `failbit` is set in `rdstate()`. ### Parameters (none). ### Return value `true` if an error has occurred, `false` otherwise. ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> int main() { std::ifstream file("test.txt"); if(!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for(int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; } ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](good "cpp/io/basic ios/good"), [`fail()`](fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](good "cpp/io/basic ios/good") | [`fail()`](fail "cpp/io/basic ios/fail") | [`bad()`](bad "cpp/io/basic ios/bad") | [`eof()`](eof "cpp/io/basic ios/eof") | [`operator bool`](operator_bool "cpp/io/basic ios/operator bool") | **`operator!`** | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | cpp std::basic_ios<CharT,Traits>::init std::basic\_ios<CharT,Traits>::init =================================== | | | | | --- | --- | --- | | ``` protected: void init( std::basic_streambuf<CharT,Traits>* sb ); ``` | | | Sets the associated stream buffer to `sb` and initializes the internal state. The postconditions are as follows: | Element | Value | | --- | --- | | `[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")` | `sb` | | `[tie()](tie "cpp/io/basic ios/tie")` | null pointer | | `[rdstate()](rdstate "cpp/io/basic ios/rdstate")` | `goodbit` if `sb` is not a null pointer, otherwise `badbit` | | `[exceptions()](exceptions "cpp/io/basic ios/exceptions")` | `goodbit` | | [`flags()`](../ios_base/flags "cpp/io/ios base/flags") | `skipws | dec` | | [`width()`](../ios_base/width "cpp/io/ios base/width") | `​0​` | | [`precision()`](../ios_base/precision "cpp/io/ios base/precision") | `6` | | `[fill()](fill "cpp/io/basic ios/fill")` | `widen(' ')` | | [`getloc()`](../ios_base/getloc "cpp/io/ios base/getloc") | a copy of the value returned by `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)()` | This member function is protected: it is called by the constructors of the derived stream classes `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` and `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` once the associated stream buffer is known. Until this function is called, every member function (including the destructor) of the default-constructed `[std::basic\_ios](../basic_ios "cpp/io/basic ios")` invokes undefined behavior. Note that `basic_ios` is a virtual base class, and therefore its constructor is not called by the constructors of those directly derived classes, which is why two-stage initialization is necessary. ### Parameters | | | | | --- | --- | --- | | sb | - | stream buffer to associate to | ### See also | | | | --- | --- | | [(constructor)](basic_ios "cpp/io/basic ios/basic ios") | constructs the object (public member function) | cpp std::basic_ios<CharT,Traits>::imbue std::basic\_ios<CharT,Traits>::imbue ==================================== | | | | | --- | --- | --- | | ``` std::locale imbue( const std::locale& loc ); ``` | | | Replaces the current locale. Effectively calls `ios_base::imbue(loc)` and if there is an associated stream buffer (`rdbuf() != 0`), then calls `rdbuf()->pubimbue(loc)`. ### Parameters | | | | | --- | --- | --- | | loc | - | the new locale | ### Return value The previous locale, as returned by `ios_base::imbue(loc)`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <sstream> #include <locale> int main() { std::istringstream iss; iss.imbue(std::locale("en_US.UTF8")); std::cout << "Current locale: " << iss.getloc().name() << '\n'; iss.imbue(std::locale()); std::cout << "Global locale : " << iss.getloc().name() << '\n'; } ``` Output: ``` Current locale: en_US.UTF8 Global locale : C ``` cpp std::basic_ios<CharT,Traits>::rdbuf std::basic\_ios<CharT,Traits>::rdbuf ==================================== | | | | | --- | --- | --- | | ``` std::basic_streambuf<CharT, Traits>* rdbuf() const; ``` | (1) | | | ``` std::basic_streambuf<CharT, Traits>* rdbuf( std::basic_streambuf<CharT, Traits>* sb ); ``` | (2) | | Manages the associated stream buffer. 1) Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer. 2) Sets the associated stream buffer to `sb`. The error state is cleared by calling `[clear()](clear "cpp/io/basic ios/clear")`. Returns the associated stream buffer before the operation. If there is no associated stream buffer, returns a null pointer. ### Parameters | | | | | --- | --- | --- | | sb | - | stream buffer to associate to | ### Return value The associated stream buffer, or a null pointer if there was no associated stream buffer. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream local; auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with // buffer of 'local' object // now std::cout work with 'local' buffer // you don't see this message std::cout << "some message"; // go back to old buffer std::cout.rdbuf(cout_buff); // you will see this message std::cout << "back to default buffer\n"; // print 'local' content std::cout << "local content: " << local.str() << "\n"; } ``` Output: ``` back to default buffer local content: some message ``` ### See also | | | | --- | --- | | [set\_rdbuf](set_rdbuf "cpp/io/basic ios/set rdbuf") | replaces the `rdbuf` without clearing its error state (protected member function) | cpp std::basic_ios<CharT,Traits>::tie std::basic\_ios<CharT,Traits>::tie ================================== | | | | | --- | --- | --- | | ``` std::basic_ostream<CharT,Traits>* tie() const; ``` | (1) | | | ``` std::basic_ostream<CharT,Traits>* tie( std::basic_ostream<CharT,Traits>* str ); ``` | (2) | | Manages the tied stream. A tied stream is an output stream which is synchronized with the sequence controlled by the stream buffer (`[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")`), that is, `flush()` is called on the tied stream before any input/output operation on `*this`. 1) Returns the current tied stream. If there is no tied stream, a null pointer is returned. 2) Sets the current tied stream to `str`. Returns the tied stream before the operation. If there is no tied stream, a null pointer is returned. ### Parameters | | | | | --- | --- | --- | | str | - | an output stream to set as the tied stream | ### Return value The tied stream, or a null pointer if there was no tied stream. ### Exceptions May throw implementation-defined exceptions. ### Notes By default, the standard stream `cout` is tied to `cin` and `cerr`. Similarly, its wide counterpart `wcout` is tied to `wcin` and `wcerr`. ### Example ``` #include <iostream> #include <fstream> #include <string> int main() { std::ofstream os("test.txt"); std::ifstream is("test.txt"); std::string value("0"); os << "Hello"; is >> value; std::cout << "Result before tie(): \"" << value << "\"\n"; is.clear(); is.tie(&os); is >> value; std::cout << "Result after tie(): \"" << value << "\"\n"; } ``` Output: ``` Result before tie(): "0" Result after tie(): "Hello" ```
programming_docs
cpp std::basic_ios<CharT,Traits>::swap std::basic\_ios<CharT,Traits>::swap =================================== | | | | | --- | --- | --- | | ``` protected: void swap( basic_ios& other ) noexcept; ``` | | (since C++11) | Exchanges the states of `*this` and `other`, except for the associated `rdbuf` objects. `[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")` and `other.rdbuf()` returns the same values as before the call. This swap function is protected: it is called by the swap member functions of the derived stream classes such as `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` or `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")`, which know how to correctly swap the associated streambuffers. ### Parameters | | | | | --- | --- | --- | | other | - | the `basic_ios` object to exchange the state with | ### Return value (none). ### See also | | | | --- | --- | | [move](move "cpp/io/basic ios/move") (C++11) | moves from another `[std::basic\_ios](../basic_ios "cpp/io/basic ios")` except for `rdbuf` (protected member function) | cpp std::basic_ios<CharT,Traits>::eof std::basic\_ios<CharT,Traits>::eof ================================== | | | | | --- | --- | --- | | ``` bool eof() const; ``` | | | Returns `true` if the associated stream has reached end-of-file. Specifically, returns `true` if `eofbit` is set in `[rdstate()](rdstate "cpp/io/basic ios/rdstate")`. See [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") for the list of conditions that set `eofbit`. ### Parameters (none). ### Return value `true` if an end-of-file has occurred, `false` otherwise. ### Notes This function only reports the stream state as set by the most recent I/O operation; it does not examine the associated data source. For example, if the most recent I/O was a [`get()`](../basic_istream/get "cpp/io/basic istream/get") which returned the last byte of a file, `eof()` returns `false`. The next `get()` fails to read anything and sets the `eofbit`. Only then does `eof()` return `true`. In typical usage, input stream processing stops on any error. `eof()` and `[fail()](fail "cpp/io/basic ios/fail")` can then be used to distinguish between different error conditions. ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> int main() { std::ifstream file("test.txt"); if(!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for(int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; } ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](good "cpp/io/basic ios/good"), [`fail()`](fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](good "cpp/io/basic ios/good") | [`fail()`](fail "cpp/io/basic ios/fail") | [`bad()`](bad "cpp/io/basic ios/bad") | **`eof()`** | [`operator bool`](operator_bool "cpp/io/basic ios/operator bool") | [`operator!`](operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | | | | | --- | --- | | [feof](../c/feof "cpp/io/c/feof") | checks for the end-of-file (function) | cpp std::basic_ios<CharT,Traits>::operator bool std::basic\_ios<CharT,Traits>::operator bool ============================================ | | | | | --- | --- | --- | | ``` operator void*() const; ``` | (1) | (until C++11) | | ``` explicit operator bool() const; ``` | (2) | (since C++11) | Checks whether the stream has no errors. 1) Returns a null pointer if `fail()` returns `true`, otherwise returns a non-null pointer. This pointer is implicitly convertible to `bool` and may be used in boolean contexts. 2) Returns `true` if the stream has no errors and is ready for I/O operations. Specifically, returns `!fail()`. This operator makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as `while(stream >> value) {...}` or `while(getline(stream, string)){...}`. Such loops execute the loop's body only if the input operation succeeded. ### Parameters (none). ### Return value `true` if the stream has no errors, `false` otherwise. ### Example ``` #include <iostream> #include <sstream> int main() { std::istringstream s("1 2 3 error"); int n; std::cout << std::boolalpha << "s is " << static_cast<bool>(s) << '\n'; while (s >> n) { std::cout << n << '\n'; } std::cout << "s is " << static_cast<bool>(s) << '\n'; } ``` Output: ``` s is true 1 2 3 s is false ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](good "cpp/io/basic ios/good"), [`fail()`](fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](good "cpp/io/basic ios/good") | [`fail()`](fail "cpp/io/basic ios/fail") | [`bad()`](bad "cpp/io/basic ios/bad") | [`eof()`](eof "cpp/io/basic ios/eof") | **`operator bool`** | [`operator!`](operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | cpp std::basic_ios<CharT,Traits>::widen std::basic\_ios<CharT,Traits>::widen ==================================== | | | | | --- | --- | --- | | ``` char_type widen( char c ) const; ``` | | | Converts a character `c` to its equivalent in the current locale. The result is converted from `char` to character type used within the stream if needed. Effectively calls `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)< [std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char_type> >(getloc()).widen(c)`. ### Parameters | | | | | --- | --- | --- | | c | - | character to convert | ### Return value Character converted to `char_type`. ### See also | | | | --- | --- | | [narrow](narrow "cpp/io/basic ios/narrow") | narrows characters (public member function) | | [do\_widen](../../locale/ctype/widen "cpp/locale/ctype/widen") [virtual] | converts a character or characters from `char` to `charT` (virtual protected member function of `std::ctype<CharT>`) | | [btowc](../../string/multibyte/btowc "cpp/string/multibyte/btowc") | widens a single-byte narrow character to wide character, if possible (function) | cpp std::basic_ios<CharT,Traits>::exceptions std::basic\_ios<CharT,Traits>::exceptions ========================================= | | | | | --- | --- | --- | | ``` std::ios_base::iostate exceptions() const; ``` | (1) | | | ``` void exceptions( std::ios_base::iostate except ); ``` | (2) | | Gets and sets the exception mask of the stream. The exception mask determines which error states trigger exceptions of type `[failure](../ios_base/failure "cpp/io/ios base/failure")`. 1) Returns the exception mask. 2) Sets the exception mask to `except`. If the stream has an error state covered by the exception mask when called, an exception is immediately triggered. ### Parameters | | | | | --- | --- | --- | | except | - | exception mask | ### Return value 1) The current exception mask. 2) (none) ### Notes ### Example ``` #include <iostream> #include <fstream> int main() { int ivalue; try { std::ifstream in("in.txt"); in.exceptions(std::ifstream::failbit); // may throw in >> ivalue; // may throw } catch (const std::ios_base::failure& fail) { // handle exception here std::cout << fail.what() << '\n'; } } ``` Possible output: ``` basic_ios::clear: iostream error ``` cpp std::basic_ios<CharT,Traits>::bad std::basic\_ios<CharT,Traits>::bad ================================== | | | | | --- | --- | --- | | ``` bool bad() const; ``` | | | Returns `true` if non-recoverable error has occurred on the associated stream. Specifically, returns `true` if [`badbit`](../ios_base/iostate "cpp/io/ios base/iostate") is set in `rdstate()`. See [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") for the list of conditions that set `badbit`. ### Parameters (none). ### Return value `true` if a non-recoverable error has occurred, `false` otherwise. ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> int main() { std::ifstream file("test.txt"); if(!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for(int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; } ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](good "cpp/io/basic ios/good"), [`fail()`](fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](good "cpp/io/basic ios/good") | [`fail()`](fail "cpp/io/basic ios/fail") | **`bad()`** | [`eof()`](eof "cpp/io/basic ios/eof") | [`operator bool`](operator_bool "cpp/io/basic ios/operator bool") | [`operator!`](operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | cpp std::basic_ios<CharT,Traits>::basic_ios std::basic\_ios<CharT,Traits>::basic\_ios ========================================= | | | | | --- | --- | --- | | ``` protected: basic_ios(); ``` | (1) | | | ``` public: explicit basic_ios( std::basic_streambuf<CharT,Traits>* sb ); ``` | (2) | | | | (3) | | | ``` private: basic_ios(const basic_ios&); ``` | (until C++11) | | ``` public: basic_ios(const basic_ios& ) = delete; ``` | (since C++11) | Constructs new `basic_ios` object. 1) Default constructor. The internal state is not initialized. `[init()](init "cpp/io/basic ios/init")` must be called before the first use of the object or before destructor, otherwise the behavior is undefined. 2) Initializes the internal state by calling `init(sb)`. The associated stream buffer is set to `sb`. 3) The copy constructor was declared `private:` and not defined until C++11 and is declared as deleted in C++11: I/O streams are not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Parameters | | | | | --- | --- | --- | | sb | - | stream buffer to associate to | cpp std::basic_ios<CharT,Traits>::~basic_ios std::basic\_ios<CharT,Traits>::~basic\_ios ========================================== | | | | | --- | --- | --- | | ``` virtual ~basic_ios(); ``` | | | Destroys the `basic_ios` object. `rdbuf` is not destroyed. ### Notes This destructor is `virtual` because the base class destructor, [`ios_base::~ios_base`](../ios_base/~ios_base "cpp/io/ios base/~ios base") is virtual. ### 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 53](https://cplusplus.github.io/LWG/issue53) | C++98 | it was unspecified whether `rdbuf` is destroyed | it is not destroyed | cpp std::basic_ios<CharT,Traits>::clear std::basic\_ios<CharT,Traits>::clear ==================================== | | | | | --- | --- | --- | | ``` void clear( std::ios_base::iostate state = std::ios_base::goodbit ); ``` | | | Sets the stream error state flags by assigning them the value of `state`. By default, assigns `[std::ios\_base::goodbit](../ios_base/iostate "cpp/io/ios base/iostate")` which has the effect of clearing all error state flags. If `[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")` is a null pointer (i.e. there is no associated stream buffer), then `state | badbit` is assigned. ### Parameters | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | state | - | new error state flags setting. It can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`goodbit`](../ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](../ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](../ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](../ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | | ### Return value (none). ### Exceptions If the new error state includes a bit that is also included in the [`exceptions()`](exceptions "cpp/io/basic ios/exceptions") mask, throws an exception of type `[failure](../ios_base/failure "cpp/io/ios base/failure")`. ### Example `clear()` without arguments can be used to unset the [`failbit`](#Parameters) after unexpected input; for `[std::cin](http://en.cppreference.com/w/cpp/io/cin).putback(c)` see [`ungetc`](../c/ungetc#Notes "cpp/io/c/ungetc"). ``` #include <iostream> #include <string> int main() { for (char c : {'\n', '4', '1', '.', '3', '\n', 'Z', 'Y', 'X'}) std::cin.putback(c); // emulate user's input (not portable: see ungetc Notes) double n; while( std::cout << "Please, enter a number: " && ! (std::cin >> n) ) { std::cin.clear(); std::string line; std::getline(std::cin, line); std::cout << line << "\nI am sorry, but '" << line << "' is not a number\n"; } std::cout << n << "\nThank you for entering the number " << n << '\n'; } ``` Output: ``` Please, enter a number: XYZ I am sorry, but 'XYZ' is not a number Please, enter a number: 3.14 Thank you for entering the number 3.14 ``` ### See also | | | | --- | --- | | [setstate](setstate "cpp/io/basic ios/setstate") | sets state flags (public member function) | | [rdstate](rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function) | cpp std::basic_ios<CharT,Traits>::rdstate std::basic\_ios<CharT,Traits>::rdstate ====================================== | | | | | --- | --- | --- | | ``` iostate rdstate() const; ``` | | | Returns the current stream error state. ### Parameters (none). ### Return value current stream error state. It is a bitmask type and can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`goodbit`](../ios_base/iostate "cpp/io/ios base/iostate") | no error | | [`badbit`](../ios_base/iostate "cpp/io/ios base/iostate") | irrecoverable stream error | | [`failbit`](../ios_base/iostate "cpp/io/ios base/iostate") | input/output operation failed (formatting or extraction error) | | [`eofbit`](../ios_base/iostate "cpp/io/ios base/iostate") | associated input sequence has reached end-of-file | ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream stream; if (stream.rdstate() == std::ios_base::goodbit) { std::cout << "stream state is goodbit\n"; } stream.setstate(std::ios_base::eofbit); // check state is exactly eofbit (no failbit and no badbit) if (stream.rdstate() == std::ios_base::eofbit) { std::cout << "stream state is eofbit\n"; } } ``` Output: ``` stream state is goodbit stream state is eofbit ``` ### See also | | | | --- | --- | | [setstate](setstate "cpp/io/basic ios/setstate") | sets state flags (public member function) | | [clear](clear "cpp/io/basic ios/clear") | modifies state flags (public member function) | cpp std::basic_ios<CharT,Traits>::good std::basic\_ios<CharT,Traits>::good =================================== | | | | | --- | --- | --- | | ``` bool good() const; ``` | | | Returns `true` if the most recent I/O operation on the stream completed successfully. Specifically, returns result of `rdstate() == 0`. See [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") for the list of conditions that set the stream status bits. ### Parameters (none). ### Return value `true` if the stream error flags are all false, `false` otherwise. ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> int main() { const char* fname = "/tmp/test.txt"; std::ofstream ofile{fname}; ofile << "10 " << "11 " << "12 " << "non-int"; ofile.close(); std::ifstream file{fname}; if (!file.good()) { std::cout << "#1. Opening file test.txt failed - " "one of the error flags is true\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for (int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) { std::cout << "#2. I/O error while reading - badbit is true\n"; return EXIT_FAILURE; } else if (file.eof()) { std::cout << "#3. End of file reached successfully - eofbit is true\n" "This is fine even though file.good() is false\n"; } else if (file.fail()) { std::cout << "#4. Non-integer data encountered - failbit is true\n"; } } ``` Possible output: ``` 10 11 12 #4. Non-integer data encountered - failbit is true ``` ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors (**`good()`**, [`fail()`](fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags: | | | | --- | --- | | [`ios_base::iostate`](../ios_base/iostate "cpp/io/ios base/iostate") flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | **`good()`** | [`fail()`](fail "cpp/io/basic ios/fail") | [`bad()`](bad "cpp/io/basic ios/bad") | [`eof()`](eof "cpp/io/basic ios/eof") | [`operator bool`](operator_bool "cpp/io/basic ios/operator bool") | [`operator!`](operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true |
programming_docs
cpp std::basic_ios<CharT,Traits>::set_rdbuf std::basic\_ios<CharT,Traits>::set\_rdbuf ========================================= | | | | | --- | --- | --- | | ``` protected: void set_rdbuf( std::basic_streambuf<CharT,Traits>* sb ); ``` | | (since C++11) | Sets the associated stream buffer to `sb` without clearing the error state. This member function is protected: it is called by the move constructors of the derived streams such as `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` or `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")`, as the final step after constructing the base class and after moving the stream buffer: only the most derived stream class knows how to correctly move the stream buffer, but `[std::basic\_ios](../basic_ios "cpp/io/basic ios")` needs to be made aware of the stream's new location so that its public member functions can access it. ### Parameters | | | | | --- | --- | --- | | sb | - | stream buffer to associate to | ### Return value (none). ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [rdbuf](rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function) | cpp std::basic_ios<CharT,Traits>::move std::basic\_ios<CharT,Traits>::move =================================== | | | | | --- | --- | --- | | ``` protected: void move( basic_ios& other ); ``` | | (since C++11) | | ``` protected: void move( basic_ios&& other ); ``` | | (since C++11) | Replaces the current state with that of `other`, except for the associated `rdbuf`. `other` is in valid, but unspecified state after the call. After the call to this function, `[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")` returns a null pointer, `other.rdbuf()` returns the same value as before the call, and `other.tie()` returns a null pointer. This member function is protected: it is called by the protected move constructors of the derived stream classes `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` and `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`, which, in turn, are called by the public move constructors of the further derived stream classes such as `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")`, which know how to correctly move the associated streambuffer. ### Parameters | | | | | --- | --- | --- | | other | - | the `basic_ios` object to transfer the state from | ### Return value (none). ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ios/swap") (C++11) | swaps with another `[std::basic\_ios](../basic_ios "cpp/io/basic ios")` except for `rdbuf` (protected member function) | cpp std::basic_ios<CharT,Traits>::narrow std::basic\_ios<CharT,Traits>::narrow ===================================== | | | | | --- | --- | --- | | ``` char narrow( char_type c, char dfault ) const; ``` | | | Converts a current locale-specific character `c` to its standard equivalent. The result is converted from `char_type` to `char` if needed. If no conversion can be performed, the function returns `dfault`. Effectively calls `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)< [std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char_type> >(getloc()).narrow(c, dfault);`. ### Parameters | | | | | --- | --- | --- | | c | - | character to convert | | dfault | - | character to return if the conversion was unsuccessful | ### Return value Character converted to its standard equivalent and then to `char`. `dfault` is returned if the conversion fails. ### See also | | | | --- | --- | | [widen](widen "cpp/io/basic ios/widen") | widens characters (public member function) | | [narrow](../../locale/ctype/narrow "cpp/locale/ctype/narrow") | invokes `do_narrow` (public member function of `std::ctype<CharT>`) | | [wctob](../../string/multibyte/wctob "cpp/string/multibyte/wctob") | narrows a wide character to a single-byte narrow character, if possible (function) | cpp std::basic_ios<CharT,Traits>::copyfmt std::basic\_ios<CharT,Traits>::copyfmt ====================================== | | | | | --- | --- | --- | | ``` basic_ios& copyfmt(const basic_ios& other); ``` | | | If `other` refers to the same object as `*this`, has no effects. Otherwise, copies the state of the stream `other` into `*this`. This is done in the following sequence: 1) Calls every callback registered by `[register\_callback()](../ios_base/register_callback "cpp/io/ios base/register callback")` passing [`erase_event`](../ios_base/event "cpp/io/ios base/event") as parameter 2) Copies all member objects from `other` to `*this` except for `[rdstate()](rdstate "cpp/io/basic ios/rdstate")`, the exception mask, and `[rdbuf()](rdbuf "cpp/io/basic ios/rdbuf")`. In particular, makes copies of the locale, the formatting flags, the contents of the arrays `[std::ios\_base::iword](../ios_base/iword "cpp/io/ios base/iword")` and `[std::ios\_base::pword](../ios_base/pword "cpp/io/ios base/pword")` (but not the `iword` and `pword` pointers themselves), the callbacks, and the tied stream. 3) Calls every callback registered by `[register\_callback()](../ios_base/register_callback "cpp/io/ios base/register callback")` passing [`copyfmt_event`](../ios_base/event "cpp/io/ios base/event") as parameter 4) Copies the exception mask from `other` to `*this` as if by calling `exceptions(other.exceptions())` ### Parameters | | | | | --- | --- | --- | | other | - | another stream to use as source | ### Return value `*this`. ### Notes The second pass through the callbacks may be used to deep-copy the user-defined objects pointed to by the pointers in `[std::ios\_base::pword](../ios_base/pword "cpp/io/ios base/pword")`. `copyfmt()` may be used to save and restore the state of a stream. Boost provides a more fine-grained [I/O state savers](http://www.boost.org/doc/libs/release/libs/io/doc/ios_state.html) library for the same purpose. ### Example makes the `[std::ofstream](../basic_ofstream "cpp/io/basic ofstream")` object "out" behave exactly like `[std::cout](../cout "cpp/io/cout")`, including formatting, `tie()` to `[std::cin](../cin "cpp/io/cin")`, etc. ``` #include <iostream> #include <fstream> int main() { std::ofstream out; out.copyfmt(std::cout); // copy everything except rdstate and rdbuf out.clear(std::cout.rdstate()); // copy rdstate out.basic_ios<char>::rdbuf(std::cout.rdbuf()); // share the buffer out << "Hello, world\n"; } ``` Output: ``` Hello, world ``` cpp std::basic_filebuf<CharT,Traits>::underflow std::basic\_filebuf<CharT,Traits>::underflow ============================================ | | | | | --- | --- | --- | | ``` protected: virtual int_type underflow() ``` | | | Reads more data into the input area. Behaves like the base class `std::basic_streambuf::underflow`, except that to read the data from the associated character sequence (the file) into the get area, first reads the bytes from the file into a temporary buffer (allocated as large as necessary), then uses `std::codecvt::in` of the imbued locale to convert the external (typically, multibyte) representation to the internal form which is then used to populate the get area. The conversion may be skipped if the locale's `std::codecvt::always_noconv` returns `true`. ### Parameters (none). ### Return value `Traits::to_int_type(*gptr())` (the first character of the pending sequence) in case of success, or `Traits::eof()` in case of failure. ### Example ``` #include <fstream> #include <iostream> struct mybuf : std::filebuf { int underflow() { std::cout << "Before underflow(): size of the get area is " << egptr()-eback() << " with " << egptr()-gptr() << " read positions available\n"; int rc = std::filebuf::underflow(); std::cout << "underflow() returns " << rc << ".\nAfter the call, " << "size of the get area is " << egptr()-eback() << " with " << egptr()-gptr() << " read positions available\n"; return rc; } }; int main() { mybuf buf; buf.open("test.txt", std::ios_base::in); std::istream stream(&buf); while(stream.get()) ; } ``` Possible output: ``` Before underflow(): size of the get area is 0 with 0 read positions available underflow() returns 73. After the call, size of the get area is 110 with 110 read positions available Before underflow(): size of the get area is 110 with 0 read positions available underflow() returns -1. After the call, size of the get area is 0 with 0 read positions available ``` ### See also | | | | --- | --- | | [underflow](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](../basic_stringbuf/underflow "cpp/io/basic stringbuf/underflow") [virtual] | returns the next character available in the input sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [underflow](../strstreambuf/underflow "cpp/io/strstreambuf/underflow") [virtual] | reads a character from the input sequence without advancing the next pointer (virtual protected member function of `std::strstreambuf`) | | [uflow](uflow "cpp/io/basic filebuf/uflow") [virtual] | reads from the associated file and advances the next pointer in the get area (virtual protected member function) | | [overflow](overflow "cpp/io/basic filebuf/overflow") [virtual] | writes characters to the associated file from the put area (virtual protected member function) | | [sgetc](../basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::basic_filebuf<CharT,Traits>::imbue std::basic\_filebuf<CharT,Traits>::imbue ======================================== | | | | | --- | --- | --- | | ``` protected: virtual void imbue( const std::locale& loc ) ``` | | | Changes the associated locale so that all characters inserted or extracted after this call (and until another call to `imbue()`) are converted using the `[std::codecvt](../../locale/codecvt "cpp/locale/codecvt")` facet of `loc`. If the old locale's encoding is state-dependent and file is not positioned at the beginning, then the new locale must have the same `[std::codecvt](../../locale/codecvt "cpp/locale/codecvt")` facet as the one previously imbued. ### Parameters | | | | | --- | --- | --- | | loc | - | the locale to imbue the stream with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [imbue](../basic_streambuf/pubimbue "cpp/io/basic streambuf/pubimbue") [virtual] | changes the associated locale (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [imbue](../basic_ios/imbue "cpp/io/basic ios/imbue") | sets the locale (public member function of `std::basic_ios<CharT,Traits>`) | cpp std::basic_filebuf<CharT,Traits>::swap std::basic\_filebuf<CharT,Traits>::swap ======================================= | | | | | --- | --- | --- | | ``` void swap( std::basic_filebuf& rhs ); ``` | | (since C++11) | Swaps the state and the contents of `*this` and `rhs`. ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_filebuf` | ### Return value (none). ### Notes This function is called automatically when swapping `[std::fstream](../basic_fstream "cpp/io/basic fstream")` objects, it is rarely necessary to call it directly. ### Example ``` #include <fstream> #include <string> #include <iostream> int main() { std::ifstream fin("test.in"); // read-only std::ofstream fout("test.out"); // write-only std::string s; getline(fin, s); std::cout << s << '\n'; // outputs the first line of test.in fin.rdbuf()->swap(*fout.rdbuf()); //swap the underlying buffers getline(fin, s); // fails: cannot read from a write-only filebuf std::cout << s << '\n'; // prints empty line } ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function) | | [std::swap(std::basic\_filebuf)](swap2 "cpp/io/basic filebuf/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [swap](../basic_fstream/swap "cpp/io/basic fstream/swap") (C++11) | swaps two file streams (public member function of `std::basic_fstream<CharT,Traits>`) | cpp std::basic_filebuf<CharT,Traits>::basic_filebuf std::basic\_filebuf<CharT,Traits>::basic\_filebuf ================================================= | | | | | --- | --- | --- | | ``` basic_filebuf(); ``` | (1) | | | ``` basic_filebuf( const std::basic_filebuf& rhs ) = delete; ``` | (2) | (since C++11) | | ``` basic_filebuf( std::basic_filebuf&& rhs ); ``` | (3) | (since C++11) | Contructs new `std::basic_filebuf` object. 1) Constructs a `std::basic_filebuf` object, initializing the base class by calling the default constructor of `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")`. The created `basic_filebuf` is not associated with a file, and `[is\_open()](is_open "cpp/io/basic filebuf/is open")` returns `false`. 2) The copy constructor is deleted; `std::basic_filebuf` is not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") 3) Move-constructs a `std::basic_filebuf` object by moving all contents from another `std::basic_filebuf` object `rhs`, including the buffers, the associated file, the locale, the openmode, the is\_open variable, and all other state. After move, `rhs` is not associated with a file and `rhs.is_open()==false`. The member pointers of the base class `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` of `rhs` and of the base class of `*this` are guaranteed to point to different buffers (unless null). ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_filebuf` | ### Notes Typically called by the constructor of `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function) | | [(destructor)](~basic_filebuf "cpp/io/basic filebuf/~basic filebuf") [virtual] | destructs a basic\_filebuf object and closes the file if it is open (virtual public member function) | cpp std::basic_filebuf<CharT,Traits>::seekpos std::basic\_filebuf<CharT,Traits>::seekpos ========================================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekpos( pos_type sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | | | Repositions the file pointer, if possible, to the position indicated by `sp`. If the associated file is not open (`is_open() == false`), fails immediately. If the file is open for writing, first writes the put area and any unshift sequences required by the currently imbued locale, using `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`. Then repositions the file pointer, as if by calling `[std::fsetpos()](../c/fsetpos "cpp/io/c/fsetpos")`. If the file is open for reading, updates the get area if necessary. If `sp` was not obtained by calling `[seekoff()](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff")` or `seekpos()` on the same file, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | sp | - | file position obtained by `[seekoff()](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff")` or `seekpos()` called earlier on the same file | | which | - | defines which of the input and/or output sequences to affect. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `sp` on success or `pos_type(off_type(-1))` on failure. ### Notes `seekpos()` is called by `[std::basic\_streambuf::pubseekpos()](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos")`, which is called by the single-argument versions of `[std::basic\_istream::seekg()](../basic_istream/seekg "cpp/io/basic istream/seekg")` and `[std::basic\_ostream::seekp()](../basic_ostream/seekp "cpp/io/basic ostream/seekp")`. Many implementations do not update the get area in `seekpos()`, delegating to `[underflow()](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow")` that is called by the next `[sgetc()](../basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc")`. ### Example On some implementations, the get area is emptied by `seekpos()` and the second `underflow()` is necessary to observe the effects. ``` #include <fstream> #include <iostream> struct mybuf : std::filebuf { pos_type seekpos(pos_type sp, std::ios_base::openmode which) { std::cout << "Before seekpos(" << sp << "), size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; pos_type rc = std::filebuf::seekpos(sp, which); std::cout << "seekpos() returns " << rc << ".\nAfter the call, " << "size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; // uncomment if get area is emptied by seekpos() // std::filebuf::underflow(); // std::cout << "after forced underflow(), size of the get area is " // << egptr() - eback() << " with " // << egptr() - gptr() << " read positions available.\n"; return rc; } }; int main() { mybuf buf; buf.open("test.txt", std::ios_base::in); std::istream stream(&buf); stream.get(); // read one char to force underflow() stream.seekg(2); } ``` Possible output: ``` Before seekpos(2), size of the get area is 110 with 109 read positions available. seekpos() returns 2. After the call, size of the get area is 110 with 108 read positions available. ``` ### 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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | `seekpos` returned an undefinedinvalid stream position on failure | `pos_type(off_type(-1))`is returned on failure | ### See also | | | | --- | --- | | [pubseekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function) | | [fseek](../c/fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | cpp std::basic_filebuf<CharT,Traits>::sync std::basic\_filebuf<CharT,Traits>::sync ======================================= | | | | | --- | --- | --- | | ``` protected: virtual int sync() ``` | | | If a put area exists (e.g. the file was opened for writing), calls `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")` to write all pending output to the file, then flushes the file as if by calling `[std::fflush](../c/fflush "cpp/io/c/fflush")`. If a get area exists (e.g. the file was opened for reading), the effect is implementation-defined. Typical implementation may empty out the get area and move the current file position back by the corresponding number of bytes. ### Parameters (none). ### Return value `​0​` in case of success, `-1` in case of failure. ### Notes `sync()` or its equivalent is implicitly called for output streams by [`close()`](close "cpp/io/basic filebuf/close"), [`seekoff()`](seekoff "cpp/io/basic filebuf/seekoff"), and [`seekpos()`](seekpos "cpp/io/basic filebuf/seekpos") and explicitly called by `[std::basic\_streambuf::pubsync()](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync")`. ### Example ### See also | | | | --- | --- | | [pubsync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [fflush](../c/fflush "cpp/io/c/fflush") | synchronizes an output stream with the actual file (function) |
programming_docs
cpp std::swap(std::basic_filebuf) std::swap(std::basic\_filebuf) ============================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( std::basic_filebuf<CharT,Traits>& lhs, std::basic_filebuf<CharT,Traits>& rhs ); ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` objects whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function) | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | cpp std::basic_filebuf<CharT,Traits>::overflow std::basic\_filebuf<CharT,Traits>::overflow =========================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type overflow ( int_type c = Traits::eof() ); ``` | | | Writes some data from the put area to the associated character sequence (to the file). Behaves like the base class `[std::basic\_streambuf::overflow](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`, except that to write the data, first uses `[std::codecvt::out](../../locale/codecvt/out "cpp/locale/codecvt/out")` of the imbued locale to convert the characters into external (possibly multibyte) representation, stored in a temporary buffer (allocated as large as necessary), then uses file I/O to copy all fully-converted bytes into the file. If `[std::codecvt::always\_noconv](../../locale/codecvt/always_noconv "cpp/locale/codecvt/always noconv")` is true, the call to `[std::codecvt::out](../../locale/codecvt/out "cpp/locale/codecvt/out")` may be skipped. If the conversion fails with `[std::codecvt\_base::error](../../locale/codecvt_base "cpp/locale/codecvt base")`, returns `Traits::eof()` without attempting any output. If the associated file is not open (`is_open() == false`), returns `Traits::eof()` before doing anything. ### Parameters (none). ### Return value `Traits::not_eof(c)` to indicate success or `Traits::eof()` to indicate failure. ### Example ### See also | | | | --- | --- | | [overflow](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function) | cpp std::basic_filebuf<CharT,Traits>::operator= std::basic\_filebuf<CharT,Traits>::operator= ============================================ | | | | | --- | --- | --- | | ``` std::basic_filebuf& operator=( std::basic_filebuf&& rhs ); ``` | | (since C++11) | | ``` std::basic_filebuf& operator=( const std::basic_filebuf& rhs ) = delete; ``` | | | Assigns another `basic_filebuf` object. 1) First calls `[close()](close "cpp/io/basic filebuf/close")` to close the associated file, then moves the contents of `rhs` into `*this`: the put and get buffers, the associated file, the locale, the openmode, the is\_open flag, and any other state. After the move, `rhs` is not associated with a file and `rhs.is_open() == false`. 2) The copy assignment operator is deleted; `basic_filebuf` is not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_filebuf` that will be moved from | ### Return value `*this`. ### Example ``` #include <fstream> #include <string> #include <iostream> int main() { std::ifstream fin("test.in"); // read-only std::ofstream fout("test.out"); // write-only std::string s; getline(fin, s); std::cout << s << '\n'; // output *fin.rdbuf() = std::move(*fout.rdbuf()); getline(fin, s); std::cout << s << '\n'; // empty line std::cout << std::boolalpha << fout.is_open() << '\n'; // prints "false" } ``` ### See also | | | | --- | --- | | [(constructor)](basic_filebuf "cpp/io/basic filebuf/basic filebuf") | constructs a basic\_filebuf object (public member function) | | [swap](swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function) | cpp std::basic_filebuf<CharT,Traits>::close std::basic\_filebuf<CharT,Traits>::close ======================================== | | | | | --- | --- | --- | | ``` std::basic_filebuf<CharT, Traits>* close(); ``` | | | If a put area exist (e.g. file was opened for writing), first calls `overflow(Traits::eof())` to write all pending output to the file, including any unshift sequences. If the most recently called function, out of `[underflow()](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow")`, `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`, `[seekpos()](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos")`, and `[seekoff()](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff")`, was `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`, then calls `std::codecvt::unshift()`, perhaps multiple times, to determine the unshift sequence according to the imbued locale, and writes that sequence to file with `overflow(Traits::eof())`. Then, closes the file as if by calling `[std::fclose()](../c/fclose "cpp/io/c/fclose")`, regardless of whether any of the preceding calls succeeded or failed. If any of the function calls made, including the call to `[std::fclose()](../c/fclose "cpp/io/c/fclose")`, fails, returns a null pointer. If any of the function calls made throws an exception, the exception is caught and rethrown after calling `[std::fclose()](../c/fclose "cpp/io/c/fclose")`. If the file is already closed, returns a null pointer right away. In any case, updates the private member variable that is accessed by `[is\_open()](is_open "cpp/io/basic filebuf/is open")`. ### Parameters (none). ### Return value `this` on success, a null pointer on failure. ### Notes `close()` is typically called through the destructor of `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` (which, in turn, is typically called by the destructor of `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`. ### Example ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic filebuf/is open") | checks if the associated file is open (public member function) | | [(destructor)](~basic_filebuf "cpp/io/basic filebuf/~basic filebuf") [virtual] | destructs a basic\_filebuf object and closes the file if it is open (virtual public member function) | cpp std::basic_filebuf<CharT,Traits>::~basic_filebuf std::basic\_filebuf<CharT,Traits>::~basic\_filebuf ================================================== | | | | | --- | --- | --- | | ``` virtual ~basic_filebuf(); ``` | | | Calls `[close()](close "cpp/io/basic filebuf/close")` to close the associated file and destructs all other members of `basic_filebuf`. If an exception is thrown by `[close()](close "cpp/io/basic filebuf/close")`, it is caught and not rethrown. ### Parameters (none). ### Return value (none). ### Notes Typically called by the destructor of `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`. ### Example ### See also | | | | --- | --- | | [(constructor)](basic_filebuf "cpp/io/basic filebuf/basic filebuf") | constructs a basic\_filebuf object (public member function) | | [close](close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function) | cpp std::basic_filebuf<CharT,Traits>::open std::basic\_filebuf<CharT,Traits>::open ======================================= | | | | | --- | --- | --- | | ``` std::basic_filebuf<CharT, Traits>* open( const char* s, std::ios_base::openmode mode ) ``` | (1) | | | ``` std::basic_filebuf<CharT, Traits>* open( const std::string& str, std::ios_base::openmode mode ) ``` | (2) | (since C++11) | | ``` std::basic_filebuf<CharT, Traits>* open( const std::filesystem::path& p, std::ios_base::openmode mode ) ``` | (3) | (since C++17) | | ``` std::basic_filebuf<CharT, Traits>* open( const std::filesystem::path::value_type* s, std::ios_base::openmode mode ) ``` | (4) | (since C++17) | Opens the file with the given name (`s`, `p.c_str()` (since C++17) or `str.c_str()`, depending on the overload). `openmode` values may be written as, e.g., `std::ios::out|std::ios::app`. | | | | --- | --- | | Overload (4) is only provided if `std::filesystem::path::value_type` is not `char`. | (since C++17) | The file is opened as if by calling `[std::fopen](../c/fopen "cpp/io/c/fopen")` with the second argument (`mode`) determined as follows: | mode | openmode & ~ate | Action if file already exists | Action if file does not exist | | --- | --- | --- | --- | | "r" | `in` | Read from start | Failure to open | | "w" | `out`, `out|trunc` | Destroy contents | Create new | | "a" | `app`, `out|app` | Append to file | Create new | | "r+" | `out|in` | Read from start | Error | | "w+" | `out|in|trunc` | Destroy contents | Create new | | "a+" | `out|in|app`, `in|app` | Write to end | Create new | | "rb" | `binary|in` | Read from start | Failure to open | | "wb" | `binary|out`, `binary|out|trunc` | Destroy contents | Create new | | "ab" | `binary|app`, `binary|out|app` | Write to end | Create new | | "r+b" | `binary|out|in` | Read from start | Error | | "w+b" | `binary|out|in|trunc` | Destroy contents | Create new | | "a+b" | `binary|out|in|app`, `binary|in|app` | Write to end | Create new | If `openmode` is not one of the modes listed, the `open()` fails. If the open operation succeeds and `openmode & [std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode) != 0` (the `ate` bit is set), repositions the file position to the end of file, as if by calling `[std::fseek](http://en.cppreference.com/w/cpp/io/c/fseek)(file, 0, [SEEK\_END](http://en.cppreference.com/w/cpp/io/c))`, where `file` is the pointer returned by calling `fopen`. If the repositioning fails, calls `[close()](close "cpp/io/basic filebuf/close")` and returns a null pointer to indicate failure. If the associated file was already open, returns a null pointer right away. ### Parameters | | | | | --- | --- | --- | | s, str, p | - | the file name to open; `s` must point to a null-terminated string | | openmode | - | the file opening mode, a binary OR of the `[std::ios\_base](../ios_base "cpp/io/ios base")` modes | ### Return value `this` on success, a null pointer on failure. ### Notes `open()` is typically called through the constructor or the `open()` member function of `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`. ### Example ``` #include <fstream> #include <iostream> int main() { std::string filename = "Test.b"; std::filebuf fb; // prepare a file to read double d = 3.14; if (!fb.open(filename, std::ios::binary|std::ios::out)) { std::cout << "Open file " << filename << " for write failed\n"; return 1; } fb.sputn(reinterpret_cast<char*>(&d), sizeof d); fb.close(); // open file for reading double d2 = 0.0; if (!fb.open(filename, std::ios::binary|std::ios::in)) { std::cout << "Open file " << filename << " for read failed\n"; return 1; } auto got = fb.sgetn(reinterpret_cast<char*>(&d2), sizeof d2); if (sizeof(d2) != got) { std::cout << "Read of " << filename << " failed\n"; } else { std::cout << "Read back from file: " << d2 << '\n'; } } ``` Output: ``` Read back from file: 3.14 ``` ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic filebuf/is open") | checks if the associated file is open (public member function) | | [close](close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function) | cpp std::basic_filebuf<CharT,Traits>::setbuf std::basic\_filebuf<CharT,Traits>::setbuf ========================================= | | | | | --- | --- | --- | | ``` protected: virtual std::basic_streambuf<CharT, Traits>* setbuf( char_type* s, std::streamsize n ) ``` | | | If `s` is a null pointer and `n` is zero, the filebuf becomes *unbuffered* for output, meaning `pbase()` and `pptr()` are null and any output is immediately sent to file. Otherwise, a call to `setbuf()` replaces the internal buffer (the controlled character sequence) with the user-supplied character array whose first element is pointed to by `s` and allows this `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` object to use up to `n` bytes in that array for buffering. This function is protected virtual, it may only be called through `pubsetbuf()` or from member functions of a user-defined class derived from `std::basic_filebuf`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the first CharT in the user-provided buffer or null | | n | - | the number of CharT elements in the user-provided buffer or zero | ### Return value `this`. ### Notes The conditions when this function may be used and the way in which the provided buffer is used is implementation-defined. * GCC 4.6 libstdc++ `setbuf()` may only be called when the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` is not associated with a file (has no effect otherwise). With a user-provided buffer, reading from file reads `n-1` bytes at a time. * Clang++3.0 libc++ `setbuf()` may be called after opening the file, but before any I/O (may crash otherwise). With a user-provided buffer, reading from file reads largest multiples of 4096 that fit in the buffer. * Visual Studio 2010 `setbuf()` may be called at any time, even after some I/O took place. Current contents of the buffer, if any, are lost. The standard does not define any behavior for this function except that `setbuf(0, 0)` called before any I/O has taken place is required to set unbuffered output. ### Example provide a 10k buffer for reading. On linux, the strace utility may be used to observe the actual number of bytes read. ``` #include <fstream> #include <iostream> #include <string> int main() { int cnt = 0; std::ifstream file; char buf[10241]; file.rdbuf()->pubsetbuf(buf, sizeof buf); file.open("/usr/share/dict/words"); for (std::string line; getline(file, line); ) ++cnt; std::cout << cnt << '\n'; } ``` ### See also | | | | --- | --- | | [pubsetbuf](../basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [setvbuf](../c/setvbuf "cpp/io/c/setvbuf") | sets the buffer and its size for a file stream (function) | cpp std::basic_filebuf<CharT,Traits>::showmanyc std::basic\_filebuf<CharT,Traits>::showmanyc ============================================ | | | | | --- | --- | --- | | ``` protected: virtual std::streamsize showmanyc() ``` | | | If implemented, returns the number of characters left to read from the file. ### Parameters (none). ### Return value The number of characters available for reading from the file, or `-1` if the end of file was reached. ### Notes This function is optional. If not implemented, this function returns `​0​` (since the base class version `std::basic_streambuf::showmanyc` gets called). Whether implemented or not, this function is normally called by `std::basic_streambuf::in_avail` if the get area is empty. The name of this function stands for "stream: how many characters?", so it is pronounced "S how many C", rather than "show many C" ### Example implementation test to see if showmanyc() is implemented for filebuf. ``` #include <fstream> #include <iostream> struct mybuf : std::filebuf { using std::filebuf::showmanyc; }; int main() { mybuf fin; fin.open("main.cpp", std::ios_base::in); std::cout << "showmanyc() returns " << fin.showmanyc() << '\n'; } ``` Possible output: ``` showmanyc() returns 267 ``` ### See also | | | | --- | --- | | [in\_avail](../basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) | | [readsome](../basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_filebuf<CharT,Traits>::uflow std::basic\_filebuf<CharT,Traits>::uflow ======================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type uflow() ``` | | | Behaves like the `[underflow()](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow")`, except that if `[underflow()](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow")` succeeds (does not return `Traits::eof()`), then advances the next pointer for the get area. In other words, consumes one of the characters obtained by `[underflow()](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow")`. ### Parameters (none). ### Return value The value of the character that was read and consumed in case of success, or `Traits::eof()` in case of failure. ### Example ### See also | | | | --- | --- | | [uflow](../basic_streambuf/uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function) | | [overflow](overflow "cpp/io/basic filebuf/overflow") [virtual] | writes characters to the associated file from the put area (virtual protected member function) | cpp std::basic_filebuf<CharT,Traits>::seekoff std::basic\_filebuf<CharT,Traits>::seekoff ========================================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekoff( off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | | | Repositions the file pointer, if possible, to the position that corresponds to exactly `off` characters from beginning, end, or current position of the file (depending on the value of `dir`). If the associated file is not open (`is_open() == false`), fails immediately. If the multibyte character encoding is state-dependent ([`codecvt::encoding()`](../../locale/codecvt/encoding "cpp/locale/codecvt/encoding") returned `-1`) or variable-length (`codecvt::encoding()` returned `​0​`) and the offset `off` is not `​0​`, fails immediately: this function cannot determine the number of bytes that correspond to `off` characters. If `dir` is not `[std::basic\_ios::cur](../ios_base/seekdir "cpp/io/ios base/seekdir")` or the offset `off` is not `​0​`, and the most resent operation done on this filebuf object was output (that is, either the put buffer is not empty, or the most recently called function was `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`), then calls `std::codecvt::unshift` to determine the unshift sequence necessary, and writes that sequence to the file by calling `[overflow()](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`. Then converts the argument `dir` to a value `whence` of type `int` as follows: | value of `dir` | value of `whence` | | --- | --- | | `std::basic_ios::beg` | `[SEEK\_SET](../c "cpp/io/c")` | | `std::basic_ios::end` | `[SEEK\_END](../c "cpp/io/c")` | | `std::basic_ios::cur` | `[SEEK\_CUR](../c "cpp/io/c")` | Then, if the character encoding is fixed-width (`codecvt::encoding()` returns some positive number `width`), moves the file pointer as if by `[std::fseek](http://en.cppreference.com/w/cpp/io/c/fseek)(file, width\*off, whence)`. Otherwise, moves the file pointer as if by `[std::fseek](http://en.cppreference.com/w/cpp/io/c/fseek)(file, 0, whence)`. The `openmode` argument, required by the base class function signature, is usually ignored, because `std::basic_filebuf` maintains only one file position. ### Parameters | | | | | --- | --- | --- | | off | - | relative position to set the position indicator to. | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | | which | - | defines which of the input and/or output sequences to affect. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value A newly constructed object of type `pos_type` which stores the resulting file position, or `pos_type(off_type(-1))` on failure. ### Notes `seekoff()` is called by `std::basic_streambuf::pubseekoff`, which is called by `std::basic_istream::seekg`, `std::basic_ostream::seekp`, `std::basic_istream::tellg`, and `std::basic_ostream::tellp`. ### Example ``` #include <iostream> #include <fstream> #include <locale> template<typename CharT> int get_encoding(const std::basic_istream<CharT>& stream) { using Facet = std::codecvt<CharT, char, std::mbstate_t>; return std::use_facet<Facet>(stream.getloc()).encoding(); } int main() { // prepare a 10-byte file holding 4 characters ("zß水𝄋") in UTF-8 std::ofstream("text.txt") << "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // open using a non-converting encoding std::ifstream f1("text.txt"); std::cout << "f1's locale's encoding() returns " << get_encoding(f1) << '\n' << "pubseekoff(3, beg) returns " << f1.rdbuf()->pubseekoff(3, std::ios_base::beg) << '\n' << "pubseekoff(0, end) returns " << f1.rdbuf()->pubseekoff(0, std::ios_base::end) << '\n'; // open using UTF-8 std::wifstream f2("text.txt"); f2.imbue(std::locale("en_US.UTF-8")); std::cout << "f2's locale's encoding() returns " << get_encoding(f2) << '\n' << "pubseekoff(3, beg) returns " << f2.rdbuf()->pubseekoff(3, std::ios_base::beg) << '\n' << "pubseekoff(0, end) returns " << f2.rdbuf()->pubseekoff(0, std::ios_base::end) << '\n'; } ``` Output: ``` f1's locale's encoding() returns 1 pubseekoff(3, beg) returns 3 pubseekoff(0, end) returns 10 f2's locale's encoding() returns 0 pubseekoff(3, beg) returns -1 pubseekoff(0, end) returns 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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | `seekoff` returned an undefinedinvalid stream position on failure | `pos_type(off_type(-1))`is returned on failure | ### See also | | | | --- | --- | | [pubseekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function) | | [fseek](../c/fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) |
programming_docs
cpp std::basic_filebuf<CharT,Traits>::is_open std::basic\_filebuf<CharT,Traits>::is\_open =========================================== | | | | | --- | --- | --- | | ``` bool is_open() const; ``` | | | Returns `true` if the most recent call to `[open()](open "cpp/io/basic filebuf/open")` succeeded and there has been no call to `[close()](close "cpp/io/basic filebuf/close")` since then. ### Parameters (none). ### Return value `true` if the associated file is open, `false` otherwise. ### Notes This function is typically called by `[std::basic\_fstream::is\_open()](../basic_fstream/is_open "cpp/io/basic fstream/is open")`. ### Example ``` #include <fstream> #include <iostream> int main() { std::ifstream fs("test.txt"); std::filebuf fb; fb.open("test.txt", std::ios_base::in); std::cout << std::boolalpha << "direct call: " << fb.is_open() << '\n' << "through streambuf: " << fs.rdbuf()->is_open() << '\n' << "through fstream: " << fs.is_open() << '\n'; } ``` Output: ``` direct call: true through streambuf: true through fstream: true ``` ### See also | | | | --- | --- | | [open](open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function) | | [close](close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function) | cpp std::basic_filebuf<CharT,Traits>::pbackfail std::basic\_filebuf<CharT,Traits>::pbackfail ============================================ | | | | | --- | --- | --- | | ``` protected: virtual int_type pbackfail( int_type c = Traits::eof() ) ``` | | | This protected virtual function is called by the public functions [`basic_streambuf::sungetc`](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") and [`basic_streambuf::sputbackc`](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") (which, in turn, are called by [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") and [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback")). 1) The caller is requesting that the get area is backed up by one character (`pbackfail()` is called with no arguments), in which case, this function re-reads the file starting one byte earlier and decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"), e.g. by calling `gbump(-1)`. 2) The caller attempts to putback a different character from the one retrieved earlier (`pbackfail()` is called with the character that needs to be put back), in which case a) First, checks if there is a putback position, and if there isn't, backs up the get area by re-reading the file starting one byte earlier. a) Then checks what character is in the putback position. If the character held there is already equal to `c`, as determined by `Traits::eq(to_char_type(c), gptr()[-1])`, then simply decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"). b) Otherwise, if the buffer is allowed to modify its own get area, decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr") and writes `c` to the location pointed to gptr() after adjustment. This function never modifies the file, only the get area of the in-memory buffer. If the file is not open (`is_open()==false`, this function returns `Traits::eof()` immediately. ### Parameters | | | | | --- | --- | --- | | c | - | the character to put back, or Traits::eof() to indicate that backing up of the get area is requested | ### Return value `c` on success except if `c` was `Traits::eof()`, in which case `Traits::not_eof(c)` is returned. `Traits::eof()` on failure. ### Example ### See also | | | | --- | --- | | [pbackfail](../basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputbackc](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [unget](../basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](../basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_fstream<CharT,Traits>::rdbuf std::basic\_fstream<CharT,Traits>::rdbuf ======================================== | | | | | --- | --- | --- | | ``` std::basic_filebuf<CharT, Traits>* rdbuf() const; ``` | | (since C++11) | Returns pointer to the underlying raw file device object. ### Parameters (none). ### Return value Pointer to the underlying raw file device. ### Example cpp std::basic_fstream<CharT,Traits>::swap std::basic\_fstream<CharT,Traits>::swap ======================================= | | | | | --- | --- | --- | | ``` void swap( basic_fstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_iostream<CharT, Traits>::swap(other)` and `rdbuf()->swap(other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <fstream> #include <iomanip> #include <iostream> #include <string> bool create_stream(std::fstream& fs, const std::string& path) { try { std::fstream fst { path, std::ios::trunc | std::ios::in | std::ios::out }; if (fst.is_open()) { fst.swap( fs ); return true; } } catch (...) { std::cout << "Exception!\n"; } return false; } void use_stream(std::fstream& fs) { fs.seekg(0); std::string data; fs >> data; std::cout << "data: " << std::quoted(data) << '\n'; } int main() { std::fstream fs; std::string path = "/tmp/test_file.txt"; if (create_stream(fs, path)) { fs.write(path.c_str(), path.length()); use_stream(fs); } } ``` Possible output: ``` data: "/tmp/test_file.txt" ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic fstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](../basic_filebuf/swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::swap(std::basic_fstream) std::swap(std::basic\_fstream) ============================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( basic_fstream<CharT,Traits> &lhs, basic_fstream<CharT,Traits> &rhs ); ``` | | | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_fstream](http://en.cppreference.com/w/cpp/io/basic_fstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic fstream/swap") (C++11) | swaps two file streams (public member function) | cpp std::basic_fstream<CharT,Traits>::operator= std::basic\_fstream<CharT,Traits>::operator= ============================================ | | | | | --- | --- | --- | | ``` basic_fstream& operator=( basic_fstream&& other ); ``` | | (since C++11) | Move assigns the file stream `other` to `*this`, effectively move-assigning both the `[std::basic\_iostream](../basic_iostream "cpp/io/basic iostream")` base class and the associated `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")`. `other` is left with no associated file. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | file stream to move. | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic fstream/swap") (C++11) | swaps two file streams (public member function) | | [operator=](../basic_filebuf/operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function of `std::basic_filebuf<CharT,Traits>`) | | [operator=](../basic_iostream/operator= "cpp/io/basic iostream/operator=") (C++11) | move-assigns another `basic_iostream` (protected member function) | cpp std::basic_fstream<CharT,Traits>::close std::basic\_fstream<CharT,Traits>::close ======================================== | | | | | --- | --- | --- | | ``` void close(); ``` | | | Closes the associated file. Effectively calls [`rdbuf()->close()`](../basic_filebuf/close "cpp/io/basic filebuf/close"). If an error occurs during operation, `setstate(failbit)` is called. ### Parameters (none). ### Return value (none). ### Notes This function is called by the destructor of basic\_fstream when the stream object goes out of scope and is not usually invoked directly. ### Example ``` #include <string> #include <fstream> #include <iostream> int main() { std::fstream f1("example1", std::ios::out), f2("example2", std::ios::out), f3("example3", std::ios::out); std::cout << std::boolalpha << f1.is_open() << '\n' << f2.is_open() << '\n' << f3.is_open() << '\n'; f1.close(); f2.close(); std::cout << f1.is_open() << '\n' << f2.is_open() << '\n' << f3.is_open() << '\n'; } ``` Possible output: ``` true true true false false true ``` ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic fstream/is open") | checks if the stream has an associated file (public member function) | | [open](open "cpp/io/basic fstream/open") | opens a file and associates it with the stream (public member function) | | [close](../basic_filebuf/close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_fstream<CharT,Traits>::open std::basic\_fstream<CharT,Traits>::open ======================================= | | | | | --- | --- | --- | | ``` void open( const char *filename, ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (1) | | | ``` void open( const std::filesystem::path::value_type *filename, ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (2) | (since C++17) | | ``` void open( const std::string &filename, ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (3) | (since C++11) | | ``` void open( const std::filesystem::path &filename, ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (4) | (since C++17) | Opens and associates the file with name `filename` with the file stream. Calls `setstate(failbit)` on failure. | | | | --- | --- | | Calls `clear()` on success. | (since C++11) | 1-2) Effectively calls `rdbuf()->open(filename, mode)`. (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). Overload (2) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 3-4) Effectively calls (1-2) as if by `open(filename.c_str(), mode)`. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Return value (none). ### Example ``` #include <string> #include <fstream> #include <iostream> int main() { std::string filename = "example.123"; std::fstream fs; fs.open(filename); if (!fs.is_open()) { fs.clear(); fs.open(filename, std::ios::out); // create file fs.close(); fs.open(filename); } std::cout << std::boolalpha; std::cout << "fs.is_open() = " << fs.is_open() << '\n'; std::cout << "fs.good() = " << fs.good() << '\n'; } ``` ### 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 22](https://cplusplus.github.io/LWG/issue22) | C++98 | it was unclear how error state changes upon a successful open | the error state is unchanged | ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic fstream/is open") | checks if the stream has an associated file (public member function) | | [close](close "cpp/io/basic fstream/close") | closes the associated file (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_fstream<CharT,Traits>::basic_fstream std::basic\_fstream<CharT,Traits>::basic\_fstream ================================================= | | | | | --- | --- | --- | | ``` basic_fstream(); ``` | (1) | | | ``` explicit basic_fstream( const char* filename, std::ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (2) | | | ``` explicit basic_fstream( const std::filesystem::path::value_type* filename, std::ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (3) | (since C++17) | | ``` explicit basic_fstream( const std::string& filename, std::ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (4) | (since C++11) | | ``` template< class FsPath > explicit basic_fstream( const FsPath& filename, std::ios_base::openmode mode = ios_base::in|ios_base::out ); ``` | (5) | (since C++17) | | ``` basic_fstream( basic_fstream&& other ); ``` | (6) | (since C++11) | | ``` basic_fstream( const basic_fstream& rhs) = delete; ``` | (7) | (since C++11) | Constructs new file stream. 1) Default constructor: constructs a stream that is not associated with a file: default-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` and constructs the base with the pointer to this default-constructed `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member. 2-3) First, performs the same steps as the default constructor, then associates the stream with a file by calling `rdbuf()->open(filename, mode)` (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). If the `open()` call returns a null pointer, sets `setstate(failbit)`. Overload (3) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 4-5) Same as `basic_fstream(filename.c_str(), mode)`. (5) participates in overload resolution only if `FsPath` is `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")`. (since C++17) 6) Move constructor. First, move-constructs the base class from `other` (which does not affect the `rdbuf()` pointer), then move-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member, then calls `this->set_rdbuf()` to install the new `basic_filebuf` as the `rdbuf()` pointer in the base class. 7) The copy-constructor is deleted: this class is not copyable. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another file stream to use as source | ### Example ``` #include <fstream> #include <utility> #include <string> int main() { std::fstream f0; std::fstream f1("test.bin", std::ios::binary); std::string name = "example.txt"; std::fstream f2(name); std::fstream f3(std::move(f1)); } ``` ### 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 3430](https://cplusplus.github.io/LWG/issue3430) | C++17 | `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")` overload led to unwanted conversions | avoided by making it a template | ### See also | | | | --- | --- | | [open](open "cpp/io/basic fstream/open") | opens a file and associates it with the stream (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | | [set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf") | replaces the `rdbuf` without clearing its error state (protected member function) | | [(constructor)](../basic_iostream/basic_iostream "cpp/io/basic iostream/basic iostream") | constructs the object (public member function of `std::basic_iostream<CharT,Traits>`) | cpp std::basic_fstream<CharT,Traits>::is_open std::basic\_fstream<CharT,Traits>::is\_open =========================================== | | | | | --- | --- | --- | | ``` bool is_open(); ``` | | (until C++11) | | ``` bool is_open() const; ``` | | (since C++11) | Checks if the file stream has an associated file. Effectively calls [`rdbuf()->is_open()`](../basic_filebuf/is_open "cpp/io/basic filebuf/is open"). ### Parameters (none). ### Return value `true` if the file stream has an associated file, `false` otherwise. ### Example ``` #include <string> #include <fstream> #include <iostream> int main() { std::string filename = "some_file"; std::fstream fs(filename, std::ios::in); std::cout << std::boolalpha; std::cout << "fs.is_open() = " << fs.is_open() << '\n'; if(!fs.is_open()) { fs.clear(); fs.open(filename, std::ios::out); std::cout << "fs.is_open() = " << fs.is_open() << '\n'; } } ``` Possible output: ``` fs.is_open() = false fs.is_open() = true ``` ### See also | | | | --- | --- | | [open](open "cpp/io/basic fstream/open") | opens a file and associates it with the stream (public member function) | | [close](close "cpp/io/basic fstream/close") | closes the associated file (public member function) |
programming_docs
cpp std::basic_osyncstream<CharT,Traits,Allocator>::~basic_osyncstream std::basic\_osyncstream<CharT,Traits,Allocator>::~basic\_osyncstream ==================================================================== | | | | | --- | --- | --- | | ``` ~basic_osyncstream(); ``` | | | Destroys a synchronized output stream. The destruction of the member `std::basic_syncbuf` will emit any buffered output not yet emitted. ### Parameters (none). ### Example ### See also | | | | --- | --- | | [(destructor)](../basic_syncbuf/~basic_syncbuf "cpp/io/basic syncbuf/~basic syncbuf") | destroys the basic\_syncbuf and emits its internal buffer (public member function of `std::basic_syncbuf<CharT,Traits,Allocator>`) | cpp std::basic_osyncstream<CharT,Traits,Allocator>::rdbuf std::basic\_osyncstream<CharT,Traits,Allocator>::rdbuf ====================================================== | | | | | --- | --- | --- | | ``` syncbuf_type* rdbuf() const noexcept; ``` | | | Returns a pointer to the underlying `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)`. ### Parameters (none). ### Example ### See also | | | | --- | --- | | [get\_wrapped](get_wrapped "cpp/io/basic osyncstream/get wrapped") | obtains a pointer to the final destination stream buffer (public member function) | | [rdbuf](../basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | cpp std::basic_osyncstream<CharT,Traits,Allocator>::get_wrapped std::basic\_osyncstream<CharT,Traits,Allocator>::get\_wrapped ============================================================= | | | | | --- | --- | --- | | ``` streambuf_type* get_wrapped() const noexcept; ``` | | | Returns a pointer to the wrapped `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")`, obtained by calling [`get_wrapped()`](../basic_syncbuf/get_wrapped "cpp/io/basic syncbuf/get wrapped") on the underlying `std::basic_syncbuf`. ### Parameters (none). ### Example wrapped buffer can be safely wrapped again in a different synchronized output stream. ``` #include <syncstream> #include <iostream> int main() { std::osyncstream bout1(std::cout); bout1 << "Hello, "; { std::osyncstream(bout1.get_wrapped()) << "Goodbye, " << "Planet!" << '\n'; } // emits the contents of the temporary buffer bout1 << "World!" << '\n'; } // emits the contents of bout1 ``` Output: ``` Goodbye, Planet! Hello, World! ``` ### See also | | | | --- | --- | | [(destructor)](~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function) | | [get\_wrapped](../basic_syncbuf/get_wrapped "cpp/io/basic syncbuf/get wrapped") | retrieves the wrapped streambuf pointer (public member function of `std::basic_syncbuf<CharT,Traits,Allocator>`) | cpp std::basic_osyncstream<CharT,Traits,Allocator>::emit std::basic\_osyncstream<CharT,Traits,Allocator>::emit ===================================================== | | | | | --- | --- | --- | | ``` void emit(); ``` | | | Emits all buffered output and executes any pending flushes, by calling [`emit()`](../basic_syncbuf/emit "cpp/io/basic syncbuf/emit") on the underlying [`std::basic_syncbuf`](../basic_syncbuf "cpp/io/basic syncbuf"). ### Parameters (none). ### Example ``` #include <syncstream> #include <iostream> int main() { { std::osyncstream bout(std::cout); bout << "Hello," << '\n'; // no flush bout.emit(); // characters transferred; cout not flushed bout << "World!" << std::endl; // flush noted; cout not flushed bout.emit(); // characters transferred; cout flushed bout << "Greetings." << '\n'; // no flush } // destructor calls emit(): characters transferred; cout not flushed // emit can be used for local exception-handling on the wrapped stream std::osyncstream bout(std::cout); bout << "Hello, " << "World!" << '\n'; try { bout.emit(); } catch (...) { // handle exceptions } } ``` Output: ``` Hello, World! Greetings. Hello, World! ``` ### See also | | | | --- | --- | | [(destructor)](~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function) | | [emit](../basic_syncbuf/emit "cpp/io/basic syncbuf/emit") | atomically transmits the entire internal buffer to the wrapped streambuf (public member function of `std::basic_syncbuf<CharT,Traits,Allocator>`) | cpp std::basic_osyncstream<CharT,Traits,Allocator>::basic_osyncstream std::basic\_osyncstream<CharT,Traits,Allocator>::basic\_osyncstream =================================================================== | | | | | --- | --- | --- | | ``` basic_osyncstream( streambuf_type* buf, const Allocator& a ); ``` | (1) | | | ``` explicit basic_osyncstream( streambuf_type* buf ); ``` | (2) | | | ``` basic_osyncstream( std::basic_ostream<CharT, Traits>& os, const Allocator& a ); ``` | (3) | | | ``` explicit basic_osyncstream( std::basic_ostream<CharT, Traits>& os ); ``` | (4) | | | ``` basic_osyncstream( std::basic_osyncstream&& other ) noexcept; ``` | (5) | | Constructs new synchronized output stream. 1-4) constructs the private member `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)` using the buffer and the allocator provided, and initializes the base class with a pointer to the member `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)`. 5) Move constructor. Move-constructs the `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)` base and the std::basic\_syncbuf member from the corresponding subobjects of `other`, then calls [`set_rdbuf`](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf") with the pointer to the newly-constructed underlying `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)` to complete the initialization of the base. After this move constructor, `other.get_wrapped()` returns `nullptr` and destruction of `other` produces no output. ### Parameters | | | | | --- | --- | --- | | buf | - | pointer to the `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` that will be wrapped | | os | - | reference to a `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`, whose rdbuf() will be wrapped | | a | - | the allocator to pass to the constructor of the member `std::basic_syncbuf` | | other | - | another osyncstream to move from | ### Example ``` #include <string_view> #include <syncstream> #include <iostream> #include <thread> void worker(const int id, std::ostream &os) { std::string_view block; switch (id) { default: [[fallthrough]]; case 0: block = "██"; break; case 1: block = "▓▓"; break; case 2: block = "▒▒"; break; case 3: block = "░░"; break; } for(int i = 1; i <= 50; ++i) { os << block << std::flush; } os << std::endl; } int main() { std::cout << "Synchronized output should not cause any interference:" << std::endl; { auto scout1 = std::osyncstream{std::cout}; auto scout2 = std::osyncstream{std::cout}; auto scout3 = std::osyncstream{std::cout}; auto scout4 = std::osyncstream{std::cout}; auto w1 = std::jthread{worker, 0, std::ref(scout1)}; auto w2 = std::jthread{worker, 1, std::ref(scout2)}; auto w3 = std::jthread{worker, 2, std::ref(scout3)}; auto w4 = std::jthread{worker, 3, std::ref(scout4)}; } std::cout << "\nLack of synchronization may cause some interference on output:" << std::endl; { auto w1 = std::jthread{worker, 0, std::ref(std::cout)}; auto w2 = std::jthread{worker, 1, std::ref(std::cout)}; auto w3 = std::jthread{worker, 2, std::ref(std::cout)}; auto w4 = std::jthread{worker, 3, std::ref(std::cout)}; } } ``` Possible output: ``` Synchronized output should not cause any interference: ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ████████████████████████████████████████████████████████████████████████████████████████████████████ Lack of synchronization may cause some interference on output: ████▓▓██▒▒▒▒▓▓██░░▒▒██░░▒▒░░░░▒▒░░▓▓▒▒██░░████████████▓▓██████▓▓▒▒▓▓██░░████▓▓▓▓██▒▒░░░░░░░░▓▓░░▓▓██▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▒▒▒▒░░▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒██░░░░░░░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████████▓▓▓▓▓▓▓▓▓▓▓▓░░▓▓▓▓ ▒▒▒▒██░░██████████████████████████░░░░░░░░░░░░░░██░░▒▒░░░░░░██████████████████ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒▒▒▒▒ ░░░░░░ ``` ### See also | | | | --- | --- | | [(constructor)](../basic_syncbuf/basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function of `std::basic_syncbuf<CharT,Traits,Allocator>`) | cpp std::basic_osyncstream<CharT,Traits,Allocator>::operator= std::basic\_osyncstream<CharT,Traits,Allocator>::operator= ========================================================== | | | | | --- | --- | --- | | ``` basic_osyncstream& operator=( std::basic_osyncstream&& other) noexcept; ``` | | | Move-assigns a synchronized output stream: Move-assigns the wrapped `std::basic_syncbuf` from the corresponding member of `other` (after this move-assignment, `other.get_wrapped()` returns a null pointer and destruction of `other` produces no output; any pending buffered output will be emitted) and [move-assigns](../basic_ostream/operator= "cpp/io/basic ostream/operator=") the base `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` (this swaps all stream state variables except for `rdbuf` between `*this` and `other`). ### Parameters | | | | | --- | --- | --- | | other | - | another osyncstream to move from | ### Example ### See also | | | | --- | --- | | [(constructor)](basic_osyncstream "cpp/io/basic osyncstream/basic osyncstream") | constructs a basic\_osyncstream (public member function) | | [(destructor)](~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function) | | [emit](emit "cpp/io/basic osyncstream/emit") | calls emit on the underlying basic\_syncbuf to transmit its internal data to the final destination (public member function) | cpp std::istrstream::rdbuf std::istrstream::rdbuf ====================== | | | | | --- | --- | --- | | ``` strstreambuf* rdbuf() const; ``` | | | Returns a pointer to the associated `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`, casting away its constness (despite the const qualifier on the member function). ### Parameters (none). ### Return value Pointer to the associated `std::strsteambuf`, with constness cast away. ### Example ``` #include <strstream> int main() { const std::istrstream buf("example"); std::strstreambuf* ptr = buf.rdbuf(); } ``` cpp std::istrstream::~istrstream std::istrstream::~istrstream ============================ | | | | | --- | --- | --- | | ``` virtual ~istrstream(); ``` | | | Destroys a `std::istrstream` object, which also destroys the member `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`. ### Parameters (none). ### Notes The constructors of `[std::istrstream](../istrstream "cpp/io/istrstream")` do not create the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` in dynamically allocated mode, so the memory leaks that are possible with `[std::ostrstream::~ostrstream](../ostrstream/~ostrstream "cpp/io/ostrstream/~ostrstream")` or `[std::strstream::~strstream](../strstream/~strstream "cpp/io/strstream/~strstream")` do not apply. ### Example ``` #include <strstream> #include <iostream> int main() { { std::istrstream s("1.234"); double d; s >> d; std::cout << d << '\n'; } // destructor called } ``` Output: ``` 1.234 ``` cpp std::istrstream::str std::istrstream::str ==================== | | | | | --- | --- | --- | | ``` char* str(); ``` | | | Returns the pointer to the beginning of the buffer, after freezing it. Effectively calls `rdbuf()->str()`. ### Parameters (none). ### Return value Pointer to the beginning of the buffer in the associated `std::strsteambuf` or a null pointer if no buffer is available. ### Example cpp std::istrstream::istrstream std::istrstream::istrstream =========================== | | | | | --- | --- | --- | | ``` explicit istrstream(const char* s); ``` | (1) | | | ``` explicit istrstream(char* s); ``` | (2) | | | ``` istrstream(const char* s, std::streamsize n); ``` | (3) | | | ``` istrstream(char* s, std::streamsize n); ``` | (4) | | Constructs new istrstream and its underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`. 1,2) Constructs the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` by calling `strstreambuf(s,0)` and initializes the base class with the address of the strstreambuf. The behavior is undefined if `s` is not pointing at an element of a null-terminated array. 3,4) Constructs the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` by calling `strstreambuf(s,n)` and initializes the base class with the address of the strstreambuf. The behavior is undefined if `s` is not pointing at an element of an array whose length is at least `n` elements. ### Parameters | | | | | --- | --- | --- | | s | - | C-string or char array to use as the contents of the stream | | n | - | size of the array | ### Example ``` #include <iostream> #include <strstream> int main() { std::istrstream s1("1 2 3"); // string literal int n1,n2,n3; if(s1 >> n1 >> n2 >> n3) std::cout << n1 << ", " << n2 << ", " << n3 << '\n'; char arr[] = {'4', ' ', '5', ' ', '6'}; std::istrstream s2(arr, sizeof arr); if(s2 >> n1 >> n2 >> n3) std::cout << n1 << ", " << n2 << ", " << n3 << '\n'; } ``` Output: ``` 1, 2, 3 4, 5, 6 ``` ### See also | | | | --- | --- | | [(constructor)](../strstreambuf/strstreambuf "cpp/io/strstreambuf/strstreambuf") | constructs a strstreambuf object (public member function of `std::strstreambuf`) | | [(constructor)](../ostrstream/ostrstream "cpp/io/ostrstream/ostrstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::ostrstream`) | | [(constructor)](../strstream/strstream "cpp/io/strstream/strstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::strstream`) | cpp std::basic_ispanstream<CharT,Traits>::rdbuf std::basic\_ispanstream<CharT,Traits>::rdbuf ============================================ | | | | | --- | --- | --- | | ``` std::basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; ``` | | (since C++23) | Returns pointer to the wrapped raw device object. ### Parameters (none). ### Return value Pointer to the wrapped raw device object. ### Example ### See also | | | | --- | --- | | [rdbuf](../basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | cpp std::basic_ispanstream<CharT,Traits>::basic_ispanstream std::basic\_ispanstream<CharT,Traits>::basic\_ispanstream ========================================================= | | | | | --- | --- | --- | | ``` explicit basic_ispanstream( std::span<CharT> s, std::ios_base::openmode mode = std::ios_base::in ); ``` | (1) | (since C++23) | | ``` template< class ROS > explicit basic_ispanstream( ROS&& r ); ``` | (2) | (since C++23) | | ``` basic_ispanstream( basic_ispanstream&& rhs ); ``` | (3) | (since C++23) | | ``` basic_ispanstream( const basic_ispanstream& ) = delete; ``` | (4) | (since C++23) | Constructs a new `basic_ispanstream`. 1) Uses the storage referenced by `s` as initial underlying buffer of the wrapped `std::basic_spanbuf` device. The wrapped `std::basic_spanbuf` object is constructed as `basic_spanbuf<Char, Traits>(s, mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 2) Uses the storage referenced by `r` after converted to `[std::span](http://en.cppreference.com/w/cpp/container/span)<const CharT>` as initial underlying buffer of the wrapped `std::basic_spanbuf` device. The wrapped `std::basic_spanbuf` object is opened in mode `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")`. This overload participates in overload resolution only if `ROS` models [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range"), `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<ROS, [std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>>` is `false`, and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<ROS, [std::span](http://en.cppreference.com/w/cpp/container/span)<const CharT>>` is `true`. 3) Move constructor. Move constructs the `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` base subobject and the wrapped `std::basic_spanbuf` from those of `rhs`, and then calls `[set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf")` with the address of the wrapped `std::basic_spanbuf` in `*this` to install it. 4) Copy constructor is deleted. `basic_ispanstream` is not copyable. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as initial underlying buffer of stream | | r | - | [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") to be use as initial underlying buffer of stream | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another `basic_ispanstream` to be moved from | ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [(constructor)](../basic_spanbuf/basic_spanbuf "cpp/io/basic spanbuf/basic spanbuf") (C++23) | constructs a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::basic_ispanstream<CharT,Traits>::swap std::basic\_ispanstream<CharT,Traits>::swap =========================================== | | | | | --- | --- | --- | | ``` void swap( basic_ispanstream& other ); ``` | | (since C++23) | Exchanges the state of the stream with those of `other`. This is done by calling `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>::swap(other)` and swapping the wrapped `std::basic_spanbuf` objects (accessible through `*rdbuf()`). ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](../basic_spanbuf/swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function of `std::basic_spanbuf<CharT,Traits>`) |
programming_docs
cpp std::swap(std::basic_ispanstream) std::swap(std::basic\_ispanstream) ================================== | Defined in header `[<spanstream>](../../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( std::basic_ispanstream<CharT, Traits>& lhs, std::basic_ispanstream<CharT, Traits>& rhs ); ``` | | (since C++23) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_ispanstream`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ispanstream/swap") (C++23) | swaps two `basic_ispanstream` objects (public member function) | cpp std::basic_ispanstream<CharT,Traits>::operator= std::basic\_ispanstream<CharT,Traits>::operator= ================================================ | | | | | --- | --- | --- | | ``` basic_ispanstream& operator=( basic_ispanstream&& other ); ``` | (1) | (since C++23) | | ``` basic_ispanstream& operator=( const basic_ispanstream& ) = delete; ``` | (2) | (since C++23) | 1) Move assigns the `other` to `*this`, effectively move-assigning both the `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` base class subobject and the wrapped `std::basic_spanbuf`. 2) Copy assignment operator is deleted. `basic_ispanstream` is not copy assignable. Note that move assignment operator of the base class swaps all stream state variables (except for [`rdbuf()`](rdbuf "cpp/io/basic ispanstream/rdbuf")) between `*this` and `other`. It is implementation-defined whether the `std::basic_spanbuf` wrapped in `other` still holds an underlying buffer after the move assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another stream to move from | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](../basic_spanbuf/operator= "cpp/io/basic spanbuf/operator=") (C++23) | assigns a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | | [operator=](../basic_istream/operator= "cpp/io/basic istream/operator=") (C++11) | move-assigns from another `basic_istream` (protected member function) | cpp std::basic_ispanstream<CharT,Traits>::span std::basic\_ispanstream<CharT,Traits>::span =========================================== | | | | | --- | --- | --- | | ``` std::span<const CharT> span() const noexcept; ``` | (1) | (since C++23) | | ``` void span( std::span<CharT> s ) noexcept; ``` | (2) | (since C++23) | | ``` template< class ROS > void span( ROS&& r ) noexcept; ``` | (3) | (since C++23) | 1) Gets a `span` referencing the written area if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode of the wrapped `std::basic_spanbuf`, or a `span` referencing the underlying buffer otherwise. 2) Makes the wrapped `std::basic_spanbuf` perform I/O on the buffer referenced by `s`. 3) Same as (2), except that `s` is obtained as if by `[std::span](http://en.cppreference.com/w/cpp/container/span)<const CharT> cs{[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<ROS>(r)}; [std::span](http://en.cppreference.com/w/cpp/container/span)<CharT> s{const\_cast<CharT\*>(cs.data()), cs.size()};` . This overload participates in overload resolution only if `ROS` models [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range"), `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<ROS, [std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>>` is `false`, and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<ROS, [std::span](http://en.cppreference.com/w/cpp/container/span)<const CharT>>` is `true`. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as the new underlying buffer of stream | | r | - | [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") to be use as the new underlying buffer of stream | ### Return value 1) A `std::span` referencing the underlying buffer or written area, depending on the open mode of the wrapped `std::basic_spanbuf`. 2-3) (none) ### Example ### See also | | | | --- | --- | | [span](../basic_spanbuf/span "cpp/io/basic spanbuf/span") (C++23) | obtains or initializes an underlying buffer according to mode (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::ostrstream::freeze std::ostrstream::freeze ======================= | | | | | --- | --- | --- | | ``` void freeze(bool flag = true); ``` | | | If the stream is using a dynamically-allocated array for output, disables (`flag == true`) or enables (`flag == false`) automatic allocation/deallocation of the buffer. Effectively calls `rdbuf()->freeze(flag)`. ### Notes After a call to `[str()](str "cpp/io/ostrstream/str")`, dynamic streams become frozen automatically. A call to `freeze(false)` is required before exiting the scope in which this `ostrstream` object was created. otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer. ### Parameters | | | | | --- | --- | --- | | flag | - | desired status | ### Return value (none). ### Example ``` #include <strstream> #include <iostream> int main() { std::ostrstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23; // note: no std::ends to demonstrate appending std::cout << "The output stream contains \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; // the stream is now frozen due to str() dyn << " More text"; // output to a frozen stream may be truncated std::cout << "The output stream contains \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; dyn.freeze(false); // freeze(false) must be called or the destructor will leak std::ostrstream dyn2; // dynamically-allocated output buffer dyn2 << "Test: " << 1.23; // note: no std::ends std::cout << "The output stream contains \""; std::cout.write(dyn2.str(), dyn2.pcount()) << "\"\n"; dyn2.freeze(false); // unfreeze the stream after str() dyn2 << " More text" << std::ends; // output will not be truncated (buffer grows) std::cout << "The output stream contains \"" << dyn2.str() << "\"\n"; dyn2.freeze(false); // freeze(false) must be called or the destructor will leak } ``` Possible output: ``` The output stream contains "Test: 1.23" The output stream contains "Test: 1.23 More " The output stream contains "Test: 1.23" The output stream contains "Test: 1.23 More text" ``` ### See also | | | | --- | --- | | [freeze](../strstreambuf/freeze "cpp/io/strstreambuf/freeze") | sets/clears the frozen state of the buffer (public member function of `std::strstreambuf`) | cpp std::ostrstream::rdbuf std::ostrstream::rdbuf ====================== | | | | | --- | --- | --- | | ``` strstreambuf* rdbuf() const; ``` | | | Returns a pointer to the associated `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`, casting away its constness (despite the const qualifier on the member function). ### Parameters (none). ### Return value Pointer to the associated `std::strsteambuf`, with constness cast away. ### Example ``` #include <strstream> int main() { const std::ostrstream buf; std::strstreambuf* ptr = buf.rdbuf(); } ``` cpp std::ostrstream::pcount std::ostrstream::pcount ======================= | | | | | --- | --- | --- | | ``` int pcount() const; ``` | | | Returns the number of characters that were output in the put area of the associated `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)`. Effectively calls `rdbuf()->pcount()`. ### Parameters (none). ### Return value The number of characters in the put area, or zero if nothing was output. ### Example ``` #include <strstream> #include <iostream> int main() { std::ostrstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23 << std::ends; std::cout << "The size of the output is " << dyn.pcount() << " and it holds \"" << dyn.str() << "\"\n"; dyn.freeze(false); char buf[10]; std::ostrstream user(buf, 10); // user-provided output buffer user << 1.23; // note: no std::ends std::cout.write(buf, user.pcount()); std::cout << '\n'; } ``` Output: ``` The size of the output is 11 and it holds "Test: 1.23" 1.23 ``` ### See also | | | | --- | --- | | [pcount](../strstreambuf/pcount "cpp/io/strstreambuf/pcount") | returns the next pointer minus the beginning pointer in the output sequence: the number of characters written (public member function of `std::strstreambuf`) | cpp std::ostrstream::ostrstream std::ostrstream::ostrstream =========================== | | | | | --- | --- | --- | | ``` ostrstream(); ``` | (1) | | | ``` ostrstream(char* s, int n, std::ios_base::openmode mode = std::ios_base::out); ``` | (2) | | Constructs new output strstream and its underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`. 1) Default-constructs the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`, which creates a dynamically growing buffer, and initializes the base class with the address of the strstreambuf member. 2) Initialized the base class with the address of the underlying `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` member, which is initialized in one of the two possible ways, both of which write to user-provided fixed-size array: a) if the `app` bit is not set in `mode`, constructs the buffer by calling `strstreambuf(s, n, s)`. The behavior is undefined if there are less than `n` elements in the array whose first element is pointed to by `s` b) if the `app` bit is set in `mode`, constructs the buffer by calling `strstreambuf(s, n, s + [std::strlen](http://en.cppreference.com/w/cpp/string/byte/strlen)(s))`. The behavior is undefined if there are less than `n` elements in the array whose first element is pointed to by `s` or if the array does not contain a valid null-terminated character sequence. ### Parameters | | | | | --- | --- | --- | | s | - | char array to use as the output buffer | | n | - | size of the array to be used as the output buffer | | mode | - | specifies stream open mode. It is a bitmask type, the following constants are defined (although only `app` is used): | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Example ``` #include <iostream> #include <strstream> int main() { std::ostrstream s1; // dynamic buffer s1 << 1 << ' ' << 3.14 << " example\n" << std::ends; std::cout << s1.str(); s1.freeze(false); char arr[15] = "Hello"; std::ostrstream s2(arr, sizeof arr, std::ios_base::app); s2 << ", world!" << std::ends; std::cout << s2.str() << '\n'; std::cout << arr << '\n'; // streams use the provided arrays } ``` Output: ``` 1 3.14 example Hello, world! Hello, world! ``` ### See also | | | | --- | --- | | [(constructor)](../strstreambuf/strstreambuf "cpp/io/strstreambuf/strstreambuf") | constructs a strstreambuf object (public member function of `std::strstreambuf`) | | [(constructor)](../istrstream/istrstream "cpp/io/istrstream/istrstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::istrstream`) | | [(constructor)](../strstream/strstream "cpp/io/strstream/strstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::strstream`) | cpp std::ostrstream::str std::ostrstream::str ==================== | | | | | --- | --- | --- | | ``` char* str(); ``` | | | Returns the pointer to the beginning of the buffer, after freezing it. Effectively calls `rdbuf()->str()`. ### Parameters (none). ### Return value Pointer to the beginning of the buffer in the associated `std::strsteambuf` or a null pointer if no buffer is available. ### Notes Before a call to `str()` that uses the result as a C string, the stream buffer must be null-terminated. Regular output such as with `stream << 1.2` does not store a null terminator, it must be appended explicitly, typically with the manipulator `[std::ends](../manip/ends "cpp/io/manip/ends")`. After a call to `str()`, dynamic streams become frozen. A call to `freeze(false)` is required before exiting the scope in which this `ostrstream` object was created. otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer, which may leave the buffer not null-terminated. ### Example ``` #include <strstream> #include <iostream> int main() { std::ostrstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23; // not adding std::ends to demonstrate append behavior std::cout << "The output stream holds \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; // the stream is now frozen due to str() dyn << " More text" << std::ends; std::cout << "The output stream holds \""; std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; dyn.freeze(false); } ``` Possible output: ``` The stream holds "Test: 1.23" The stream holds "Test: 1.23 More " ``` ### See also | | | | --- | --- | | [str](../strstreambuf/str "cpp/io/strstreambuf/str") | marks the buffer frozen and returns the beginning pointer of the input sequence (public member function of `std::strstreambuf`) | cpp std::ostrstream::~ostrstream std::ostrstream::~ostrstream ============================ | | | | | --- | --- | --- | | ``` virtual ~ostrstream(); ``` | | | Destroys a `std::ostrstream` object, which also destroys the member `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`, which may call the deallocation function if the underlying buffer was dynamically-allocated and not frozen. ### Parameters (none). ### Notes If `[str()](str "cpp/io/ostrstream/str")` was called on a dynamic ostrstream and [freeze(false)](freeze "cpp/io/ostrstream/freeze") was not called after that, this destructor leaks memory. ### Example ``` #include <strstream> #include <iostream> int main() { { std::ostrstream s; // dynamic buffer s << 1.23; std::cout << s.str() << '\n'; s.freeze(false); } // destructor called, buffer deallocated { std::ostrstream s; s << 1.23; std::cout << s.str() << '\n'; // buf.freeze(false); } // destructor called, memory leaked } ``` Output: ``` 1.23 1.23 ``` cpp std::fpos<State>::state std::fpos<State>::state ======================= | | | | | --- | --- | --- | | ``` State state() const; ``` | (1) | | | ``` void state( State st ); ``` | (2) | | Manages the file position state. 1) Returns the value of the file position state 2) Replaces the file position state with the value of `st`. For the specializations of `[std::fpos](../fpos "cpp/io/fpos")` that are used in the standard library, `State` is always `[std::mbstate\_t](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t")`. ### Parameters | | | | | --- | --- | --- | | st | - | new value for the state | ### Return value 1) the current value of the fpos state 2) (none) ### Example ``` #include <iostream> #include <sstream> #include <cwchar> int main() { std::istringstream s("test"); std::mbstate_t st = s.tellg().state(); if(std::mbsinit(&st)) std::cout << "The stream is in the initial shift state\n"; } ``` Output: ``` The stream is in the initial shift state ``` ### See also | | | | --- | --- | | [mbstate\_t](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) | cpp std::make_error_code(std::io_errc) std::make\_error\_code(std::io\_errc) ===================================== | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::error_code make_error_code( std::io_errc e ) noexcept; ``` | | (since C++11) | Constructs an `[std::error\_code](../../error/error_code "cpp/error/error code")` object from a value of type `[std::io\_errc](../io_errc "cpp/io/io errc")` as if by `return [std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)(static\_cast<int>(e), [std::iostream\_category](http://en.cppreference.com/w/cpp/io/iostream_category)())`. This function is called by the constructor of `[std::error\_code](../../error/error_code "cpp/error/error code")` when given an `[std::io\_errc](../io_errc "cpp/io/io errc")` argument. ### Parameters | | | | | --- | --- | --- | | e | - | error code number | ### Return value A value of type `[std::error\_code](../../error/error_code "cpp/error/error code")` that holds the error code number from `e` associated with the error category `"iostream"`. ### Example ``` #include <iostream> #include <system_error> int main() { std::error_code ec = std::make_error_code(std::io_errc::stream); // This works because of the overloaded method // and the is_error_code_enum specialization. ec = std::io_errc::stream; std::cout << "Error code from io_errc::stream has category " << ec.category().name() << '\n'; } ``` Output: ``` Error code from io_errc::stream has category iostream ``` ### See also | | | | --- | --- | | [error\_code](../../error/error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [io\_errc](../io_errc "cpp/io/io errc") (C++11) | the IO stream error codes (enum) | | [make\_error\_code(std::errc)](../../error/errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `[std::errc](../../error/errc "cpp/error/errc")` error code (function) | | [make\_error\_code(std::future\_errc)](../../thread/future_errc/make_error_code "cpp/thread/future errc/make error code") (C++11) | constructs a future error code (function) | cpp std::make_error_condition(std::io_errc) std::make\_error\_condition(std::io\_errc) ========================================== | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::error_condition make_error_condition( std::io_errc e ) noexcept; ``` | | (since C++11) | Constructs an `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` object from a value of type `[std::io\_errc](../io_errc "cpp/io/io errc")` as if by `return [std::error\_condition](http://en.cppreference.com/w/cpp/error/error_condition)(static\_cast<int>(e), [std::iostream\_category](http://en.cppreference.com/w/cpp/io/iostream_category)())`. ### Parameters | | | | | --- | --- | --- | | e | - | error code number | ### Return value A value of type `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` that holds the error code number from `e` associated with the error category `"iostream"`. ### Example ``` #include <iostream> #include <system_error> #include <string> int main() { std::error_condition ec = std::make_error_condition(std::io_errc::stream); std::cout << "error condition for io_errc::stream has value " << ec.value() << "\nand message \"" << ec.message() << "\"\n"; } ``` Output: ``` error condition for io_errc::stream has value 1 and message "unspecified iostream_category error" ``` ### See also | | | | --- | --- | | [error\_condition](../../error/error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [io\_errc](../io_errc "cpp/io/io errc") (C++11) | the IO stream error codes (enum) |
programming_docs
cpp std::basic_iostream<CharT,Traits>::swap std::basic\_iostream<CharT,Traits>::swap ======================================== | | | | | --- | --- | --- | | ``` protected: void swap( basic_iostream& other ); ``` | | (since C++11) | Exchanges the state with another input/output stream object. Effectively calls `basic_istream<CharT,Traits>::swap(other)`. This member function is protected: it is called by the swap member functions of the derived stream classes `[std::basic\_stringstream](../basic_stringstream "cpp/io/basic stringstream")` and `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`, which know how to correctly swap the associated stream buffers. ### Parameters | | | | | --- | --- | --- | | other | - | another stream to exchange the state with | ### Return value `*this`. cpp std::basic_iostream<CharT,Traits>::basic_iostream std::basic\_iostream<CharT,Traits>::basic\_iostream =================================================== | | | | | --- | --- | --- | | ``` explicit basic_iostream( std::basic_streambuf<CharT,Traits>* sb ); ``` | (1) | | | ``` basic_iostream( const basic_iostream& other ) = delete; ``` | (2) | (since C++11) | | ``` protected: basic_iostream( basic_iostream&& other ); ``` | (3) | (since C++11) | Constructs new stream object. 1) Initializes with streambuf `sb`. The base classes are initialized as `basic_istream<CharT,Traits>(sb)` and `basic_ostream<CharT,Traits>(sb)`. After the call `rdbuf() == sb` and `gcount() == 0`. 2) Copy construction is not allowed. 3) Move constructor: move-constructs the first base class `basic_istream` as `basic_istream<CharT,Traits>(std::move(rhs));`, which in turn move-constructs and initializes the virtual base `[std::basic\_ios](../basic_ios "cpp/io/basic ios")`. The initialization of the other base, `basic_ostream`, is implementation-defined (e.g., a protected default constructor may be added to `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`, which does nothing) because move-construction cannot use `rhs` twice. This move constructor is protected: it is called by the move constructors of the derived stream classes `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")` and `[std::basic\_stringstream](../basic_stringstream "cpp/io/basic stringstream")` before they move-construct and associate the stream buffer. ### Parameters | | | | | --- | --- | --- | | sb | - | streambuf to initialize with | | other | - | another stream to initialize with | ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic iostream/operator=") (C++11) | move-assigns another `basic_iostream` (protected member function) | cpp std::basic_iostream<CharT,Traits>::~basic_iostream std::basic\_iostream<CharT,Traits>::~basic\_iostream ==================================================== | | | | | --- | --- | --- | | ``` virtual ~basic_iostream(); ``` | | | Destructs the input/output stream. ### Notes This destructor does not perform any operation on the underlying stream buffer (`rdbuf()`): the destructors of the derived streams such as `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")` and `[std::basic\_stringstream](../basic_stringstream "cpp/io/basic stringstream")` are responsible for calling the destructors of the stream buffers. cpp std::basic_iostream<CharT,Traits>::operator= std::basic\_iostream<CharT,Traits>::operator= ============================================= | | | | | --- | --- | --- | | ``` basic_iostream& operator=( const basic_iostream& other ) = delete; ``` | (1) | | | ``` protected: basic_iostream& operator=( basic_iostream&& other ); ``` | (2) | (since C++11) | Assigns another stream object. 1) Copy assignment is not allowed. 2) Move assigns another stream object. Effectively calls `swap(rhs)`. This move assignment operator is protected: it is called by the move assignment operators of the derived stream classes `[std::basic\_stringstream](../basic_stringstream "cpp/io/basic stringstream")` and `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")` which know how to properly move-assign the associated stream buffers. ### Parameters | | | | | --- | --- | --- | | other | - | another stream to assign state of | ### Return value `*this`. ### See also | | | | --- | --- | | [(constructor)](basic_iostream "cpp/io/basic iostream/basic iostream") | constructs the object (public member function) | cpp std::get_money std::get\_money =============== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class MoneyT > /*unspecified*/ get_money( MoneyT& mon, bool intl = false ); ``` | | (since C++11) | When used in an expression `in >> get_money(mon, intl)`, parses the character input as a monetary value, as specified by the `[std::money\_get](../../locale/money_get "cpp/locale/money get")` facet of the locale currently imbued in `in`, and stores the value in `mon`. The extraction operation in `in >> get_money(mon, intl)` behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). ### Parameters | | | | | --- | --- | --- | | mon | - | variable where monetary value will be written. Can be either `long double` or `basic_string` | | intl | - | expects to find required international currency strings if `true`, expects optional currency symbols otherwise | ### Return value Returns an object of unspecified type such that if `in` is the name of an input stream of type `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `in >> get_money(mon, intl)` behaves as if the following code was executed: `typedef [std::istreambuf\_iterator](http://en.cppreference.com/w/cpp/iterator/istreambuf_iterator)<CharT, Traits> Iter; typedef [std::money\_get](http://en.cppreference.com/w/cpp/locale/money_get)<CharT, Iter> MoneyGet; [std::ios\_base::iostate](http://en.cppreference.com/w/cpp/io/ios_base/iostate) err = [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate); const MoneyGet &mg = [std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<MoneyGet>(in.getloc()); mg.get(Iter(in.rdbuf()), Iter(), intl, in, err, mon); if ([std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate) != err) out.setstate(err);` ### Example ``` #include <iostream> #include <sstream> #include <locale> #include <iomanip> int main() { std::istringstream in("$1,234.56 2.22 USD 3.33"); long double v1, v2; std::string v3; in.imbue(std::locale("en_US.UTF-8")); in >> std::get_money(v1) >> std::get_money(v2) >> std::get_money(v3, true); if (in) { std::cout << std::quoted(in.str()) << " parsed as: " << v1 << ", " << v2 << ", " << v3 << '\n'; } else { std::cout << "Parse failed"; } } ``` Output: ``` "$1,234.56 2.22 USD 3.33" parsed as: 123456, 222, 333 ``` ### See also | | | | --- | --- | | [money\_get](../../locale/money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) | | [put\_money](put_money "cpp/io/manip/put money") (C++11) | formats and outputs a monetary value (function template) | cpp std::ends std::ends ========= | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& ends( std::basic_ostream<CharT, Traits>& os ); ``` | | | Inserts a null character into the output sequence `os` as if by calling `os.put(CharT())`. This is an output-only I/O manipulator, it may be called with an expression such as `out << std::ends` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`. ### Notes This manipulator is typically used with `[std::ostrstream](http://en.cppreference.com/w/cpp/io/ostrstream)`, when the associated output buffer needs to be null-terminated to be processed as a C string. Unlike `[std::endl](endl "cpp/io/manip/endl")`, this manipulator does not flush the stream. ### Parameters | | | | | --- | --- | --- | | os | - | reference to output stream | ### Return value `os` (reference to the stream after insertion of the null character). ### Example ``` #include <cstdio> #include <strstream> int main() { std::ostrstream oss; oss << "Sample text: " << 42 << std::ends; std::printf("%s\n", oss.str()); oss.freeze(false); // enable memory deallocation } ``` Output: ``` Sample text: 42 ``` ### See also | | | | --- | --- | | [ostrstream](../ostrstream "cpp/io/ostrstream") (deprecated in C++98) | implements character array output operations (class) | cpp std::setbase std::setbase ============ | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` /*unspecified*/ setbase( int base ); ``` | | | Sets the numeric base of the stream. When used in an expression `out << setbase(base)` or `in >> setbase(base)`, changes the `basefield` flag of the stream `out` or `in`, depending on the value of `base`: * the value `16` sets `basefield` to `[std::ios\_base::hex](../ios_base/fmtflags "cpp/io/ios base/fmtflags")` * the value `8` sets `[std::ios\_base::oct](../ios_base/fmtflags "cpp/io/ios base/fmtflags")` * the value `10` sets `[std::ios\_base::dec](../ios_base/fmtflags "cpp/io/ios base/fmtflags")`. Values of `base` other than 8, 10, or 16 reset `basefield` to zero, which corresponds to decimal output and prefix-dependent input. ### Parameters | | | | | --- | --- | --- | | base | - | new value for basefield | ### Return value Returns an object of unspecified type such that if `str` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` or `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `str << setbase(base)` or `str >> setbase(base)` behaves as if the following code was executed: ``` str.setf(base == 8 ? std::ios_base::oct : base == 10 ? std::ios_base::dec : base == 16 ? std::ios_base::hex : std::ios_base::fmtflags(0), std::ios_base::basefield); ``` ### Example ``` #include <iostream> #include <sstream> #include <iomanip> int main() { std::cout << "Parsing string \"10 0x10 010\"\n"; int n1, n2, n3; std::istringstream s("10 0x10 010"); s >> std::setbase(16) >> n1 >> n2 >> n3; std::cout << "hexadecimal parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; s.clear(); s.seekg(0); s >> std::setbase(0) >> n1 >> n2 >> n3; std::cout << "prefix-dependent parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; std::cout << "hex output: " << std::setbase(16) << std::showbase << n1 << ' ' << n2 << ' ' << n3 << '\n'; } ``` Output: ``` Parsing string "10 0x10 010" hexadecimal parse: 16 16 16 prefix-dependent parse: 10 16 8 hex output: 0xa 0x10 0x8 ``` ### See also | | | | --- | --- | | [dechexoct](hex "cpp/io/manip/hex") | changes the base used for integer I/O (function) | | [showbasenoshowbase](showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | cpp std::showpoint, std::noshowpoint std::showpoint, std::noshowpoint ================================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& showpoint( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& noshowpoint( std::ios_base& str ); ``` | (2) | | Enables or disables the unconditional inclusion of the decimal point character in floating-point output. Has no effect on input. 1) enables the `showpoint` flag in the stream `str` as if by calling `str.setf([std::ios\_base::showpoint](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` 2) disables the `showpoint` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::showpoint](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` This is an I/O manipulator, it may be called with an expression such as `out << std::showpoint` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::showpoint` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. The character to use as decimal point character is determined by the numpunct facet of the locale imbued in the stream at the time of output, as described in `[std::num\_put::put](../../locale/num_put/put "cpp/locale/num put/put")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> int main() { std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n' << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n'; } ``` Output: ``` 1.0 with showpoint: 1.00000 1.0 with noshowpoint: 1 ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | cpp std::showbase, std::noshowbase std::showbase, std::noshowbase ============================== | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& showbase( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& noshowbase( std::ios_base& str ); ``` | (2) | | 1) enables the `showbase` flag in the stream `str` as if by calling `str.setf([std::ios\_base::showbase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) disables the `showbase` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::showbase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This is an I/O manipulator, it may be called with an expression such as `out << std::showbase` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::showbase` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. The `showbase` flag affects the behavior of integer output (see `[std::num\_put::put](../../locale/num_put/put "cpp/locale/num put/put")`), monetary input (see `[std::money\_get::get](../../locale/money_get/get "cpp/locale/money get/get")`) and monetary output (see `[std::money\_put::put](../../locale/money_put/put "cpp/locale/money put/put")`). ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Notes As specifed in `[std::num\_put::put](../../locale/num_put/put "cpp/locale/num put/put")`, the showbase flag in integer output acts like the # format specifier in `[std::printf](../c/fprintf "cpp/io/c/fprintf")`, which means the numeric base prefix is *not* added when outputting the value zero. ### Example ``` #include <sstream> #include <locale> #include <iostream> #include <iomanip> int main() { // showbase affects the output of octals and hexadecimals std::cout << std::hex << "showbase: " << std::showbase << 42 << '\n' << "noshowbase: " << std::noshowbase << 42 << '\n'; // and both input and output of monetary values std::locale::global(std::locale("en_US.utf8")); long double val = 0; std::istringstream is("3.14"); is >> std::showbase >> std::get_money(val); std::cout << "With showbase, parsing 3.14 as money gives " << val << '\n'; is.seekg(0); is >> std::noshowbase >> std::get_money(val); std::cout << "Without showbase, parsing 3.14 as money gives " << val << '\n'; } ``` Output: ``` showbase: 0x2a noshowbase: 2a With showbase, parsing 3.14 as money gives 0 Without showbase, parsing 3.14 as money gives 314 ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | cpp std::setfill std::setfill ============ | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class CharT > /*unspecified*/ setfill( CharT c ); ``` | | | When used in an expression `out << setfill(c)` sets the fill character of the stream `out` to `c`. ### Parameters | | | | | --- | --- | --- | | c | - | new value for the fill character | ### Return value Returns an object of unspecified type such that if `out` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>`, then the expression `out << setfill(n)` behaves as if the following code was executed: `out.fill(n);` ### Notes The current fill character may be obtained with `[std::ostream::fill](../basic_ios/fill "cpp/io/basic ios/fill")`. ### Example ``` #include <iostream> #include <iomanip> int main() { std::cout << "default fill: [" << std::setw(10) << 42 << "]\n" << "setfill('*'): [" << std::setfill('*') << std::setw(10) << 42 << "]\n"; } ``` Output: ``` default fill: [ 42] setfill('*'): [********42] ``` ### See also | | | | --- | --- | | [fill](../basic_ios/fill "cpp/io/basic ios/fill") | manages the fill character (public member function of `std::basic_ios<CharT,Traits>`) | | [internalleftright](left "cpp/io/manip/left") | sets the placement of fill characters (function) | | [setw](setw "cpp/io/manip/setw") | changes the width of the next input/output field (function) | cpp std::endl std::endl ========= | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os ); ``` | | | Inserts a newline character into the output sequence `os` and flushes it as if by calling `os.put(os.widen('\n'))` followed by `os.flush()`. This is an output-only I/O manipulator, it may be called with an expression such as `out << std::endl` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`. ### Notes This manipulator may be used to produce a line of output immediately, e.g. when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly. An explicit flush of `[std::cout](../cout "cpp/io/cout")` is also necessary before a call to `[std::system](../../utility/program/system "cpp/utility/program/system")`, if the spawned process performs any screen I/O. In most other usual interactive I/O scenarios, `std::endl` is redundant when used with `[std::cout](../cout "cpp/io/cout")` because any input from `[std::cin](../cin "cpp/io/cin")`, output to `[std::cerr](../cerr "cpp/io/cerr")`, or program termination forces a call to `[std::cout](http://en.cppreference.com/w/cpp/io/cout).flush()`. Use of `std::endl` in place of `'\n'`, encouraged by some sources, may significantly degrade output performance. In many implementations, standard output is line-buffered, and writing `'\n'` causes a flush anyway, unless `std::ios::sync_with_stdio(false)` was executed. In those situations, unnecessary `endl` only degrades the performance of file output, not standard output. The code samples on this wiki [follow Bjarne Stroustrup](http://www.stroustrup.com/3rd_code.html) and [The C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-endl) in flushing the standard output only where necessary. When an incomplete line of output needs to be flushed, the `[std::flush](flush "cpp/io/manip/flush")` manipulator may be used. When every character of output needs to be flushed, the `[std::unitbuf](unitbuf "cpp/io/manip/unitbuf")` manipulator may be used. ### Parameters | | | | | --- | --- | --- | | os | - | reference to output stream | ### Return value `os` (reference to the stream after manipulation). ### Example With \n instead of endl, the output would be the same, but may not appear in real time. ``` #include <iostream> #include <chrono> template<typename Diff> void log_progress(Diff d) { std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d).count() << " ms passed" << std::endl; } int main() { std::cout.sync_with_stdio(false); // on some platforms, stdout flushes on \n volatile int sink = 0; auto t1 = std::chrono::high_resolution_clock::now(); for (int j=0; j<5; ++j) { for (int n=0; n<10000; ++n) for (int m=0; m<20000; ++m) sink += m*n; // do some work auto now = std::chrono::high_resolution_clock::now(); log_progress(now - t1); } } ``` Possible output: ``` 487 ms passed 974 ms passed 1470 ms passed 1965 ms passed 2455 ms passed ``` ### See also | | | | --- | --- | | [unitbufnounitbuf](unitbuf "cpp/io/manip/unitbuf") | controls whether output is flushed after each operation (function) | | [flush](flush "cpp/io/manip/flush") | flushes the output stream (function template) | | [flush](../basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) |
programming_docs
cpp std::flush_emit std::flush\_emit ================ | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& flush_emit( std::basic_ostream<CharT, Traits>& os ); ``` | | (since C++20) | Flushes the output sequence `os` as if by calling `os.flush()`. Then, if `os.rdbuf()` actually points to a `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)<CharT, Traits, Allocator>` `buf`, calls `buf.emit()`. This is an output-only I/O manipulator, it may be called with an expression such as `out << std::flush_emit` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`. ### Parameters | | | | | --- | --- | --- | | os | - | reference to output stream | ### Return value `os` (reference to the stream after manipulation). ### Example ### See also | | | | --- | --- | | [flush](../basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::dec, std::hex, std::oct std::dec, std::hex, std::oct ============================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& dec( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& hex( std::ios_base& str ); ``` | (2) | | | ``` std::ios_base& oct( std::ios_base& str ); ``` | (3) | | Modifies the default numeric base for integer I/O. 1) sets the `basefield` of the stream `str` to `dec` as if by calling `str.setf([std::ios\_base::dec](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::basefield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) sets the `basefield` of the stream `str` to `hex` as if by calling `str.setf([std::ios\_base::hex](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::basefield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 3) sets the `basefield` of the stream `str` to `oct` as if by calling `str.setf([std::ios\_base::oct](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::basefield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This is an I/O manipulator. It may be called with an expression such as `out << std::hex` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::hex` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> #include <sstream> #include <bitset> int main() { std::cout << "The number 42 in octal: " << std::oct << 42 << '\n' << "The number 42 in decimal: " << std::dec << 42 << '\n' << "The number 42 in hex: " << std::hex << 42 << '\n'; int n; std::istringstream("2A") >> std::hex >> n; std::cout << std::dec << "Parsing \"2A\" as hex gives " << n << '\n'; // the output base is sticky until changed std::cout << std::hex << "42 as hex gives " << 42 << " and 21 as hex gives " << 21 << '\n'; // Note: there is no I/O manipulator that sets up a stream to print out // numbers in binary format (e.g. bin). If binary output is necessary // the std::bitset trick can be used: std::cout << "The number 42 in binary: " << std::bitset<8>{42} << '\n'; } ``` Output: ``` The number 42 in octal: 52 The number 42 in decimal: 42 The number 42 in hex: 2a Parsing "2A" as hex gives 42 42 as hex gives 2a and 21 as hex gives 15 The number 42 in binary: 00101010 ``` ### See also | | | | --- | --- | | [setbase](setbase "cpp/io/manip/setbase") | changes the base used for integer I/O (function) | | [showbasenoshowbase](showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | cpp std::quoted std::quoted =========== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class CharT > /*unspecified*/ quoted( const CharT* s, CharT delim=CharT('"'), CharT escape=CharT('\\') ); ``` | (1) | (since C++14) | | ``` template< class CharT, class Traits, class Allocator > /*unspecified*/ quoted( const std::basic_string<CharT, Traits, Allocator>& s, CharT delim=CharT('"'), CharT escape=CharT('\\') ); ``` | (2) | (since C++14) | | ``` template< class CharT, class Traits> /*unspecified*/ quoted( std::basic_string_view<CharT, Traits> s, CharT delim=CharT('"'), CharT escape=CharT('\\') ); ``` | (3) | (since C++17) | | ``` template< class CharT, class Traits, class Allocator > /*unspecified*/ quoted( std::basic_string<CharT, Traits, Allocator>& s, CharT delim=CharT('"'), CharT escape=CharT('\\') ); ``` | (4) | (since C++14) | Allows insertion and extraction of quoted strings, such as the ones found in CSV or XML. When used in an expression `out << quoted(s, delim, escape)`, where `out` is an output stream with `char_type` equal to `CharT` and, for overloads 2-4, `traits_type` equal to `Traits`, behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"), which inserts into `out` a sequence of characters `seq` constructed as follows: a) First, the character `delim` is added to the sequence b) Then every character from `s`, except if the next character to output equals `delim` or equals `escape` (as determined by the stream's `traits_type::eq`), then first appends an extra copy of `escape` c) In the end, `delim` is appended to `seq` once more Then, if `seq.size() < out.width()`, adds `out.width()-seq.size()` copies of the fill character `out.fill()` either at the end of the sequence (if `ios_base::left` is set in `out.flags()`) or at the beginning of the sequence (in all other cases). Finally, outputs each character from the resulting sequence as if by calling `out.rdbuf()->sputn(seq, n)`, where `n=[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(out.width(), seq.size())` and `out.width(0)` to cancel the effects of `[std::setw](setw "cpp/io/manip/setw")`, if any. 4) When used in an expression `in >> quoted(s, delim, escape)`, where `in` is an input stream with `char_type` equal to `CharT` and `traits_type` equal to `Traits`, extracts characters from `in`, using `[std::basic\_istream::operator>>](../basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt")`, according to the following rules: a) If the first character extracted does not equal `delim` (as determined by the stream's `traits_type::eq`), then simply performs `in >> s`. b) Otherwise (if the first character is the delimiter): 1) Turns off the `skipws` flag on the input stream 2) Empties the destination string by calling `s.clear()` 3) Extracts characters from `in` and appends them to `s`, except that whenever an `escape` character is extracted, it is ignored and the next character is appended to `s`. Extraction stops when `!in == true` or when an unescaped `delim` character is found. 4) Discards the final (unescaped) `delim` character. 5) Restores the `skipws` flag on the input stream to its original value. ### Parameters | | | | | --- | --- | --- | | s | - | the string to insert or extract | | delim | - | the character to use as the delimiter, defaults to `"` | | escape | - | the character to use as the escape character, defaults to `\` | ### Return value Returns an object of unspecified type such that the described behavior takes place. ### Exceptions Throws `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` if `operator>>` or `operator<<` throws. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_quoted_string_io`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <iomanip> #include <sstream> void default_delimiter() { const std::string in = "std::quoted() quotes this string and embedded \"quotes\" too"; std::stringstream ss; ss << std::quoted(in); std::string out; ss >> std::quoted(out); std::cout << "Default delimiter case:\n" "read in [" << in << "]\n" "stored as [" << ss.str() << "]\n" "written out [" << out << "]\n\n"; } void custom_delimiter() { const char delim {'$'}; const char escape {'%'}; const std::string in = "std::quoted() quotes this string and embedded $quotes$ $too"; std::stringstream ss; ss << std::quoted(in, delim, escape); std::string out; ss >> std::quoted(out, delim, escape); std::cout << "Custom delimiter case:\n" "read in [" << in << "]\n" "stored as [" << ss.str() << "]\n" "written out [" << out << "]\n\n"; } int main() { default_delimiter(); custom_delimiter(); } ``` Output: ``` Default delimiter case: read in [std::quoted() quotes this string and embedded "quotes" too] stored as ["std::quoted() quotes this string and embedded \"quotes\" too"] written out [std::quoted() quotes this string and embedded "quotes" too] Custom delimiter case: read in [std::quoted() quotes this string and embedded $quotes$ $too] stored as [$std::quoted() quotes this string and embedded %$quotes%$ %$too$] written out [std::quoted() quotes this string and embedded $quotes$ $too] ``` ### See also cpp std::unitbuf, std::nounitbuf std::unitbuf, std::nounitbuf ============================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& unitbuf( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& nounitbuf( std::ios_base& str ); ``` | (2) | | Enables or disables automatic flushing of the output stream after any output operation. Has no effect on input. 1) enables the `unitbuf` flag in the stream `str` as if by calling `str.setf([std::ios\_base::unitbuf](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) disables the `unitbuf` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::unitbuf](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This is an I/O manipulator, it may be called with an expression such as `out << std::unitbuf` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::unitbuf` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Notes Flushing is performed in the destructor of the `[std::basic\_ostream::sentry](../basic_ostream/sentry "cpp/io/basic ostream/sentry")` object, which calls `str.rdbuf()->pubsync()` if `str.flags() & [std::ios\_base::unitbuf](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)` is `true`. The standard output objects `[std::cerr](../cerr "cpp/io/cerr")` and `[std::wcerr](../cerr "cpp/io/cerr")` have their `unitbuf` bit set by default. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example Without std::unitbuf or another explicit flush, the output is the same, but does not appear in real time. ``` #include <iostream> #include <chrono> template<typename Diff> void log_progress(Diff d) { std::cout << "..(" << std::chrono::duration_cast<std::chrono::milliseconds>(d).count() << " ms).."; } int main() { volatile int sink = 0; std::cout << std::unitbuf; // enable automatic flushing auto t1 = std::chrono::high_resolution_clock::now(); for (int j = 0; j < 5; ++j) { for (int n = 0; n < 10000; ++n) for (int m = 0; m < 20000; ++m) sink += m * n; // do some work auto now = std::chrono::high_resolution_clock::now(); log_progress(now - t1); } std::cout << '\n'; } ``` Output: ``` ..(450 ms)....(902 ms)....(1352 ms)....(1802 ms)....(2252 ms).. ``` ### See also | | | | --- | --- | | [flush](flush "cpp/io/manip/flush") | flushes the output stream (function template) | | [endl](endl "cpp/io/manip/endl") | outputs `'\n'` and flushes the output stream (function template) | cpp std::resetiosflags std::resetiosflags ================== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` /*unspecified*/ resetiosflags( std::ios_base::fmtflags mask ); ``` | | | When used in an expression `out << resetiosflags(mask)` or `in >> resetiosflags(mask)`, clears all format flags of the stream `out` or `in` as specified by the `mask`. ### Parameters | | | | | --- | --- | --- | | mask | - | bitmask of the flags to clear | ### Return value Returns an object of unspecified type such that if `str` is the name of a stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` or `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `str << resetiosflags(mask)` or `str >> resetiosflags(mask)` behaves as if the following code was executed: `str.setf([std::ios\_base::fmtflags](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)(0), mask);` ### Example ``` #include <sstream> #include <iostream> #include <iomanip> int main() { std::istringstream in("10 010 10 010 10 010"); int n1, n2; in >> std::oct >> n1 >> n2; std::cout << "Parsing \"10 010\" with std::oct gives: " << n1 << ' ' << n2 << '\n'; in >> std::dec >> n1 >> n2; std::cout << "Parsing \"10 010\" with std::dec gives: " << n1 << ' ' << n2 << '\n'; in >> std::resetiosflags(std::ios_base::basefield) >> n1 >> n2; std::cout << "Parsing \"10 010\" with autodetect gives: " << n1 << ' ' << n2 << '\n'; } ``` Output: ``` Parsing "10 010" with std::oct gives: 8 8 Parsing "10 010" with std::dec gives: 10 10 Parsing "10 010" with autodetect gives: 10 8 ``` ### See also | | | | --- | --- | | [setf](../ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | cpp std::skipws, std::noskipws std::skipws, std::noskipws ========================== | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& skipws( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& noskipws( std::ios_base& str ); ``` | (2) | | Enables or disables skipping of leading whitespace by the formatted input functions (enabled by default). Has no effect on output. 1) enables the `skipws` flag in the stream `str` as if by calling `str.setf([std::ios\_base::skipws](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) disables the `skipws` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::skipws](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. The whitespace skipping is performed by the constructor of `[std::basic\_istream::sentry](../basic_istream/sentry "cpp/io/basic istream/sentry")`, which reads and discards the characters classified as whitespace by the `[std::ctype](../../locale/ctype "cpp/locale/ctype")` facet of the stream's imbued locale. This is an I/O manipulator, it may be called with an expression such as `out << std::noskipws` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::noskipws` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> #include <sstream> int main() { char c1, c2, c3; std::istringstream("a b c") >> c1 >> c2 >> c3; std::cout << "Default behavior: c1 = " << c1 << " c2 = " << c2 << " c3 = " << c3 << '\n'; std::istringstream("a b c") >> std::noskipws >> c1 >> c2 >> c3; std::cout << "noskipws behavior: c1 = " << c1 << " c2 = " << c2 << " c3 = " << c3 << '\n'; } ``` Output: ``` Default behavior: c1 = a c2 = b c3 = c noskipws behavior: c1 = a c2 = c3 = b ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | | [ws](ws "cpp/io/manip/ws") | consumes whitespace (function template) | cpp std::setprecision std::setprecision ================= | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` /*unspecified*/ setprecision( int n ); ``` | | | When used in an expression `out << setprecision(n)` or `in >> setprecision(n)`, sets the `precision` parameter of the stream `out` or `in` to exactly `n`. ### Parameters | | | | | --- | --- | --- | | n | - | new value for precision | ### Return value Returns an object of unspecified type such that if `str` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` or an input stream of type `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `str << setprecision(n)` or `str >> setprecision(n)` behaves as if the following code was executed: `str.precision(n);` ### Example ``` #include <iostream> #include <iomanip> #include <cmath> #include <limits> int main() { const long double pi = std::acos(-1.L); std::cout << "default precision (6): " << pi << '\n' << "std::setprecision(10): " << std::setprecision(10) << pi << '\n' << "max precision: " << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << pi << '\n'; } ``` Output: ``` default precision (6): 3.14159 std::setprecision(10): 3.141592654 max precision: 3.141592653589793239 ``` ### See also | | | | --- | --- | | [fixedscientifichexfloatdefaultfloat](fixed "cpp/io/manip/fixed") (C++11)(C++11) | changes formatting used for floating-point I/O (function) | | [precision](../ios_base/precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function of `std::ios_base`) | cpp std::flush std::flush ========== | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& flush( std::basic_ostream<CharT, Traits>& os ); ``` | | | Flushes the output sequence `os` as if by calling `os.flush()`. This is an output-only I/O manipulator, it may be called with an expression such as `out << std::flush` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`. ### Notes This manipulator may be used to produce an incomplete line of output immediately, e.g. when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly. An explicit flush of `[std::cout](../cout "cpp/io/cout")` is also necessary before a call to `[std::system](../../utility/program/system "cpp/utility/program/system")`, if the spawned process performs any screen I/O (a common example is `[std::system](http://en.cppreference.com/w/cpp/utility/program/system)("pause")` on Windows). In most other usual interactive I/O scenarios, `[std::endl](endl "cpp/io/manip/endl")` is redundant when used with `[std::cout](../cout "cpp/io/cout")` because any input from `[std::cin](../cin "cpp/io/cin")`, output to `[std::cerr](../cerr "cpp/io/cerr")`, or program termination forces a call to `[std::cout](http://en.cppreference.com/w/cpp/io/cout).flush()`. When a complete line of output needs to be flushed, the `[std::endl](endl "cpp/io/manip/endl")` manipulator may be used. When every output operation needs to be flushed, the `[std::unitbuf](unitbuf "cpp/io/manip/unitbuf")` manipulator may be used. ### Parameters | | | | | --- | --- | --- | | os | - | reference to output stream | ### Return value `os` (reference to the stream after manipulation). ### Example Without std::flush, the output would be the same, but may not appear in real time. ``` #include <iostream> #include <chrono> template<typename Diff> void log_progress(Diff d) { std::cout << "..(" << std::chrono::duration_cast<std::chrono::milliseconds>(d).count() << " ms).." << std::flush; } int main() { volatile int sink=0; auto t1 = std::chrono::high_resolution_clock::now(); for(int j=0; j<5; ++j) { for(int n=0; n<10000; ++n) for(int m=0; m<20000; ++m) sink += m*n; // do some work auto now = std::chrono::high_resolution_clock::now(); log_progress(now - t1); } std::cout << '\n'; } ``` Possible output: ``` ..(450 ms)....(901 ms)....(1350 ms)....(1800 ms)....(2250 ms).. ``` ### See also | | | | --- | --- | | [unitbufnounitbuf](unitbuf "cpp/io/manip/unitbuf") | controls whether output is flushed after each operation (function) | | [endl](endl "cpp/io/manip/endl") | outputs `'\n'` and flushes the output stream (function template) | | [flush](../basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) |
programming_docs
cpp std::ws std::ws ======= | Defined in header `[<istream>](../../header/istream "cpp/header/istream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_istream<CharT,Traits>& ws( std::basic_istream<CharT, Traits>& is ); ``` | | | Discards leading whitespace from an input stream. Behaves as an [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that `is.gcount()` is not modified. After constructing and checking the sentry object, extracts characters from the stream and discards them until any one of the following conditions occurs: * end of file condition occurs in the input sequence (in which case the function calls `setstate(eofbit)` but does not set `failbit`; this does not apply if the `eofbit` is already set on `is` prior to the call to `ws`, in which case the construction of the sentry object would set `failbit`). * the next available character `c` in the input sequence is not whitespace as determined by `std::isspace(c, is.getloc())`. The non-whitespace character is not extracted. This is an input-only I/O manipulator, it may be called with an expression such as `in >> std::ws` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | is | - | reference to input stream | ### Return value `is` (reference to the stream after extraction of consecutive whitespace). ### Notes If `eofbit` is set on the stream prior to the call, the construction of the sentry object will set `failbit`. ### Example ``` #include <iostream> #include <iomanip> #include <istream> #include <sstream> #include <string> int main() { for (const char* str: {" #1 test", "\t #2 test", "#3 test"}) { std::string line; std::getline(std::istringstream{str}, line); std::cout << "getline returns: \t" << quoted(line) << '\n'; std::istringstream iss{str}; std::getline(iss >> std::ws, line); std::cout << "ws + getline returns: \t" << quoted(line) << '\n'; } } ``` Output: ``` getline returns: " #1 test" ws + getline returns: "#1 test" getline returns: " #2 test" ws + getline returns: "#2 test" getline returns: "#3 test" ws + getline returns: "#3 test" ``` ### See also | | | | --- | --- | | [ignore](../basic_istream/ignore "cpp/io/basic istream/ignore") | extracts and discards characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::setw std::setw ========= | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` /*unspecified*/ setw( int n ); ``` | | | When used in an expression `out << setw(n)` or `in >> setw(n)`, sets the `width` parameter of the stream `out` or `in` to exactly `n`. ### Parameters | | | | | --- | --- | --- | | n | - | new value for width | ### Return value Returns an object of unspecified type such that if `str` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` or `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `str << setw(n)` or `str >> setw(n)` behaves as if the following code was executed: `str.width(n);` ### Notes The width property of the stream will be reset to zero (meaning "unspecified") if any of the following functions are called: * Input + [`operator>>(basic_istream&, basic_string&)`](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") + [`operator>>(basic_istream&, char*)`](../basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") * Output + Overloads 1-7 of [`basic_ostream::operator<<()`](../basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") (at Stage 3 of [`num_put::put()`](../../locale/num_put/put "cpp/locale/num put/put")) + [`operator<<(basic_ostream&, char)`](../basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") and [`operator<<(basic_ostream&, char*)`](../basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") + [`operator<<(basic_ostream&, basic_string&)`](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") + `[std::put\_money](put_money "cpp/io/manip/put money")` (inside [`money_put::put()`](../../locale/money_put/put "cpp/locale/money put/put")) + `[std::quoted](quoted "cpp/io/manip/quoted")` (when used with an output stream) The exact effects this modifier has on the input and output vary between the individual I/O functions and are described at each `operator<<` and `operator>>` overload page individually. ### Example ``` #include <sstream> #include <iostream> #include <iomanip> int main() { std::cout << "no setw: [" << 42 << "]\n" << "setw(6): [" << std::setw(6) << 42 << "]\n" << "setw(6), several elements: [" << 89 << std::setw(6) << 12 << 34 << "]\n"; std::istringstream is("hello, world"); char arr[10]; is >> std::setw(6) >> arr; std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \"" << arr << "\"\n"; } ``` Output: ``` no setw: [42] setw(6): [ 42] setw(6), several elements: [89 1234] Input from "hello, world" with setw(6) gave "hello" ``` ### See also | | | | --- | --- | | [width](../ios_base/width "cpp/io/ios base/width") | manages field width (public member function of `std::ios_base`) | | [setfill](setfill "cpp/io/manip/setfill") | changes the fill character (function template) | | [internalleftright](left "cpp/io/manip/left") | sets the placement of fill characters (function) | | [showbasenoshowbase](showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | cpp std::get_time std::get\_time ============== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class CharT > /*unspecified*/ get_time( std::tm* tmb, const CharT* fmt ); ``` | | (since C++11) | When used in an expression `in >> get_time(tmb, fmt)`, parses the character input as a date/time value according to format string `fmt` according to the `[std::time\_get](../../locale/time_get "cpp/locale/time get")` facet of the locale currently imbued in the input stream `in`. The resultant value is stored in a `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object pointed to by `tmb`. ### Parameters | | | | | --- | --- | --- | | tmb | - | valid pointer to the std::tm object where the result will be stored | | fmt | - | pointer to a null-terminated CharT string 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`. | ### Return value Returns an object of unspecified type such that if `in` is the name of an input stream of type `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `in >> get_time(tmb, fmt)` behaves as if the following code was executed: `typedef [std::istreambuf\_iterator](http://en.cppreference.com/w/cpp/iterator/istreambuf_iterator)<CharT, Traits> Iter; typedef [std::time\_get](http://en.cppreference.com/w/cpp/locale/time_get)<CharT, Iter> TimeGet; [std::ios\_base::iostate](http://en.cppreference.com/w/cpp/io/ios_base/iostate) err = [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate); const TimeGet& tg = [std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<TimeGet>(in.getloc()); tg.get(Iter(in.rdbuf()), Iter(), in, err, tmb, fmt, fmt + traits::length(fmt)); if (err != [std::ios\_base::goodbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate)) in.setstate(err);` ### Notes As specified in `[std::time\_get::do\_get](../../locale/time_get/get "cpp/locale/time get/get")`, which this function calls, it's unspecified if this function zero out the fields in `*tmb` that are not set directly by the conversion specifiers that appear in `fmt`: portable programs should initialize every field of `*tmb` to zero before calling `std::get_time`. ### Example note: choose clang or gcc >= 12.1 to observe the output. libstdc++ before 12.1 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\_get](../../locale/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](put_time "cpp/io/manip/put time") (C++11) | formats and outputs a date/time value according to the specified format (function template) | | [parse](../../chrono/parse "cpp/chrono/parse") (C++20) | parses a `chrono` object from a stream (function template) | cpp std::showpos, std::noshowpos std::showpos, std::noshowpos ============================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& showpos( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& noshowpos( std::ios_base& str ); ``` | (2) | | Enables or disables the display of the plus sign `'+'` in non-negative integer output. Has no effect on input. 1) enables the `showpos` flag in the stream `str` as if by calling `str.setf([std::ios\_base::showpos](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) disables the `showpos` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::showpos](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This is an I/O manipulator, it may be called with an expression such as `out << std::showpos` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::showpos` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> int main() { std::cout << "showpos: " << std::showpos << 42 << ' ' << 3.14 << ' ' << 0 << '\n' << "noshowpos: " << std::noshowpos << 42 << ' ' << 3.14 << ' ' << 0 << '\n'; } ``` Output: ``` showpos: +42 +3.14 +0 noshowpos: 42 3.14 0 ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | cpp std::fixed, std::scientific, std::hexfloat, std::defaultfloat std::fixed, std::scientific, std::hexfloat, std::defaultfloat ============================================================= | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& fixed( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& scientific( std::ios_base& str ); ``` | (2) | | | ``` std::ios_base& hexfloat( std::ios_base& str ); ``` | (3) | (since C++11) | | ``` std::ios_base& defaultfloat( std::ios_base& str ); ``` | (4) | (since C++11) | Modifies the default formatting for floating-point output. 1) Sets the `floatfield` of the stream `str` to `fixed` as if by calling `str.setf([std::ios\_base::fixed](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::floatfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` 2) Sets the `floatfield` of the stream `str` to `scientific` as if by calling `str.setf([std::ios\_base::scientific](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::floatfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` 3) Sets the `floatfield` of the stream `str` to `fixed` and `scientific` simultaneously as if by calling `str.setf([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), [std::ios\_base::floatfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This enables hexadecimal floating-point formatting. 4) Sets the `floatfield` of the stream `str` to zero, as if by calling `str.unsetf([std::ios\_base::floatfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This enables the default floating-point formatting, which is different from fixed and scientific. This is an I/O manipulator, it may be called with an expression such as `out << std::fixed` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` (or with an expression such as `in >> std::scientific` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`). ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Notes Hexadecimal floating-point formatting ignores the stream precision specification, as required by the specification of `[std::num\_put::do\_put](../../locale/num_put/put "cpp/locale/num put/put")`. These manipulators do not affect floating-point parsing. ### Example ``` #include <iostream> #include <iomanip> #include <sstream> enum class cap { title, middle, end }; void print(const char* text, double num, cap c) { if (c == cap::title) std::cout << "┌──────────┬────────────┬──────────────────────────┐\n" "│ number │ iomanip │ representation │\n" "├──────────┼────────────┼──────────────────────────┤\n" ; std::cout << std::left << "│ " << std::setw(8) << text << " │ fixed │ " << std::setw(24) << std::fixed << num << " │\n" << "│ " << std::setw(8) << text << " │ scientific │ " << std::setw(24) << std::scientific << num << " │\n" << "│ " << std::setw(8) << text << " │ hexfloat │ " << std::setw(24) << std::hexfloat << num << " │\n" << "│ " << std::setw(8) << text << " │ default │ " << std::setw(24) << std::defaultfloat << num << " │\n" ; std::cout << (c != cap::end ? "├──────────┼────────────┼──────────────────────────┤\n" : "└──────────┴────────────┴──────────────────────────┘\n" ); } int main() { print("0.0", 0.0, cap::title); print("0.01", 0.01, cap::middle); print("0.00001", 0.00001, cap::end); // Note; choose clang for correct output double f; std::istringstream("0x1.8p+0") >> f; std::cout << "Parsing 0x1.8p+0 gives " << f << '\n'; std::istringstream("0x1P-1022") >> f; std::cout << "Parsing 0x1P-1022 gives " << f << '\n'; } ``` Output: ``` ┌──────────┬────────────┬──────────────────────────┐ │ number │ iomanip │ representation │ ├──────────┼────────────┼──────────────────────────┤ │ 0.0 │ fixed │ 0.000000 │ │ 0.0 │ scientific │ 0.000000e+00 │ │ 0.0 │ hexfloat │ 0x0p+0 │ │ 0.0 │ default │ 0 │ ├──────────┼────────────┼──────────────────────────┤ │ 0.01 │ fixed │ 0.010000 │ │ 0.01 │ scientific │ 1.000000e-02 │ │ 0.01 │ hexfloat │ 0x1.47ae147ae147bp-7 │ │ 0.01 │ default │ 0.01 │ ├──────────┼────────────┼──────────────────────────┤ │ 0.00001 │ fixed │ 0.000010 │ │ 0.00001 │ scientific │ 1.000000e-05 │ │ 0.00001 │ hexfloat │ 0x1.4f8b588e368f1p-17 │ │ 0.00001 │ default │ 1e-05 │ └──────────┴────────────┴──────────────────────────┘ Parsing 0x1.8p+0 gives 1.5 Parsing 0x1P-1022 gives 2.22507e-308 ``` ### See also | | | | --- | --- | | [setprecision](setprecision "cpp/io/manip/setprecision") | changes floating-point precision (function) |
programming_docs
cpp std::emit_on_flush, std::noemit_on_flush std::emit\_on\_flush, std::noemit\_on\_flush ============================================ | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& emit_on_flush( std::basic_ostream<CharT, Traits>& os ); ``` | (1) | (since C++20) | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& noemit_on_flush( std::basic_ostream<CharT, Traits>& os ); ``` | (2) | (since C++20) | If `os.rdbuf()` actually points to a `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)<CharT, Traits, Allocator>` `buf`, toggles whether it emits (i.e., transmits data to the underlying stream buffer) when flushed: 1) calls `buf.set_emit_on_sync(true)` 2) calls `buf.set_emit_on_sync(false)` Otherwise, these manipulators have no effect. This is an output-only I/O manipulator, it may be called with an expression such as `out << std::emit_on_flush` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")`. ### Parameters | | | | | --- | --- | --- | | os | - | reference to output stream | ### Return value `os` (reference to the stream after manipulation). ### Example ### See also | | | | --- | --- | | [set\_emit\_on\_sync](../basic_syncbuf/set_emit_on_sync "cpp/io/basic syncbuf/set emit on sync") | changes the current emit-on-sync policy (public member function of `std::basic_syncbuf<CharT,Traits,Allocator>`) | cpp std::left, std::right, std::internal std::left, std::right, std::internal ==================================== | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& left( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& right( std::ios_base& str ); ``` | (2) | | | ``` std::ios_base& internal( std::ios_base& str ); ``` | (3) | | Modifies the positioning of the fill characters in an output stream. `left` and `right` apply to any type being output, `internal` applies to integer, floating-point, and monetary output. Has no effect on input. 1) sets the `adjustfield` of the stream `str` to `left` as if by calling `str.setf([std::ios\_base::left](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) sets the `adjustfield` of the stream `str` to `right` as if by calling `str.setf([std::ios\_base::right](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 3) sets the `adjustfield` of the stream `str` to `internal` as if by calling `str.setf([std::ios\_base::internal](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), [std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. The initial default for standard streams is equivalent to `right`. This is an I/O manipulator. It may be called with an expression such as `out << std::left` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::left` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> #include <iomanip> #include <locale> int main() { std::cout.imbue(std::locale("en_US.utf8")); std::cout << "Default positioning:\n" << std::setfill('*') << std::setw(12) << -1.23 << '\n' << std::setw(12) << std::hex << std::showbase << 42 << '\n' << std::setw(12) << std::put_money(123, true) << "\n\n"; std::cout << "Left positioning:\n" << std::left << std::setw(12) << -1.23 << '\n' << std::setw(12) << 42 << '\n' << std::setw(12) << std::put_money(123, true) << "\n\n"; std::cout << "Internal positioning:\n" << std::internal << std::setw(12) << -1.23 << '\n' << std::setw(12) << 42 << '\n' << std::setw(12) << std::put_money(123, true) << "\n\n"; std::cout << "Right positioning:\n" << std::right << std::setw(12) << -1.23 << '\n' << std::setw(12) << 42 << '\n' << std::setw(12) << std::put_money(123, true) << '\n'; } ``` Output: ``` Default positioning: *******-1.23 ********0x2a ***USD *1.23 Left positioning: -1.23******* 0x2a******** USD *1.23*** Internal positioning: -*******1.23 0x********2a USD ****1.23 Right positioning: *******-1.23 ********0x2a ***USD *1.23 ``` ### See also | | | | --- | --- | | [setw](setw "cpp/io/manip/setw") | changes the width of the next input/output field (function) | | [setfill](setfill "cpp/io/manip/setfill") | changes the fill character (function template) | | [showbasenoshowbase](showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | cpp std::boolalpha, std::noboolalpha std::boolalpha, std::noboolalpha ================================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& boolalpha( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& noboolalpha( std::ios_base& str ); ``` | (2) | | 1) Enables the `boolalpha` flag in the stream `str` as if by calling `str.setf([std::ios\_base::boolalpha](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` 2) Disables the `boolalpha` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::boolalpha](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))` `std::boolalpha` is an I/O manipulator, so it may be called with an expression such as `out << std::boolalpha` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::boolalpha` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <sstream> #include <locale> #include <iostream> int main() { // boolalpha output std::cout << std::boolalpha << "boolalpha true: " << true << '\n' << "boolalpha false: " << false << '\n'; std::cout << std::noboolalpha << "noboolalpha true: " << true << '\n' << "noboolalpha false: " << false << '\n'; // boolalpha parse bool b1, b2; std::istringstream is("true false"); is >> std::boolalpha >> b1 >> b2; std::cout << '\"' << is.str() << "\" parsed as " << b1 << ' ' << b2 << '\n'; } ``` Output: ``` boolalpha true: true boolalpha false: false noboolalpha true: 1 noboolalpha false: 0 "true false" parsed as 1 0 ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | | [do\_truenamedo\_falsename](../../locale/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>`) | cpp std::setiosflags std::setiosflags ================ | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` /*unspecified*/ setiosflags( std::ios_base::fmtflags mask ); ``` | | | When used in an expression `out << setiosflags(mask)` or `in >> setiosflags(mask)`, sets all format flags of the stream `out` or `in` as specified by the `mask`. ### Parameters | | | | | --- | --- | --- | | mask | - | bitmask of the flags to set | ### Return value Returns an object of unspecified type such that if `str` is the name of a stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` or `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>`, then the expression `str << setiosflags(mask)` or `str >> setiosflags(mask)` behaves as if the following code was executed: `str.setf(mask);` ### Example ``` #include <iostream> #include <iomanip> int main() { std::cout << std::resetiosflags(std::ios_base::dec) << std::setiosflags( std::ios_base::hex | std::ios_base::uppercase | std::ios_base::showbase) << 42 << '\n'; } ``` Output: ``` 0X2A ``` ### See also | | | | --- | --- | | [setf](../ios_base/setf "cpp/io/ios base/setf") | sets specific format flag (public member function of `std::ios_base`) | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | cpp std::uppercase, std::nouppercase std::uppercase, std::nouppercase ================================ | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` std::ios_base& uppercase( std::ios_base& str ); ``` | (1) | | | ``` std::ios_base& nouppercase( std::ios_base& str ); ``` | (2) | | Enables the use of uppercase characters in floating-point and hexadecimal integer output. Has no effect on input. 1) enables the `uppercase` flag in the stream `str` as if by calling `str.setf([std::ios\_base::uppercase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. 2) disables the `uppercase` flag in the stream `str` as if by calling `str.unsetf([std::ios\_base::uppercase](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags))`. This is an I/O manipulator, it may be called with an expression such as `out << std::uppercase` for any `out` of type `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` or with an expression such as `in >> std::uppercase` for any `in` of type `[std::basic\_istream](../basic_istream "cpp/io/basic istream")`. ### Parameters | | | | | --- | --- | --- | | str | - | reference to I/O stream | ### Return value `str` (reference to the stream after manipulation). ### Example ``` #include <iostream> int main() { std::cout << std::hex << std::showbase << "0x2a with uppercase: " << std::uppercase << 0x2a << '\n' << "0x2a with nouppercase: " << std::nouppercase << 0x2a << '\n' << "1e-10 with uppercase: " << std::uppercase << 1e-10 << '\n' << "1e-10 with nouppercase: " << std::nouppercase << 1e-10 << '\n'; } ``` Output: ``` 0x2a with uppercase: 0X2A 0x2a with nouppercase: 0x2a 1e-10 with uppercase: 1E-10 1e-10 with nouppercase: 1e-10 ``` ### See also | | | | --- | --- | | [resetiosflags](resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | cpp std::put_time std::put\_time ============== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class CharT > /*unspecified*/ put_time( const std::tm* tmb, const CharT* fmt ); ``` | | (since C++11) | When used in an expression `out << put_time(tmb, fmt)`, converts the date and time information from a given calendar time `tmb` to a character string according to [format string](#Format_string) `fmt`, as if by calling `[std::strftime](../../chrono/c/strftime "cpp/chrono/c/strftime")`, `[std::wcsftime](../../chrono/c/wcsftime "cpp/chrono/c/wcsftime")`, or analog (depending on `CharT`), according to the `[std::time\_put](../../locale/time_put "cpp/locale/time put")` facet of the locale currently imbued in the output stream `out`. ### Parameters | | | | | --- | --- | --- | | tmb | - | pointer to the calendar time structure as obtained from `[std::localtime](../../chrono/c/localtime "cpp/chrono/c/localtime")` or `[std::gmtime](../../chrono/c/gmtime "cpp/chrono/c/gmtime")` | | fmt | - | pointer to a null-terminated `CharT` string specifying the [format of conversion](#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 Returns an object of unspecified type such that if `out` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>`, then the expression `out << put_time(tmb, fmt)` behaves as if the following code was executed: `typedef [std::ostreambuf\_iterator](http://en.cppreference.com/w/cpp/iterator/ostreambuf_iterator)<CharT, Traits> Iter; typedef [std::time\_put](http://en.cppreference.com/w/cpp/locale/time_put)<CharT, Iter> TimePut; const TimePut& tp = [std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<TimePut>(out.getloc()); const Iter end = tp.put(Iter(out.rdbuf()), out, out.fill(), tmb, fmt, fmt + Traits::length(fmt)); if (end.failed()) out.setstate([std::ios\_base::badbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate));` ### Example ``` #include <iostream> #include <iomanip> #include <ctime> int main() { std::time_t t = std::time(nullptr); std::tm tm = *std::localtime(&t); std::cout.imbue(std::locale("ru_RU.utf8")); std::cout << "ru_RU: " << std::put_time(&tm, "%c %Z") << '\n'; std::cout.imbue(std::locale("ja_JP.utf8")); std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << '\n'; } ``` Output: ``` ru_RU: Ср. 28 дек. 2011 10:21:16 EST ja_JP: 2011年12月28日 10時21分16秒 EST ``` ### See also | | | | --- | --- | | [time\_put](../../locale/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](get_time "cpp/io/manip/get time") (C++11) | parses a date/time value of specified format (function template) | | [strftime](../../chrono/c/strftime "cpp/chrono/c/strftime") | converts a `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object to custom textual representation (function) | | [wcsftime](../../chrono/c/wcsftime "cpp/chrono/c/wcsftime") | converts a `[std::tm](../../chrono/c/tm "cpp/chrono/c/tm")` object to custom wide string textual representation (function) |
programming_docs
cpp std::put_money std::put\_money =============== | Defined in header `[<iomanip>](../../header/iomanip "cpp/header/iomanip")` | | | | --- | --- | --- | | ``` template< class MoneyT > /*unspecified*/ put_money( const MoneyT& mon, bool intl = false ); ``` | | (since C++11) | When used in an expression `out << put_money(mon, intl)`, converts the monetary value `mon` to its character representation as specified by the `[std::money\_put](../../locale/money_put "cpp/locale/money put")` facet of the locale currently imbued in `out`. The insertion operation in `out << put_money(mon, intl)` behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). ### Parameters | | | | | --- | --- | --- | | mon | - | a monetary value, either `long double` or `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` | | intl | - | use international currency strings if `true`, use currency symbols otherwise | ### Return value Returns an object of unspecified type such that if `out` is the name of an output stream of type `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>`, then the expression `out << put_money(mon, intl)` behaves as if the following code was executed: `typedef [std::ostreambuf\_iterator](http://en.cppreference.com/w/cpp/iterator/ostreambuf_iterator)<CharT, Traits> Iter; typedef [std::money\_put](http://en.cppreference.com/w/cpp/locale/money_put)<CharT, Iter> MoneyPut; const MoneyPut& mp = [std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<MoneyPut>(out.getloc()); const Iter end = mp.put(Iter(out.rdbuf()), intl, out, out.fill(), mon); if (end.failed()) out.setstate(std::ios::badbit);` ### Example ``` #include <iostream> #include <iomanip> int main() { long double mon = 123.45; // or std::string mon = "123.45"; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << std::showbase << "en_US: " << std::put_money(mon) << " or " << std::put_money(mon, true) << '\n'; std::cout.imbue(std::locale("ru_RU.UTF-8")); std::cout << "ru_RU: " << std::put_money(mon) << " or " << std::put_money(mon, true) << '\n'; std::cout.imbue(std::locale("ja_JP.UTF-8")); std::cout << "ja_JP: " << std::put_money(mon) << " or " << std::put_money(mon, true) << '\n'; } ``` Possible output: ``` en_US: $1.23 or USD 1.23 ru_RU: 1.23 руб or 1.23 RUB ja_JP: ¥123 or JPY 123 ``` ### See also | | | | --- | --- | | [money\_put](../../locale/money_put "cpp/locale/money put") | formats a monetary value for output as a character sequence (class template) | | [get\_money](get_money "cpp/io/manip/get money") (C++11) | parses a monetary value (function template) | cpp std::basic_spanbuf<CharT,Traits>::swap std::basic\_spanbuf<CharT,Traits>::swap ======================================= | | | | | --- | --- | --- | | ``` void swap( basic_spanbuf& rhs ); ``` | | (since C++23) | Swaps the state of `*this` and `rhs`. Calls `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<Char, Traits>::swap(rhs)`, swaps the open mode of `*this` and `rhs`, and then makes them use the underlying buffer of each other. ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_stringbuf` | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Notes This function is called automatically when swapping stream objects, it is rarely necessary to call it directly. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic spanbuf/operator=") (C++23) | assigns a `basic_spanbuf` object (public member function) | | [swap](../basic_ispanstream/swap "cpp/io/basic ispanstream/swap") (C++23) | swaps two `basic_ispanstream` objects (public member function of `std::basic_ispanstream<CharT,Traits>`) | | [swap](../basic_ospanstream/swap "cpp/io/basic ospanstream/swap") (C++23) | swaps two `basic_ospanstream` objects (public member function of `std::basic_ospanstream<CharT,Traits>`) | | [swap](../basic_spanstream/swap "cpp/io/basic spanstream/swap") (C++23) | swaps two `basic_spanstream` objects (public member function of `std::basic_spanstream<CharT,Traits>`) | cpp std::basic_spanbuf<CharT,Traits>::seekpos std::basic\_spanbuf<CharT,Traits>::seekpos ========================================== | | | | | --- | --- | --- | | ``` protected: pos_type seekpos( pos_type sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ) override; ``` | | (since C++23) | Repositions the next pointer to the get and/or put area, if possible, to the position indicated by `sp`. Equivalent to `return seekoff(off_type(sp), [std::ios\_base::beg](http://en.cppreference.com/w/cpp/io/ios_base/seekdir), which);`. ### Parameters | | | | | --- | --- | --- | | sp | - | stream position, such as one obtained by `seekoff()` or `seekpos()` | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `sp` on success or `pos_type(off_type(-1))` on failure. ### Notes `seekpos()` is called by `[std::basic\_streambuf::pubseekpos()](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos")`, which is called by the single-argument versions of `[std::basic\_istream::seekg()](../basic_istream/seekg "cpp/io/basic istream/seekg")` and `[std::basic\_ostream::seekp()](../basic_ostream/seekp "cpp/io/basic ostream/seekp")`. ### Example ### See also | | | | --- | --- | | [pubseekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](../basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekpos](../strstreambuf/seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::strstreambuf`) | cpp std::swap(std::basic_spanbuf) std::swap(std::basic\_spanbuf) ============================== | Defined in header `[<spanstream>](../../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( std::basic_spanbuf<CharT, Traits>& lhs, std::basic_spanbuf<CharT, Traits>& rhs ); ``` | | (since C++23) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_spanbuf`. Exchanges the state of `lhs` with that of `rhs`. Equivalent to `lhs.swap(rhs);`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `std::basic_spanbuf` objects whose states to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function) | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | cpp std::basic_spanbuf<CharT,Traits>::operator= std::basic\_spanbuf<CharT,Traits>::operator= ============================================ | | | | | --- | --- | --- | | ``` basic_spanbuf& operator=( basic_spanbuf&& rhs ); ``` | (1) | (since C++23) | | ``` basic_spanbuf& operator( const basic_spanbuf& ) = delete; ``` | (2) | (since C++23) | 1) Move assignment operator. Equivalent to `auto tmp{std::move(rhs)}; this->swap(tmp); return *this;`. After move assignment, `*this` holds the state `rhs` held before move assignment. It is implementation-defined whether `rhs` still hold the underlying buffer after move assignment. 2) The copy assignment operator is deleted; `basic_spanbuf` is not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_spanbuf` that will be moved from | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [(constructor)](basic_spanbuf "cpp/io/basic spanbuf/basic spanbuf") (C++23) | constructs a `basic_spanbuf` object (public member function) | | [swap](swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function) | cpp std::basic_spanbuf<CharT,Traits>::setbuf std::basic\_spanbuf<CharT,Traits>::setbuf ========================================= | | | | | --- | --- | --- | | ``` protected: std::basic_streambuf<CharT, Traits>* setbuf( CharT *s, std::streamsize n ) override; ``` | | (since C++23) | Makes the `basic_spanbuf` perform I/O on the buffer [`s`, `s + n`). Equivalently calls `this->span([std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>(s, n))` and then returns `this`. | Set bits in open mode(affecting pointers to get area) | Return value after setting | | --- | --- | | `[eback()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[gptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | | `[std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s` | `s` | `s + n` | | | | Set bits in open mode(affecting pointers to put area) | Return value after setting | | `[pbase()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[epptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && ![std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s` | `s` | `s + n` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && [std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s` | `s + n` | `s + n` | This function is protected virtual, it may only be called through `pubsetbuf()` or from member functions of a user-defined class derived from `std::basic_spanbuf`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the first `CharT` in the user-provided buffer | | n | - | the number of `CharT` elements in the user-provided buffer | ### Return value `this`. ### Notes The deprecated stream buffer `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")` or the boost.IOStreams device [`boost::basic_array`](http://www.boost.org/doc/libs/release/libs/iostreams/doc/classes/array.html#array) can also implement I/O buffering over a user-provided `char` array. ### Example ### See also | | | | --- | --- | | [pubsetbuf](../basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [setbuf](../basic_stringbuf/setbuf "cpp/io/basic stringbuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [setbuf](../strstreambuf/setbuf "cpp/io/strstreambuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function of `std::strstreambuf`) | cpp std::basic_spanbuf<CharT,Traits>::seekoff std::basic\_spanbuf<CharT,Traits>::seekoff ========================================== | | | | | --- | --- | --- | | ``` protected: pos_type seekoff( off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ) override; ``` | | (since C++23) | Repositions the next pointer to get and/or put area, if possible, to the position that corresponds to exactly `off` characters from beginning, end, or current position of the get and/or put area of the buffer. Let `*n*` be the number of `CharT` elements in underlying buffer, or `​0​` when there is no underlying buffer, this function fails if. * the next pointer to the get and/or put area to reposition is null and the computed `*newoff*` (see below) is not zero, which may occur if there is no underlying buffer, or the `*this` is not opened in the mode required by `which`, or * `dir` is `[std::ios\_base::cur](../ios_base/seekdir "cpp/io/ios base/seekdir")` and both `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` and `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` are set in `which`, or * the computed `*newoff*` is not representable in `off_type`, less than zero, or greater than `*n*`. `*newoff*` is computed as below: * If `dir` is `[std::ios\_base::beg](../ios_base/seekdir "cpp/io/ios base/seekdir")`, `*newoff*` is `off`. * If `dir` is `[std::ios\_base::cur](../ios_base/seekdir "cpp/io/ios base/seekdir")`, `*newoff*` is + `pptr() - pbase() + off` if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in `which`, or + `gptr() - eback() + off` if `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` is set in `which`. * If `dir` is `[std::ios\_base::end](../ios_base/seekdir "cpp/io/ios base/seekdir")`, `*newoff*` is + `pptr() - pbase() + off` if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` but not `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode of `*this`, + otherwise, `off + n`. This function repositions the next pointer to get and/or put area to `pbuf + newoff` on success if `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` and/or `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is correspondingly set in `which`, where `*pbuf*` is the pointer to the beginning of the underlying buffer, or the null pointer value if there is no underlying buffer. ### Parameters | | | | | --- | --- | --- | | off | - | relative position to set the next pointer(s) to | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `pos_type(newoff)` on success, `pos_type(off_type(-1))` on failure. ### Example ### See also | | | | --- | --- | | [seekoff](../basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekoff](../strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::strstreambuf`) | cpp std::basic_spanbuf<CharT,Traits>::basic_spanbuf std::basic\_spanbuf<CharT,Traits>::basic\_spanbuf ================================================= | | | | | --- | --- | --- | | ``` basic_spanbuf() : basic_spanbuf(std::ios_base::in | std::ios_base::out) {} ``` | (1) | (since C++23) | | ``` explicit basic_spanbuf( std::ios_base::openmode which ) : basic_spanbuf(std::span<CharT>{}, which) {} ``` | (2) | (since C++23) | | ``` explicit basic_spanbuf( std::span<CharT> buf, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (3) | (since C++23) | | ``` basic_spanbuf( const basic_spanbuf& ) = delete; ``` | (4) | (since C++23) | | ``` basic_spanbuf( basic_spanbuf&& rhs ); ``` | (5) | (since C++23) | 1) Default constructor. Creates a `basic_spanbuf` that has no underlying buffer and is opened for both input and output. The pointers to get and put area are set to the null pointer value. 2) Same as (1), except that the `basic_spanbuf` is opened in mode specified by `which`. 3) Creates a `basic_spanbuf` that manages the underlying buffer referenced by `buf` (or has no underlying buffer if `buf` is empty) and is opened in mode specified by `which`. The pointers to get and put area are set as following, or to the null pointer value if not mentioned in the table: | Set bits in open mode(affecting pointers to get area) | Return value after setting | | --- | --- | | `[eback()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[gptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | | `[std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data()` | `s.data() + s.size()` | | | | Set bits in open mode(affecting pointers to put area) | Return value after setting | | `[pbase()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[epptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && ![std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data()` | `s.data() + s.size()` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && [std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data() + s.size()` | `s.data() + s.size()` | 4) Copy constructor is deleted. `basic_spanbuf` is not copyable. 5) Move constructor. Move-constructs the `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` base subobject from that of `rhs`. The pointers to get and put area, the open mode, and the underlying buffer (if any) are identical to those in `rhs` before construction. It is implementation-defined whether `rhs` still holds the underlying buffer after the move-construction. ### Parameters | | | | | --- | --- | --- | | buf | - | a [`std::span`](../../container/span "cpp/container/span") referencing the underlying buffer | | rhs | - | another `basic_spanbuf` | | which | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Notes These constructors are typically called by the constructors of `std::basic_ispanstream`, `std::basic_ospanstream`, and `std::basic_spanstream`. ### Example ### See also | | | | --- | --- | | [(constructor)](../basic_ispanstream/basic_ispanstream "cpp/io/basic ispanstream/basic ispanstream") (C++23) | constructs the `basic_ispanstream` (public member function of `std::basic_ispanstream<CharT,Traits>`) | | [(constructor)](../basic_ospanstream/basic_ospanstream "cpp/io/basic ospanstream/basic ospanstream") (C++23) | constructs the `basic_ospanstream` (public member function of `std::basic_ospanstream<CharT,Traits>`) | | [(constructor)](../basic_spanstream/basic_spanstream "cpp/io/basic spanstream/basic spanstream") (C++23) | constructs the `basic_spanstream` (public member function of `std::basic_spanstream<CharT,Traits>`) |
programming_docs
cpp std::basic_spanbuf<CharT,Traits>::span std::basic\_spanbuf<CharT,Traits>::span ======================================= | | | | | --- | --- | --- | | ``` std::span<CharT> span() const noexcept; ``` | (1) | (since C++23) | | ``` void span( std::span<CharT> s ) noexcept; ``` | (2) | (since C++23) | 1) Gets a `span` referencing the written area if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode, or a `span` referencing the underlying buffer otherwise. 2) Makes the `basic_spanbuf` perform I/O on the buffer referenced by `s`. Sets pointers to get area, put area, or both. | Set bits in open mode(affecting pointers to get area) | Return value after setting | | --- | --- | | `[eback()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[gptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` | | `[std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data()` | `s.data() + s.size()` | | | | Set bits in open mode(affecting pointers to put area) | Return value after setting | | `[pbase()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | `[epptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && ![std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data()` | `s.data() + s.size()` | | `[std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode) && [std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` | `s.data()` | `s.data() + s.size()` | `s.data() + s.size()` | ### Parameters | | | | | --- | --- | --- | | s | - | a [`std::span`](../../container/span "cpp/container/span") that references the user-provided buffer | ### Return value 1) `[std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>(pbase(), pptr())` if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode, or a `[std::span](http://en.cppreference.com/w/cpp/container/span)<CharT>` that references the whole underlying buffer otherwise. 2) (none) ### Example ### See also | | | | --- | --- | | [str](../basic_stringbuf/str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [view](../basic_stringbuf/view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [str](../strstreambuf/str "cpp/io/strstreambuf/str") | marks the buffer frozen and returns the beginning pointer of the input sequence (public member function of `std::strstreambuf`) | cpp std::basic_spanstream<CharT,Traits>::rdbuf std::basic\_spanstream<CharT,Traits>::rdbuf =========================================== | | | | | --- | --- | --- | | ``` std::basic_spanbuf<CharT, Traits>* rdbuf() const noexcept; ``` | | (since C++23) | Returns pointer to the wrapped raw device object. ### Parameters (none). ### Return value Pointer to the wrapped raw device object. ### Example ### See also | | | | --- | --- | | [rdbuf](../basic_ios/rdbuf "cpp/io/basic ios/rdbuf") | manages associated stream buffer (public member function of `std::basic_ios<CharT,Traits>`) | cpp std::basic_spanstream<CharT,Traits>::swap std::basic\_spanstream<CharT,Traits>::swap ========================================== | | | | | --- | --- | --- | | ``` void swap( basic_spanstream& other ); ``` | | (since C++23) | Exchanges the state of the stream with those of `other`. This is done by calling `[std::basic\_iostream](http://en.cppreference.com/w/cpp/io/basic_iostream)<CharT, Traits>::swap(other)` and swapping the wrapped `std::basic_spanbuf` objects (accessible through `*rdbuf()`). ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](../basic_spanbuf/swap "cpp/io/basic spanbuf/swap") (C++23) | swaps two `basic_spanbuf` objects (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::basic_spanstream<CharT,Traits>::basic_spanstream std::basic\_spanstream<CharT,Traits>::basic\_spanstream ======================================================= | | | | | --- | --- | --- | | ``` explicit basic_spanstream( std::span<CharT> s, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (1) | (since C++23) | | ``` basic_spanstream( basic_spanstream&& rhs ); ``` | (2) | (since C++23) | | ``` basic_spanstream( const basic_spanstream& ) = delete; ``` | (3) | (since C++23) | Constructs a new `basic_spanstream`. 1) Uses the storage referenced by `s` as initial underlying buffer of the wrapped `std::basic_spanbuf` device. The wrapped `std::basic_spanbuf` object is constructed as `basic_spanbuf<Char, Traits>(s, mode)`. 2) Move constructor. Move constructs the `[std::basic\_iostream](../basic_iostream "cpp/io/basic iostream")` base subobject and the wrapped `std::basic_spanbuf` from those of `rhs`, and then calls `[set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf")` with the address of the wrapped `std::basic_spanbuf` in `*this` to install it. 3) Copy constructor is deleted. `basic_spanstream` is not copyable. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as initial underlying buffer of stream | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another `basic_spanstream` to be moved from | ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [(constructor)](../basic_spanbuf/basic_spanbuf "cpp/io/basic spanbuf/basic spanbuf") (C++23) | constructs a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::swap(std::basic_spanstream) std::swap(std::basic\_spanstream) ================================= | Defined in header `[<spanstream>](../../header/spanstream "cpp/header/spanstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( std::basic_spanstream<CharT, Traits>& lhs, std::basic_spanstream<CharT, Traits>& rhs ); ``` | | (since C++23) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_spanstream`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic spanstream/swap") (C++23) | swaps two `basic_spanstream` objects (public member function) | cpp std::basic_spanstream<CharT,Traits>::operator= std::basic\_spanstream<CharT,Traits>::operator= =============================================== | | | | | --- | --- | --- | | ``` basic_spanstream& operator=( basic_spanstream&& other ); ``` | (1) | (since C++23) | | ``` basic_spanstream& operator=( const basic_spanstream& ) = delete; ``` | (2) | (since C++23) | 1) Move assigns the `other` to `*this`, effectively move-assigning both the `[std::basic\_iostream](../basic_iostream "cpp/io/basic iostream")` base class subobject and the wrapped `std::basic_spanbuf`. 2) Copy assignment operator is deleted. `basic_spanstream` is not copy assignable. Note that move assignment operator of the base class swaps all stream state variables (except for [`rdbuf()`](rdbuf "cpp/io/basic spanstream/rdbuf")) between `*this` and `other`. It is implementation-defined whether the `std::basic_spanbuf` wrapped in `other` still holds an underlying buffer after the move assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another stream to move from | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](../basic_spanbuf/operator= "cpp/io/basic spanbuf/operator=") (C++23) | assigns a `basic_spanbuf` object (public member function of `std::basic_spanbuf<CharT,Traits>`) | | [operator=](../basic_iostream/operator= "cpp/io/basic iostream/operator=") (C++11) | move-assigns another `basic_iostream` (protected member function) | cpp std::basic_spanstream<CharT,Traits>::span std::basic\_spanstream<CharT,Traits>::span ========================================== | | | | | --- | --- | --- | | ``` std::span<CharT> span() const noexcept; ``` | (1) | (since C++23) | | ``` void span( std::span<CharT> s ) noexcept; ``` | (2) | (since C++23) | 1) Gets a `span` referencing the written area if `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in the open mode of the wrapped `std::basic_spanbuf`, or a `span` referencing the underlying buffer otherwise. 2) Makes the wrapped `std::basic_spanbuf` perform I/O on the buffer referenced by `s`. ### Parameters | | | | | --- | --- | --- | | s | - | `std::span` referencing the storage to be use as the new underlying buffer of stream | ### Return value 1) A `std::span` referencing the underlying buffer or written area, depending on the open mode of the wrapped `std::basic_spanbuf`. 2) (none) ### Example ### See also | | | | --- | --- | | [span](../basic_spanbuf/span "cpp/io/basic spanbuf/span") (C++23) | obtains or initializes an underlying buffer according to mode (public member function of `std::basic_spanbuf<CharT,Traits>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::underflow std::basic\_stringbuf<CharT,Traits,Allocator>::underflow ======================================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type underflow() ``` | | | Reads the next character from the get area of the buffer. Specifically: 1) If the input sequence has a read position available (`egptr() > gptr()`), returns `Traits::to_int_type(*gptr())` 2) Otherwise, if `pptr() > egptr()` (some characters were inserted into the stream since the last time `[overflow()](overflow "cpp/io/basic stringbuf/overflow")` changed `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")`) then extends the end of the get area to include the most recently inserted characters, by changing `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` to equal `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, and then returns `Traits::to_int_type(*gptr())` 3) Otherwise, returns `Traits::eof()`. Any character in the buffer which has been initialized, regardless of whether it originated from the string passed in the constructor or was appended by `[overflow()](overflow "cpp/io/basic stringbuf/overflow")`, is considered to be part of the input sequence. ### Parameters (none). ### Return value `Traits::to_int_type(*gptr())` (the next character to read in the get area) in case of success, or `Traits::eof()` in case of failure. ### Example ``` #include <sstream> #include <iostream> struct mybuf : std::stringbuf { mybuf(const std::string& new_str, std::ios_base::openmode which = std::ios_base::in|std::ios_base::out) : std::stringbuf(new_str, which) {} int_type overflow(int_type c) { std::cout << "Before overflow(): get area size is " << egptr()-eback() << ' ' << " the put area size is " << epptr()-pbase() << '\n'; int_type rc = std::stringbuf::overflow(c); std::cout << "After overflow(): get area size is " << egptr()-eback() << ' ' << " put area size is " << epptr()-pbase() << '\n'; return rc; } int_type underflow() { std::cout << "Before underflow(): get area size is " << egptr()-eback() << ' ' << " put area size is " << epptr()-pbase() << '\n'; int_type ch = std::stringbuf::underflow(); std::cout << "After underflow(): get area size is " << egptr()-eback() << ' ' << " put area size is " << epptr()-pbase() << '\n'; if(ch == EOF) std::cout << "underflow() returns EOF\n"; else std::cout << "underflow() returns '" << char(ch) << "'\n"; return ch; } }; int main() { mybuf sbuf("123"); // read-write stream std::iostream stream(&sbuf); int n; stream >> n; // calls sgetc() four times // three calls return the characters '1', '2', '3' // the fourth call, gptr() == egptr() and underflow() is called // underflow returns EOF std::cout << n << '\n'; stream.clear(); // clear the eofbit stream << "123456"; // sputc() is called 6 times // first three calls store "123" in the existing buffer // 4th call finds that pptr() == epptr() and calls overflow() // overflow() grows the buffer and sets egptr() to 4 // 5th and 6th calls store '5' and '6', advancing pptr() stream >> n; // calls sgetc() 4 times // 1st call returns the '4' that was made available by overflow() // on the 2nd call, egptr() == egptr() and underflow() is called // underflow advances egptr() to equal pptr() (which is 6) // 3rd sgetc() returns '6' // 4th sgetc() finds gptr() == egptr(), calls underflow() // underflow() returns EOF std::cout << n << '\n'; } ``` Possible output: ``` Before underflow(): get area size is 3 put area size is 3 After underflow(): get area size is 3 put area size is 3 underflow() returns EOF 123 Before overflow(): get area size is 3 the put area size is 3 After overflow(): get area size is 4 put area size is 35 Before underflow(): get area size is 4 put area size is 35 After underflow(): get area size is 6 put area size is 35 underflow() returns '5' Before underflow(): get area size is 6 put area size is 35 After underflow(): get area size is 6 put area size is 35 underflow() returns EOF 456 ``` ### See also | | | | --- | --- | | [underflow](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](../basic_filebuf/underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [underflow](../strstreambuf/underflow "cpp/io/strstreambuf/underflow") [virtual] | reads a character from the input sequence without advancing the next pointer (virtual protected member function of `std::strstreambuf`) | | [sgetc](../basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::get_allocator std::basic\_stringbuf<CharT,Traits,Allocator>::get\_allocator ============================================================= | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++20) | Returns the allocator associated with the internal sequence container. ### Parameters (none). ### Return value the associated allocator. ### See also | | | | --- | --- | | [get\_allocator](../../string/basic_string/get_allocator "cpp/string/basic string/get allocator") | returns the associated allocator (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::swap std::basic\_stringbuf<CharT,Traits,Allocator>::swap =================================================== | | | | | --- | --- | --- | | ``` void swap( basic_stringbuf& rhs ); ``` | | (since C++11) (until C++20) | | ``` void swap( basic_stringbuf& rhs ) noexcept(/* see below */); ``` | | (since C++20) | Swaps the state and the contents of `*this` and `rhs`. | | | | --- | --- | | The behavior is undefined if `Allocator` does not propagate on swap and the allocators of `*this` and `other` are unequal. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_stringbuf` | ### Return value (none). ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (since C++11)(until C++20) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::propagate\_on\_container\_swap::value || [std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` | (since C++20) | ### Notes This function is called automatically when swapping `[std::stringstream](../basic_stringstream "cpp/io/basic stringstream")` objects, it is rarely necessary to call it directly. ### Example ``` #include <sstream> #include <string> #include <iostream> #include <iomanip> int main() { std::istringstream one("one"); std::ostringstream two("two"); std::cout << "Before swap, one = " << std::quoted( one.str() ) << " two = " << quoted( two.str() ) << '\n'; one.rdbuf()->swap(*two.rdbuf()); std::cout << "After swap, one = " << quoted( one.str() ) << " two = " << quoted( two.str() ) << '\n'; } ``` Output: ``` Before swap, one = "one" two = "two" After swap, one = "two" two = "one" ``` ### See also | | | | --- | --- | | [(constructor)](basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function) | | [swap](../basic_stringstream/swap "cpp/io/basic stringstream/swap") (C++11) | swaps two string streams (public member function of `std::basic_stringstream<CharT,Traits,Allocator>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::str std::basic\_stringbuf<CharT,Traits,Allocator>::str ================================================== | | | | | --- | --- | --- | | | (1) | | | ``` std::basic_string<CharT, Traits, Allocator> str() const; ``` | (until C++20) | | ``` std::basic_string<CharT, Traits, Allocator> str() const&; ``` | (since C++20) | | ``` template<class SAlloc> std::basic_string<CharT, Traits, SAlloc> str( const SAlloc& a ) const; ``` | (2) | (since C++20) | | ``` std::basic_string<CharT, Traits, Allocator> str() &&; ``` | (3) | (since C++20) | | ``` void str( const std::basic_string<CharT, Traits, Allocator>& s ); ``` | (4) | | | ``` template<class SAlloc> void str( const std::basic_string<CharT, Traits, SAlloc>& s ); ``` | (5) | (since C++20) | | ``` void str( std::basic_string<CharT, Traits, Allocator>&& s ); ``` | (6) | (since C++20) | Gets and sets the underlying string. For the purpose of explanation, let `buf_` denote the internal `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` object holding the underlying character sequence. Define *buffer pointer initialization* as follows: * For input streams (`bool(mode & [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode)) == true`), makes `eback()` point at the first character, `gptr() == eback()`, and `egptr() == eback() + buf_.size()`: the subsequent input will read the first character of the string. * For output streams (`bool(mode & [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode)) == true`), makes `pbase()` points at the first character and `epptr() >= pbase() + buf_.size()` (`epptr()` is allowed to point farther so that the following `sputc()` wouldn't immediately call `overflow()`). | | | | --- | --- | | * For append streams (`bool(mode & [std::ios\_base::ate](http://en.cppreference.com/w/cpp/io/ios_base/openmode)) == true`), makes `pptr() == pbase() + buf_.size()`, so that subsequent output will be appended to the last character of the string. | (since C++11) | * For non-appending output streams, makes `pptr() == pbase()`, so that subsequent output will overwrite the characters of the string. 1) Creates and returns a `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` object containing a copy of this `std::basic_stringbuf`'s underlying character sequence. For input-only streams, the returned string contains the characters from the range `[eback(), egptr())`. For input/output or output-only streams, contains the characters from `pbase()` to the last character in the sequence regardless of `egptr()` and `epptr()`. | | | | --- | --- | | The member character sequence in a buffer open for writing can be over-allocated for efficiency purposes. In that case, only the *initialized characters* are returned: these characters are the ones that were obtained from the string argument of the constructor, the string argument of the most recent call to a setter overload of `str()`, or from an write operation. A typical implementation that uses over-allocation maintains a high-watermark pointer to track the end of the initialized part of the buffer and this overload returns the characters from `pbase()` to the high-watermark pointer. | (since C++11) | | | | | --- | --- | | Equivalent to `return [std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT, Traits, Allocator>(view(), get_allocator());`. | (since C++20) | 2) Same as (1), except that `a` is used to construct the returned `std::basic_string`. Equivalent to `return [std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT, Traits, SAlloc>(view(), a);`. This overload participates in overload resolution only if `SAlloc` meets the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). 3) Creates `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` object as if initialized with `std::move(buf_)`. `buf_` may need to be adjusted to contain the same content as in (1) at first. After construction of the `std::basic_string` object, sets `buf_` to empty and performs buffer pointer initialization, then returns the `std::basic_string` object. 4) Replaces the underlying character sequence as if by `buf_ = s`, then performs buffer pointer initialization. 5) Same as (4), except the type of `s`'s allocator is not `Allocator`. This overload participates in overload resolution only if `SAlloc` and `Allocator` are not the same type. 6) Replaces the underlying character sequence as if by `buf_ = std::move(s)`, then performs buffer pointer initialization. ### Parameters | | | | | --- | --- | --- | | s | - | a `basic_string` object holding the replacement character sequence | | a | - | allocator to use for all memory allocations of the returned `basic_string` | ### Return value 1-3) A `basic_string` object holding this buffer's underlying character sequence. 4-6) (none) ### Notes This function is typically accessed through `[std::basic\_istringstream::str()](../basic_istringstream/str "cpp/io/basic istringstream/str")`, `[std::basic\_ostringstream::str()](../basic_ostringstream/str "cpp/io/basic ostringstream/str")`, or `[std::basic\_stringstream::str()](../basic_stringstream/str "cpp/io/basic stringstream/str")`. ### Example ``` #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.rdbuf()->str("1 2"); // set the get area in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.rdbuf()->str() << "\"\n"; // or in.str() std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); // C++11 ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; } ``` Output: ``` after reading the first int from "1 2", the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2", str() = "3 2" after writing the int '3' to append stream "1 2", str() = "1 23" ``` ### See also | | | | --- | --- | | [str](../basic_stringstream/str "cpp/io/basic stringstream/str") | gets or sets the contents of underlying string device object (public member function of `std::basic_stringstream<CharT,Traits,Allocator>`) | | [view](view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function) |
programming_docs
cpp std::basic_stringbuf<CharT,Traits,Allocator>::seekpos std::basic\_stringbuf<CharT,Traits,Allocator>::seekpos ====================================================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekpos( pos_type sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | | | Repositions `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` and/or `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, if possible, to the position indicated by `sp`. Effectively executes `seekoff(off_type(sp), [std::ios\_base::beg](http://en.cppreference.com/w/cpp/io/ios_base/seekdir), which)`. ### Parameters | | | | | --- | --- | --- | | sp | - | stream position, such as one obtained by `[seekoff()](seekoff "cpp/io/basic stringbuf/seekoff")` or `seekpos()` | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `sp` on success or `pos_type(off_type(-1))` on failure. ### Notes `seekpos()` is called by `[std::basic\_streambuf::pubseekpos()](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos")`, which is called by the single-argument versions of `[std::basic\_istream::seekg()](../basic_istream/seekg "cpp/io/basic istream/seekg")` and `[std::basic\_ostream::seekp()](../basic_ostream/seekp "cpp/io/basic ostream/seekp")`. ### Example ``` #include <sstream> #include <iostream> struct mybuf : std::stringbuf { mybuf(const std::string& str) : std::stringbuf(str) {} pos_type seekpos(pos_type sp, std::ios_base::openmode which) { std::cout << "Before seekpos(" << sp << "), size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; pos_type rc = std::stringbuf::seekpos(sp, which); std::cout << "seekpos() returns " << rc << ".\nAfter the call, " << "size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; return rc; } }; int main() { mybuf buf("12345"); std::iostream stream(&buf); stream.seekg(2); } ``` Output: ``` Before seekpos(2), size of the get area is 5 with 5 read positions available. seekpos() returns 2. After the call, size of the get area is 5 with 3 read positions available. ``` ### See also | | | | --- | --- | | [pubseekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](../basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekpos](../strstreambuf/seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::strstreambuf`) | cpp std::swap(std::basic_stringbuf) std::swap(std::basic\_stringbuf) ================================ | Defined in header `[<sstream>](../../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_stringbuf<CharT,Traits,Alloc>& lhs, std::basic_stringbuf<CharT,Traits,Alloc>& rhs ); ``` | | (since C++11) (until C++20) | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_stringbuf<CharT,Traits,Alloc>& lhs, std::basic_stringbuf<CharT,Traits,Alloc>& rhs ) noexcept(noexcept(lhs.swap(rhs))); ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")` objects whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic stringbuf/swap") (C++11) | swaps two basic\_stringbuf objects (public member function) | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::basic_stringbuf std::basic\_stringbuf<CharT,Traits,Allocator>::basic\_stringbuf =============================================================== | | | | | --- | --- | --- | | ``` basic_stringbuf() : basic_stringbuf(std::ios_base::in | std::ios_base::out) { } ``` | (1) | (since C++11) | | | (2) | | | ``` explicit basic_stringbuf( std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (until C++11) | | ``` explicit basic_stringbuf( std::ios_base::openmode which ); ``` | (since C++11) | | ``` explicit basic_stringbuf( const std::basic_string<CharT, Traits, Allocator>& s, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (3) | | | ``` basic_stringbuf( const basic_stringbuf& rhs ) = delete; ``` | (4) | (since C++11) | | ``` basic_stringbuf( basic_stringbuf&& rhs ); ``` | (5) | (since C++11) | | ``` explicit basic_stringbuf( const Allocator& a ) : basic_stringbuf(std::ios_base::in | std::ios_base::out, a) { } ``` | (6) | (since C++20) | | ``` basic_stringbuf( std::ios_base::openmode which, const Allocator& a ); ``` | (7) | (since C++20) | | ``` explicit basic_stringbuf( std::basic_string<CharT, Traits, Allocator>&& s, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (8) | (since C++20) | | ``` template<class SAlloc> basic_stringbuf( const std::basic_string<CharT, Traits, SAlloc>& s, const Allocator& a ) : basic_stringbuf(s, std::ios_base::in | std::ios_base::out, a ) { } ``` | (9) | (since C++20) | | ``` template<class SAlloc> basic_stringbuf( const std::basic_string<CharT, Traits, SAlloc>& s, std::ios_base::openmode, const Allocator& a ); ``` | (10) | (since C++20) | | ``` template<class SAlloc> explicit basic_stringbuf( const std::basic_string<CharT, Traits, SAlloc>& s, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (11) | (since C++20) | | ``` basic_stringbuf( basic_stringbuf&& rhs, const Allocator& a ); ``` | (12) | (since C++20) | 1) Default constructor. It is implementation-defined whether the sequence pointers (`eback()`, `gptr()`, `egptr()`, `pbase()`, `pptr()`, `epptr()`) are initialized to null pointers. 2) Constructs a `std::basic_stringbuf` object: initializes the base class by calling the default constructor of `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")`, initializes the character sequence with an empty string, and sets the mode to `which`. 3) Constructs a `std::basic_stringbuf` object by performing the same initialization as (1), followed by initializing the associated character sequence as if by calling `[str(s)](str "cpp/io/basic stringbuf/str")`. 4) The copy constructor is deleted; `std::basic_stringbuf` is not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") 5) Move-constructs a `std::basic_stringbuf` object by moving all state from another `std::basic_stringbuf` object `rhs`, including the associated string, the open mode, the locale, and all other state. After the move, the six pointers of `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` in `*this` are guaranteed to be different from the corresponding pointers in the moved-from `rhs` unless null. 6-7) Same as (1-2), except that `a` is used to construct the associated string. 8) Same as (3), except that `std::move(s)` is used to construct the associated string. 9-10) Constructs a `std::basic_stringbuf` object by performing the same initialization as (1), followed by initializing the associated string with content of `s`, using `a` as its allocator. 11) Same as (3), except the type of `s`'s allocator is not `Allocator`. This overload participates in overload resolution only if `SAlloc` and `Allocator` are not the same type. 12) Same as (5), except that `a` is used to construct the associated string. ### Parameters | | | | | --- | --- | --- | | s | - | a `basic_string` used to initialize the buffer | | a | - | another allocator used to construct the internal `basic_string` | | rhs | - | another `basic_stringbuf` | | which | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Notes Typically called by the constructor of `[std::basic\_stringstream](../basic_stringstream "cpp/io/basic stringstream")`. The level of support for the open modes other than `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` and `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` varies among implementations. C++11 explicitly specifies the support for `[std::ios\_base::ate](../ios_base/openmode "cpp/io/ios base/openmode")` in `[str()](str "cpp/io/basic stringbuf/str")` and in this constructor, but `[std::ios\_base::app](../ios_base/openmode "cpp/io/ios base/openmode")`, `[std::ios\_base::trunc](../ios_base/openmode "cpp/io/ios base/openmode")`, and `[std::ios\_base::binary](../ios_base/openmode "cpp/io/ios base/openmode")` have different effects on different implementations. ### Example Demonstrates calling the constructor of basic\_stringbuf directly. ``` #include <iostream> #include <sstream> int main() { // default constructor (mode = in|out) std::stringbuf buf1; buf1.sputc('1'); std::cout << &buf1 << '\n'; // string constructor in at-end mode (C++11) std::stringbuf buf2("test", std::ios_base::in | std::ios_base::out | std::ios_base::ate); buf2.sputc('1'); std::cout << &buf2 << '\n'; // append mode test (results differ among compilers) std::stringbuf buf3("test", std::ios_base::in | std::ios_base::out | std::ios_base::app); buf3.sputc('1'); buf3.pubseekpos(1); buf3.sputc('2'); std::cout << &buf3 << '\n'; } ``` Output: ``` 1 test1 est12 (Sun Studio) 2st1 (GCC) ``` ### 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 | ### See also | | | | --- | --- | | [(constructor)](../basic_stringstream/basic_stringstream "cpp/io/basic stringstream/basic stringstream") | constructs the string stream (public member function of `std::basic_stringstream<CharT,Traits,Allocator>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::overflow std::basic\_stringbuf<CharT,Traits,Allocator>::overflow ======================================================= | | | | | --- | --- | --- | | ``` protected: virtual int_type overflow ( int_type c = Traits::eof() ); ``` | | | Appends the character `c` to the output character sequence. If `c` is the end-of-file indicator (`traits::eq_int_type(c,traits::eof()) == true`), then there is no character to append. The function does nothing and returns an unspecified value other than `traits::eof()`. Otherwise, if the output sequence has a write position available or this function can successfully make a write position available, then calls `sputc(c)` and returns `c`. This function can make a write position available if the stringbuf is open for output (`(mode & ios_base::out) != 0`): in this case, it reallocates (or initially allocates) the buffer big enough to hold the entire current buffer plus at least one more character. If the stringbuf is also open for input (`(mode & ios_base::in) != 0`), then `overflow` also increases the size of the get area by moving `egptr()` to point just past the new write position. ### Parameters | | | | | --- | --- | --- | | c | - | the character to store in the put area | ### Return value `Traits::eof()` to indicate failure, `c` if the character `c` was successfully appended, or some value other than `Traits::eof()` if called with `Traits::eof()` as the argument. ### Notes This function is different from a typical `overflow()` which moves the contents of the buffer to the associated character sequence because for a `[std::basic\_stringbuf](http://en.cppreference.com/w/cpp/io/basic_stringbuf)`, the buffer and the associated sequence are one and the same. ### Example In the implementation used to execute this example, overflow() over-allocates the put area to 512 bytes: a call to str() would only return the four initialized bytes, but the next 508 calls to sputc() would not require new calls to overflow(). ``` #include <sstream> #include <iostream> struct mybuf : std::stringbuf { mybuf(const std::string& new_str, std::ios_base::openmode which = std::ios_base::in|std::ios_base::out) : std::stringbuf(new_str, which) {} int_type overflow(int_type c = EOF) override { std::cout << "stringbuf::overflow('" << char(c) << "') called\n" << "Before: size of get area: " << egptr() - eback() << '\n' << " size of put area: " << epptr() - pbase() << '\n'; int_type ret = std::stringbuf::overflow(c); std::cout << "After : size of get area: " << egptr() - eback() << '\n' << " size of put area: " << epptr() - pbase() << '\n'; return ret; } }; int main() { std::cout << "read-write stream:\n"; mybuf sbuf(" "); // read-write stream std::iostream stream(&sbuf); stream << 1234; std::cout << sbuf.str() << '\n'; std::cout << "\nread-only stream:\n"; mybuf ro_buf(" ", std::ios_base::in); // read-only stream std::iostream ro_stream(&ro_buf); ro_stream << 1234; std::cout << "\nwrite-only stream:\n"; mybuf wr_buf(" ", std::ios_base::out); // write-only stream std::iostream wr_stream(&wr_buf); wr_stream << 1234; } ``` Possible output: ``` read-write stream: stringbuf::overflow('4') called Before: size of get area: 3 size of put area: 3 After : size of get area: 4 size of put area: 512 1234 read-only stream: stringbuf::overflow('1') called Before: size of get area: 3 size of put area: 0 After : size of get area: 3 size of put area: 0 write-only stream: stringbuf::overflow('4') called Before: size of get area: 0 size of put area: 3 After : size of get area: 0 size of put area: 512 ``` ### See also | | | | --- | --- | | [overflow](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](underflow "cpp/io/basic stringbuf/underflow") [virtual] | returns the next character available in the input sequence (virtual protected member function) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::view std::basic\_stringbuf<CharT,Traits,Allocator>::view =================================================== | | | | | --- | --- | --- | | ``` std::basic_string_view<CharT, Traits> view() const noexcept; ``` | | (since C++20) | Creates and returns a `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying character sequence. * For input-only streams, the returned view represents the range `[eback(), egptr())`. * For input/output or output-only streams, references the characters from `pbase()` to the last character in the sequence regardless of `egptr()` and `epptr()`. * If the stream is neither input nor output, returns `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>{}`. The member character sequence in a buffer open for writing can be over-allocated for efficiency purposes. In that case, only the *initialized characters* are referenced: these characters are the ones that were obtained from the string argument of the constructor, the string argument used by the most recent call to a setter overload of `str()`, or from a write operation. A typical implementation that uses over-allocation maintains a high-watermark pointer to track the end of the initialized part of the buffer and the returned view references the characters from `pbase()` to the high-watermark pointer. ### Parameters (none). ### Return value A view over the underlying character sequence. ### Notes Using of the return value is undefined behavior if the underlying character sequence is destroyed or invalidated, unless the return value is empty. This function is typically accessed through `std::basic_istringstream::view()`, `std::basic_ostringstream::view()`, or `std::basic_stringstream::view()`. ### See also | | | | --- | --- | | [str](str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function) | | [operator basic\_string\_view](../../string/basic_string/operator_basic_string_view "cpp/string/basic string/operator basic string view") (C++17) | returns a non-modifiable string\_view into the entire string (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::operator= std::basic\_stringbuf<CharT,Traits,Allocator>::operator= ======================================================== | | | | | --- | --- | --- | | ``` std::basic_stringbuf& operator=( std::basic_stringbuf&& rhs ); ``` | (1) | (since C++11) | | ``` std::basic_stringbuf& operator=( const std::basic_stringbuf& rhs ) = delete; ``` | (2) | | 1) Move assignment operator: Moves the contents of `rhs` into `*this`. After the move, `*this` has the associated string, the open mode, the locale, and all other state formerly held by `rhs`. The six pointers of `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` in `*this` are guaranteed to be different from the corresponding pointers in the moved-from `rhs` unless null. 2) The copy assignment operator is deleted; `basic_stringbuf` is not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | rhs | - | another `basic_stringbuf` that will be moved from | ### Return value `*this`. ### Example ``` #include <sstream> #include <string> #include <iostream> int main() { std::istringstream one("one"); std::ostringstream two("two"); std::cout << "Before move, one = \"" << one.str() << '"' << " two = \"" << two.str() << "\"\n"; *one.rdbuf() = std::move(*two.rdbuf()); std::cout << "After move, one = \"" << one.str() << '"' << " two = \"" << two.str() << "\"\n"; } ``` Output: ``` Before move, one = "one" two = "two" After move, one = "two" two = "" ``` ### See also | | | | --- | --- | | [(constructor)](basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function) |
programming_docs
cpp std::basic_stringbuf<CharT,Traits,Allocator>::setbuf std::basic\_stringbuf<CharT,Traits,Allocator>::setbuf ===================================================== | | | | | --- | --- | --- | | ``` protected: virtual std::basic_streambuf<CharT, Traits>* setbuf( char_type* s, std::streamsize n ) ``` | | | If `s` is a null pointer and `n` is zero, this function has no effect. Otherwise, the effect is implementation-defined: some implementations do nothing, while some implementations clear the `[std::string](../../string/basic_string "cpp/string/basic string")` member currently used as the buffer and begin using the user-supplied character array of size `n`, whose first element is pointed to by `s`, as the buffer and the input/output character sequence. This function is protected virtual, it may only be called through `pubsetbuf()` or from member functions of a user-defined class derived from `std::basic_stringbuf`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the first CharT in the user-provided buffer or null | | n | - | the number of CharT elements in the user-provided buffer or zero | ### Return value `this`. ### Notes The deprecated stream buffer `[std::strstreambuf](http://en.cppreference.com/w/cpp/io/strstreambuf)` or the boost.IOStreams device [`boost::basic_array`](http://www.boost.org/doc/libs/release/libs/iostreams/doc/classes/array.html#array) may be used to implement I/O buffering over a user-provided char array in portable manner. ### Example Test for the stringstream's setbuf functionality. ``` #include <iostream> #include <sstream> int main() { std::ostringstream ss; char c[1024] = {}; ss.rdbuf()->pubsetbuf(c, 1024); ss << 3.14 << '\n'; std::cout << c << '\n'; } ``` Output: ``` 3.14 (on GNU g++/libstdc++ and SunPro C++/roguewave) <nothing> (on MS Visual Studio 2010, SunPro C++/stlport4, CLang++/libc++) ``` ### See also | | | | --- | --- | | [pubsetbuf](../basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::seekoff std::basic\_stringbuf<CharT,Traits,Allocator>::seekoff ====================================================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekoff( off_type off, ios_base::seekdir dir, ios_base::openmode which = ios_base::in | ios_base::out ); ``` | | | Repositions `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` and/or `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, if possible, to the position that corresponds to exactly `off` characters from beginning, end, or current position of the get and/or put area of the buffer. * If `which` includes `ios_base::in` and this buffer is open for reading (that is, if `((which & ios_base::in) == ios_base::in`), then repositions the read pointer `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` inside the get area as described below * If `which` includes `ios_base::out` and this buffer is open for writing (that is, `(which & ios_base::out) == ios_base::out`), then repositions the write pointer `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` inside the put area as described below * If `which` includes both `ios_base::in` and `ios_base::out` and the buffer is open for both reading and writing (`(which & (ios_base::in | ios_base::out)) == (ios_base::in | ios_base::out)`), and `dir` is either `ios_base::beg` or `ios_base::end`, then repositions both read and write pointers as described below. * Otherwise, this function fails. If the pointer (either `gptr` or `pptr` or both) is repositioned, it is done as follows: 1) If the pointer to be repositioned is a null pointer and the new offset `newoff` would be non-zero, this function fails. 2) The new pointer offset `newoff` of type `off_type` is determined a) if `dir == ios_base::beg`, then `newoff` is zero b) if `dir == ios_base::cur`, then `newoff` is the current position of the pointer (`gptr() - eback()` or `pptr() - pbase()`) c) if `dir == ios_base::end`, then `newoff` is the length of the entire initialized part of the buffer (if overallocation is used, the high watermark pointer minus the beginning pointer) 3) If `newoff + off < 0` (the repositioning would move the pointer to before the beginning of the buffer) or if `newoff + off` would point past the end of the buffer (or past the last initialized character in the buffer if overallocation is used), the function fails 4) Otherwise, the pointer is assigned as if by `gptr() = eback() + newoff + off` or `pptr() = pbase() + newoff + off` ### Parameters | | | | | --- | --- | --- | | off | - | relative position to set the next pointer(s) to | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `pos_type(newoff)` on success, `pos_type(off_type(-1))` on failure and if pos\_type cannot represent the resulting stream position. ### Example ``` #include <iostream> #include <sstream> int main() { std::stringstream ss("123"); // in/out std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // absolute positioning both pointers ss.rdbuf()->pubseekoff(1, std::ios_base::beg); // move both 1 forward std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // try to move both pointers 1 forward from current position if (-1 == ss.rdbuf()->pubseekoff(1, std::ios_base::cur)) std::cout << "moving both pointers from current position failed\n"; std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // move the write pointer 1 forward, but not the read pointer // can also be called as ss.seekp(1, std::ios_base::cur); ss.rdbuf()->pubseekoff(1, std::ios_base::cur, std::ios_base::out); std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; ss << 'a'; // write at put position std::cout << "Wrote 'a' at put position, the buffer is now " << ss.str() << '\n'; char ch; ss >> ch; std::cout << "reading at get position gives '" << ch << "'\n"; } ``` Output: ``` put pos = 0 get pos = 0 put pos = 1 get pos = 1 moving both pointers from current position failed put pos = 1 get pos = 1 put pos = 2 get pos = 1 Wrote 'a' at put position, the buffer is now 12a reading at get position gives '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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | `seekoff` returned an undefinedinvalid stream position on failure | `pos_type(off_type(-1))`is returned on failure | ### See also | | | | --- | --- | | [pubseekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | | [seekoff](../basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekoff](../strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::strstreambuf`) | cpp std::basic_stringbuf<CharT,Traits,Allocator>::pbackfail std::basic\_stringbuf<CharT,Traits,Allocator>::pbackfail ======================================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type pbackfail( int_type c = Traits::eof() ) ``` | | | This protected virtual function is called by the public functions [`basic_streambuf::sungetc`](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") and [`basic_streambuf::sputbackc`](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") (which, in turn, are called by [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") and [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback")). 1) The caller is requesting that the get area is backed up by one character (`pbackfail()` is called with no arguments or with `Traits::eof()` as the argument) a) First, checks if there is a putback position, and if there really isn't, fails. (stringbuf has no external character source to re-read) b) If the caller was wrong and the putback position is in fact available, simply decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"), e.g. by calling `gbump(-1)`. 2) The caller attempts to putback a different character from the one retrieved earlier (`pbackfail()` is called with the character that needs to be put back), in which case a) First, checks if there is a putback position, and if there isn't, fails. b) Then checks what character is in the putback position. If the character held there is already equal to `c`, as determined by `Traits::eq(to_char_type(c), gptr()[-1])`, then simply decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"). c) Otherwise, if the buffer is open for reading only, fails. d) Otherwise, if the buffer is open for writing (`mode && [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode)` is nonzero), then decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr") and writes `c` to the location pointed to gptr() after adjustment. ### Parameters | | | | | --- | --- | --- | | c | - | the character to put back, or Traits::eof() to indicate that backing up of the get area is requested | ### Return value `c` on success except if `c` was `Traits::eof()`, in which case `Traits::not_eof(c)` is returned. `Traits::eof()` on failure. ### Example ### See also | | | | --- | --- | | [pbackfail](../basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputbackc](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [unget](../basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](../basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::ios_base::precision std::ios\_base::precision ========================= | | | | | --- | --- | --- | | ``` streamsize precision() const; ``` | (1) | | | ``` streamsize precision( streamsize new_precision ); ``` | (2) | | Manages the precision (i.e. how many digits are generated) of floating point output performed by `[std::num\_put::do\_put](../../locale/num_put/put "cpp/locale/num put/put")`. 1) Returns the current precision. 2) Sets the precision to the given one. Returns the previous precision. The default precision, as established by `[std::basic\_ios::init](../basic_ios/init "cpp/io/basic ios/init")`, is 6. ### Parameters | | | | | --- | --- | --- | | new\_precision | - | new precision setting | ### Return value the precision before the call to the function. ### Example ``` #include <iostream> int main() { const double d = 1.2345678901234; std::cout << "The default precision is " << std::cout.precision() << "\n\n"; std::cout << "With default precision d is " << d << '\n'; std::cout.precision(12); std::cout << "With high precision d is " << d << '\n'; } ``` Output: ``` The default precision is 6 With default precision d is 1.23457 With high precision d is 1.23456789012 ``` ### See also | | | | --- | --- | | [width](width "cpp/io/ios base/width") | manages field width (public member function) | | [setprecision](../manip/setprecision "cpp/io/manip/setprecision") | changes floating-point precision (function) | cpp std::ios_base::flags std::ios\_base::flags ===================== | | | | | --- | --- | --- | | ``` fmtflags flags() const; ``` | (1) | | | ``` fmtflags flags( fmtflags flags ); ``` | (2) | | Manages format flags. 1) returns current formatting setting. 2) replaces current settings with given ones. ### Parameters | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | flags | - | new formatting setting. It can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`dec`](fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](../manip/hex "cpp/io/manip/hex")` | | [`oct`](fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](../manip/hex "cpp/io/manip/hex")` | | [`hex`](fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](../manip/hex "cpp/io/manip/hex")` | | [`basefield`](fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](../manip/left "cpp/io/manip/left")` | | [`right`](fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](../manip/left "cpp/io/manip/left")` | | [`internal`](fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](../manip/left "cpp/io/manip/left")` | | [`adjustfield`](fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](../manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](../manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](../manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](../manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](../manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](../manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](../manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](../manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](../manip/uppercase "cpp/io/manip/uppercase")` | | ### Return value the formatting flags before the call to the function. ### Example ### See also | | | | --- | --- | | [setf](setf "cpp/io/ios base/setf") | sets specific format flag (public member function) | | [unsetf](unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function) | cpp std::ios_base::pword std::ios\_base::pword ===================== | | | | | --- | --- | --- | | ``` void*& pword( int index ); ``` | | | First, allocates or resizes the private storage (dynamic array of `void*` or another indexable data structure) sufficiently to make `index` a valid index, then returns a reference to the `void*` element of the private storage with the index `index`. The reference may be invalidated by any operation on this `ios_base` object, including another call to `pword()`, but the stored values are retained, so that reading from `pword(index)` with the same index later will produce the same value until the next call to `[std::basic\_ios::copyfmt()](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt")`. The value can be used for any purpose. The index of the element must be obtained by `[xalloc()](xalloc "cpp/io/ios base/xalloc")`, otherwise the behavior is undefined. New elements are initialized to a [null pointer](../../language/pointer#Null_pointers "cpp/language/pointer"). If the function fails (possibly caused by an allocation failure) and `*this` is a base class subobject of a `basic_ios<>` object or subobject, calls `[std::basic\_ios](http://en.cppreference.com/w/cpp/io/basic_ios)<>::setstate(badbit)` which may throw `[std::ios\_base::failure](failure "cpp/io/ios base/failure")`. ### Parameters | | | | | --- | --- | --- | | index | - | index value of the element | ### Return value A reference to the element. ### Exceptions May throw `[std::ios\_base::failure](failure "cpp/io/ios base/failure")` when setting the badbit. ### Notes If the pointers stored in `pword` require management, `[register\_callback()](register_callback "cpp/io/ios base/register callback")` may be used to install handlers that execute deep copy or deallocation as needed. ### Example Uses base class pword storage for runtime type identification of derived stream objects. ``` #include <iostream> template<class charT, class traits = std::char_traits<charT> > class mystream : public std::basic_ostream<charT, traits> { public: static const int xindex; mystream(std::basic_ostream<charT, traits>& ostr) : std::basic_ostream<charT, traits>(ostr.rdbuf()) { this->pword(xindex) = this; } void myfn() { *this << "[special handling for mystream]"; } }; // each specialization of mystream obtains a unique index from xalloc() template<class charT, class traits> const int mystream<charT, traits>::xindex = std::ios_base::xalloc(); // This I/O manipulator will be able to recognize ostreams that are mystreams // by looking up the pointer stored in pword template<class charT, class traits> std::basic_ostream<charT, traits>& mymanip(std::basic_ostream<charT, traits>& os) { if (os.pword(mystream<charT, traits>::xindex) == &os) static_cast<mystream<charT, traits>&>(os).myfn(); return os; } int main() { std::cout << "cout, narrow-character test " << mymanip << '\n'; mystream<char> myout(std::cout); myout << "myout, narrow-character test " << mymanip << '\n'; std::wcout << "wcout, wide-character test " << mymanip << '\n'; mystream<wchar_t> mywout(std::wcout); mywout << "mywout, wide-character test " << mymanip << '\n'; } ``` Output: ``` cout, narrow-character test myout, narrow-character test [special handling for mystream] wcout, wide-character test mywout, wide-character test [special handling for mystream] ``` ### 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 36](https://cplusplus.github.io/LWG/issue36) | C++98 | the stored value might not beretained if the reference is invalidated | the stored value is retaineduntil the next call of `copyfmt()` | | [LWG 41](https://cplusplus.github.io/LWG/issue41) | C++98 | the function set badbit by itself on failure,but `ios_base` does not provide such interface | badbit is set by `basic_ios`(if `*this` is its base class subobject) | ### See also | | | | --- | --- | | [iword](iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function) | | [xalloc](xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to **`pword()`** and [`iword()`](iword "cpp/io/ios base/iword") (public static member function) |
programming_docs
cpp std::ios_base::setf std::ios\_base::setf ==================== | | | | | --- | --- | --- | | ``` fmtflags setf( fmtflags flags ); ``` | (1) | | | ``` fmtflags setf( fmtflags flags, fmtflags mask ); ``` | (2) | | Sets the formatting flags to specified settings. 1) Sets the formatting flags identified by `flags`. Effectively the following operation is performed `fl = fl | flags` where `fl` defines the state of internal formatting flags. 2) Clears the formatting flags under `mask`, and sets the cleared flags to those specified by `flags`. Effectively the following operation is performed `fl = (fl & ~mask) | (flags & mask)` where `fl` defines the state of internal formatting flags. ### Parameters | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | flags, mask | - | new formatting setting. `mask` defines which flags can be altered, `flags` defines which flags of those to be altered should be set (others will be cleared). Both parameters can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`dec`](fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](../manip/hex "cpp/io/manip/hex")` | | [`oct`](fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](../manip/hex "cpp/io/manip/hex")` | | [`hex`](fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](../manip/hex "cpp/io/manip/hex")` | | [`basefield`](fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](../manip/left "cpp/io/manip/left")` | | [`right`](fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](../manip/left "cpp/io/manip/left")` | | [`internal`](fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](../manip/left "cpp/io/manip/left")` | | [`adjustfield`](fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](../manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](../manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](../manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](../manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](../manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](../manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](../manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](../manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](../manip/uppercase "cpp/io/manip/uppercase")` | | ### Return value the formatting flags before the call to the function. ### Example ``` #include <iostream> #include <iomanip> const double PI = 3.1415926535; int main() { const int WIDTH = 15; std::cout.setf(std::ios::right); //equivalent: cout << right; std::cout << std::setw(WIDTH/2) << "radius" << std::setw(WIDTH) << "circumference" << '\n'; std::cout.setf(std::ios::fixed); for (double radius = 1; radius <= 6; radius += 0.5) { std::cout << std::setprecision(1) << std::setw(WIDTH/2) << radius << std::setprecision(2) << std::setw(WIDTH) << (2 * PI * radius) << '\n'; } } ``` Output: ``` radius circumference 1.0 6.28 1.5 9.42 2.0 12.57 2.5 15.71 3.0 18.85 3.5 21.99 4.0 25.13 4.5 28.27 5.0 31.42 5.5 34.56 6.0 37.70 ``` ### See also | | | | --- | --- | | [flags](flags "cpp/io/ios base/flags") | manages format flags (public member function) | | [unsetf](unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function) | cpp std::ios_base::ios_base std::ios\_base::ios\_base ========================= | | | | | --- | --- | --- | | | (1) | | | ``` private: ios_base( const ios_base& ); ``` | (until C++11) | | ``` public: ios_base( const ios_base& ) = delete; ``` | (since C++11) | | ``` protected: ios_base(); ``` | (2) | | 1) The copy constructor is private (until C++11)deleted (since C++11): streams are not copyable. 2) The default constructor is protected: only derived classes may construct `std::ios_base`. The internal state is undefined after the construction. The derived class must call [`basic_ios::init()`](../basic_ios/init "cpp/io/basic ios/init") to complete initialization before first use or before destructor; otherwise the behavior is undefined. ### Notes The same applies to the constructors of the next class in the I/O hierarchy, `[std::basic\_ios](../basic_ios "cpp/io/basic ios")`. Further-derived classes (`[std::istream](../basic_istream "cpp/io/basic istream")` and `[std::ostream](../basic_ostream "cpp/io/basic ostream")`) are always constructed with a concrete streambuffer object and call [`basic_ios::init()`](../basic_ios/init "cpp/io/basic ios/init"), possibly more than once, to complete initialization of their virtual base. ### 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 50](https://cplusplus.github.io/LWG/issue50) | C++98 | the copy constructor was not specified | specified as private | cpp std::ios_base::xalloc std::ios\_base::xalloc ====================== | | | | | --- | --- | --- | | ``` static int xalloc(); ``` | | | Returns a unique (program-wide) index value that can be used to access one `long` and one `void*` elements in the private storage of `std::ios_base` by calling `[iword()](iword "cpp/io/ios base/iword")` and `[pword()](pword "cpp/io/ios base/pword")`. The call to `xalloc` does not allocate memory. This function is thread-safe; concurrent access by multiple threads does not result in a data race. (since C++14). Effectively increments a private static data member of `std::ios_base`, as if by executing `return index++;`, if `index` is the name of that static member (which may be `[std::atomic](../../atomic/atomic "cpp/atomic/atomic")` to support concurrent access by multiple threads, or otherwise synchronized) (since C++14). ### Parameters (none). ### Return value Unique integer for use as pword/iword index. ### Example Uses base class pword storage for runtime type identification of derived stream objects. ``` #include <iostream> template<class charT, class traits = std::char_traits<charT> > class mystream : public std::basic_ostream<charT, traits> { public: static const int xindex; mystream(std::basic_ostream<charT, traits>& ostr) : std::basic_ostream<charT, traits>(ostr.rdbuf()) { this->pword(xindex) = this; } void myfn() { *this << "[special handling for mystream]"; } }; // each specialization of mystream obtains a unique index from xalloc() template<class charT, class traits> const int mystream<charT, traits>::xindex = std::ios_base::xalloc(); // This I/O manipulator will be able to recognize ostreams that are mystreams // by looking up the pointer stored in pword template<class charT, class traits> std::basic_ostream<charT, traits>& mymanip(std::basic_ostream<charT, traits>& os) { if (os.pword(mystream<charT, traits>::xindex) == &os) static_cast<mystream<charT, traits>&>(os).myfn(); return os; } int main() { std::cout << "cout, narrow-character test " << mymanip << '\n'; mystream<char> myout(std::cout); myout << "myout, narrow-character test " << mymanip << '\n'; std::wcout << "wcout, wide-character test " << mymanip << '\n'; mystream<wchar_t> mywout(std::wcout); mywout << "mywout, wide-character test " << mymanip << '\n'; } ``` Output: ``` cout, narrow-character test myout, narrow-character test [special handling for mystream] wcout, wide-character test mywout, wide-character test [special handling for mystream] ``` ### See also | | | | --- | --- | | [pword](pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function) | | [iword](iword "cpp/io/ios base/iword") | resizes the private storage if necessary and access to the `long` element at the given index (public member function) | cpp std::ios_base::Init std::ios\_base::Init ==================== | | | | | --- | --- | --- | | ``` class Init; ``` | | | This class is used to ensure that the default C++ streams (`[std::cin](../cin "cpp/io/cin")`, `[std::cout](../cout "cpp/io/cout")`, etc.) are properly initialized and destructed. The class tracks how many instances of it are created and initializes the C++ streams when the first instance is constructed as well as flushes the output streams when the last instance is destructed. The header `<iostream>` behaves as if it defines (directly or indirectly) an instance of `std::ios_base::Init` with static storage duration: this makes it safe to access the standard I/O streams in the constructors and destructors of static objects with [ordered initialization](../../language/initialization#Non-local_variables "cpp/language/initialization") (as long as `#include <iostream>` is included in the translation unit before these objects were defined). ### Member functions | | | | --- | --- | | (constructor) | if `*this` is the first instance created, initializes the default C++ streams (public member function) | | (destructor) | if `*this` is the last instance destroyed, flushes the default C++ streams (public member function) | ### See also | | | | --- | --- | | [cinwcin](../cin "cpp/io/cin") | reads from the standard C input stream `[stdin](../c/std_streams "cpp/io/c/std streams")` (global object) | | [coutwcout](../cout "cpp/io/cout") | writes to the standard C output stream `[stdout](../c/std_streams "cpp/io/c/std streams")`(global object) | | [cerrwcerr](../cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](../c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [clogwclog](../clog "cpp/io/clog") | writes to the standard C error stream `[stderr](../c/std_streams "cpp/io/c/std streams")`(global object) | cpp std::ios_base::imbue std::ios\_base::imbue ===================== | | | | | --- | --- | --- | | ``` std::locale imbue( const std::locale& loc ); ``` | | | Sets the associated locale of the stream to the given one. Before returning, each function, registered by `[register\_callback()](register_callback "cpp/io/ios base/register callback")` is called with `imbue_event` as a parameter. ### Parameters | | | | | --- | --- | --- | | loc | - | new locale to associate the stream to | ### Return value The locale object associated with the stream before the operation. ### 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 47](https://cplusplus.github.io/LWG/issue47) | C++98 | the return value was misspecified as the return value of `getloc()` | corrected | ### See also | | | | --- | --- | | [getloc](getloc "cpp/io/ios base/getloc") | returns current locale (public member function) | cpp std::ios_base::failure std::ios\_base::failure ======================= | Defined in header `[<ios>](../../header/ios "cpp/header/ios")` | | | | --- | --- | --- | | ``` class failure; ``` | | | The class `std::ios_base::failure` defines an exception object that is thrown on failure by the functions in the Input/Output library. | | | | --- | --- | | `std::ios_base::failure` may be defined either as a member class of `[std::ios\_base](../ios_base "cpp/io/ios base")` or as a synonym (typedef) for another class with equivalent functionality. | (since C++17) | | | | | --- | --- | | std-ios base-failure-2003-inheritance.svg Inheritance diagram. | (until C++11) | | std-ios base-failure-inheritance.svg Inheritance diagram. | (since C++11) | ### Member functions | | | | --- | --- | | (constructor) | constructs a new `failure` object with the given message (public member function) | | operator= | replaces the `failure` object (public member function) | | what | returns the explanatory string (public member function) | std::ios\_base::failure::failure --------------------------------- | | | | | --- | --- | --- | | | (1) | | | ``` explicit failure( const std::string& message ); ``` | (until C++11) | | ``` explicit failure( const std::string& message, const std::error_code& ec = std::io_errc::stream ); ``` | (since C++11) | | ``` explicit failure( const char* message, const std::error_code& ec = std::io_errc::stream ); ``` | (2) | (since C++11) | | | (3) | | | ``` failure( const failure& other ); ``` | (until C++11) | | ``` failure( const failure& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object using `message` as explanation string which can later be retrieved using [`what()`](../../error/exception/what "cpp/error/exception/what"). `ec` is used to identify the specific reason for the failure. (since C++11) 3) Copy constructor. Initialize the contents with those of `other`. If `*this` and `other` both have dynamic type `std::ios_base::failure` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | message | - | explanatory string | | ec | - | error code to identify the specific reason for the failure | | other | - | another `failure` to copy | ### Notes Because copying `std::ios_base::failure` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::ios\_base::failure::operator= ----------------------------------- | | | | | --- | --- | --- | | ``` failure& operator=( const failure& other ); ``` | | (until C++11) | | ``` failure& operator=( const failure& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::ios_base::failure` 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::ios\_base::failure::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::system\_error](../../error/system_error "cpp/error/system error") ---------------------------------------------------------------------------------------- ### Member functions | | | | --- | --- | | [code](../../error/system_error/code "cpp/error/system error/code") | returns error code (public member function of `std::system_error`) | | [what](../../error/system_error/what "cpp/error/system error/what") [virtual] | returns an explanatory string (virtual public member function of `std::system_error`) | 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`) | ### Example ``` #include <iostream> #include <fstream> int main() { std::ifstream f("doesn't exist"); try { f.exceptions(f.failbit); } catch (const std::ios_base::failure& e) { std::cout << "Caught an ios_base::failure.\n" << "Explanatory string: " << e.what() << '\n' << "Error code: " << e.code() << '\n'; } } ``` Possible output: ``` Caught an ios_base::failure. Explanatory string: ios_base::clear: unspecified iostream_category error Error code: iostream:1 ``` ### 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 48](https://cplusplus.github.io/LWG/issue48) | C++98 | the constructor overload (1) initialized the base class `[std::exception](../../error/exception "cpp/error/exception")`with `msg`, but the base class does not have a matching constructor | correspondingdescription removed | ### See also | | | | --- | --- | | [io\_errc](../io_errc "cpp/io/io errc") (C++11) | the IO stream error codes (enum) |
programming_docs
cpp std::ios_base::register_callback std::ios\_base::register\_callback ================================== | | | | | --- | --- | --- | | ``` void register_callback( event_callback function, int index ); ``` | | | Registers a user-defined function which will be called by `[imbue()](imbue "cpp/io/ios base/imbue")`, `[std::basic\_ios::copyfmt()](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt")` and `~ios_base()`. Every registered callback is called every time: the event type (a value of type `[event](event "cpp/io/ios base/event")`) is passed as its first argument, and may be used to distinguish between the callers. The callbacks are called in the reverse order of registration (in other words, `register_callback()` pushes a callback pair on the callback stack). If `register_callback()` is called from within a callback function to add a new callback, the new callback is only called on the next event. The user-defined callback function is not allowed to throw exceptions. ### Parameters | | | | | --- | --- | --- | | function | - | the function which will be called on event, supplied as a function pointer of type [event\_callback](event_callback "cpp/io/ios base/event callback") | | index | - | custom parameter which will be passed to the function | ### Return value (none). ### Notes Once registered, a callback cannot be deregistered: it remains a part of the stream object for the rest of its lifetime. If the behavior of a callback needs to change, it may be controlled through `[iword()](iword "cpp/io/ios base/iword")` or `[pword()](pword "cpp/io/ios base/pword")`. If the same function is registered multiple times, it is called multiple times. The integer value that is stored together with the callback is typically an index obtained from `[xalloc()](xalloc "cpp/io/ios base/xalloc")`. ### Example demonstrates the use of register\_callback to update locale-dependent cached values that are used by a custom output operator. ``` #include <iostream> #include <locale> #include <functional> // cached locale-specific message and its hash typedef std::pair<std::string, std::size_t> cache_t; // populate the cached message and its hash from the locale void update_cache(cache_t& cache, std::locale loc) { auto& fct = std::use_facet< std::messages<char> >(loc); std::messages_base::catalog cat = fct.open("sed", loc); cache.first = cat < 0 ? "" : fct.get(cat, 0, 0, "Memory exhausted"); cache.second = std::hash<std::string>()(cache.first); } // update the cache if the locale changed void true_callback(std::ios_base::event evt, std::ios_base& str, int idx) { if (evt == std::ios_base::imbue_event) { cache_t* ptr = static_cast<cache_t*>(str.pword(idx)); update_cache(*ptr, str.getloc()); } } // registers the cache in pword() and sets up the callback struct CacheSetup { CacheSetup(std::ostream& os, std::ios_base::event_callback f, cache_t* cache) { int index = std::ostream::xalloc(); os.pword(index) = cache; // store pointer to cache in the stream os.register_callback(f, index); // store callback and the index to the pointer update_cache(*cache, os.getloc()); // initialize cache }; }; // some custom class struct S { }; // some custom class's operator<< that needs fast access to hashed message std::ostream& operator<<(std::ostream& os, const S&) { static cache_t cache; static CacheSetup setup(os, true_callback, &cache); return os << cache.first << " : " << cache.second; } int main() { std::locale loc("en_US.utf8"); S s; std::cout.imbue(loc); std::cout << s << '\n'; std::cout.imbue(std::locale(loc, new std::messages_byname<char>("de_DE.utf8"))); std::cout << s << '\n'; std::cout.imbue(std::locale(loc, new std::messages_byname<char>("ja_JP.utf8"))); std::cout << s << '\n'; std::cout.imbue(std::locale(loc, new std::messages_byname<char>("ru_RU.utf8"))); std::cout << s << '\n'; } ``` Output: ``` Memory exhausted : 2,295,079,096 Speicher erschöpft : 3,139,423,551 メモリーが足りません : 3,837,351,114 Память исчерпана : 3,742,732,851 ``` cpp std::ios_base::iword std::ios\_base::iword ===================== | | | | | --- | --- | --- | | ``` long& iword( int index ); ``` | | | First, allocates or resizes the private storage (dynamic array of `long` or another indexable data structure) sufficiently to make `index` a valid index, then returns a reference to the `long` element of the private storage with the index `index`. The reference may be invalidated by any operation on this `ios_base` object, including another call to `iword()`, but the stored values are retained, so that reading from `iword(index)` with the same index later will produce the same value until the next call to `[std::basic\_ios::copyfmt()](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt")`. The value can be used for any purpose. The index of the element must be obtained by a previous call to `[xalloc()](xalloc "cpp/io/ios base/xalloc")`, otherwise the behavior is undefined. New elements are initialized to `​0​`. If the function fails (possibly caused by an allocation failure) and `*this` is a base class subobject of a `basic_ios<>` object or subobject, calls `[std::basic\_ios](http://en.cppreference.com/w/cpp/io/basic_ios)<>::setstate(badbit)` which may throw `[std::ios\_base::failure](failure "cpp/io/ios base/failure")`. ### Notes Typical use of iword storage is to pass information (e.g. custom formatting flags) from user-defined I/O manipulators to user-defined `operator<<` and `operator>>` or to user-defined formatting facets imbued into standard streams. ### Parameters | | | | | --- | --- | --- | | index | - | index value of the element | ### Return value A reference to the element. ### Exceptions May throw `[std::ios\_base::failure](failure "cpp/io/ios base/failure")` when setting the badbit. ### Example ``` #include <iostream> #include <string> struct Foo { static int foo_xalloc; std::string data; Foo(const std::string& s) : data(s) {} }; // allocates the iword storage for use with Foo objects int Foo::foo_xalloc = std::ios_base::xalloc(); // This user-defined operator<< prints the string in reverse if the iword holds 1 std::ostream& operator<<(std::ostream& os, Foo& f) { if(os.iword(Foo::foo_xalloc) == 1) return os << std::string(f.data.rbegin(), f.data.rend()); else return os << f.data; } // This I/O manipulator flips the number stored in iword between 0 and 1 std::ios_base& rev(std::ios_base& os) { os.iword(Foo::foo_xalloc) = !os.iword(Foo::foo_xalloc); return os; } int main() { Foo f("example"); std::cout << f << '\n' << rev << f << '\n' << rev << f << '\n'; } ``` Output: ``` example elpmaxe 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 36](https://cplusplus.github.io/LWG/issue36) | C++98 | the stored value might not beretained if the reference is invalidated | the stored value is retaineduntil the next call of `copyfmt()` | | [LWG 41](https://cplusplus.github.io/LWG/issue41) | C++98 | the function set badbit by itself on failure,but `ios_base` does not provide such interface | badbit is set by `basic_ios`(if `*this` is its base class subobject) | ### See also | | | | --- | --- | | [pword](pword "cpp/io/ios base/pword") | resizes the private storage if necessary and access to the `void*` element at the given index (public member function) | | [xalloc](xalloc "cpp/io/ios base/xalloc") [static] | returns a program-wide unique integer that is safe to use as index to [`pword()`](pword "cpp/io/ios base/pword") and **`iword()`** (public static member function) | cpp std::ios_base::getloc std::ios\_base::getloc ====================== | | | | | --- | --- | --- | | ``` std::locale getloc() const; ``` | | | Returns the current locale associated with the stream. ### Parameters (none). ### Return value The locale object associated with the stream. ### Example ``` #include <iostream> #include <ctime> #include <iomanip> #include <codecvt> int main() { 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"))); std::time_t t = std::time(nullptr); out << std::put_time(std::localtime(&t), L"%A %c") << '\n'; } ``` Possible output: ``` 土曜日 2013年09月14日 11時31分15秒 ``` ### 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 47](https://cplusplus.github.io/LWG/issue47) | C++98 | the return value was misspecified as the return value of `imbue()` | corrected | ### See also | | | | --- | --- | | [imbue](imbue "cpp/io/ios base/imbue") | sets locale (public member function) | cpp std::ios_base::event std::ios\_base::event ===================== | | | | | --- | --- | --- | | ``` enum event {erase_event, imbue_event, copyfmt_event}; ``` | | | Specifies the event type which is passed to functions registered by `[register\_callback()](register_callback "cpp/io/ios base/register callback")` on specific events. The following constants are defined: | Constant | Explanation | | --- | --- | | `erase_event` | issued on `~ios_base()` or [`basic_ios::copyfmt()`](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt") (before the copy of members takes place) | | `imbue_event` | issued on `[imbue()](imbue "cpp/io/ios base/imbue")` | | `copyfmt_event` | issued on [`basic_ios::copyfmt()`](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt") (after the copy of members takes place, but before the exception settings are copied) | ### Example cpp std::ios_base::fmtflags std::ios\_base::fmtflags ======================== | | | | | --- | --- | --- | | ``` typedef /*implementation defined*/ fmtflags; ``` | | | | ``` static constexpr fmtflags dec = /*implementation defined*/ static constexpr fmtflags oct = /*implementation defined*/ static constexpr fmtflags hex = /*implementation defined*/ static constexpr fmtflags basefield = dec | oct | hex; ``` | | | | ``` static constexpr fmtflags left = /*implementation defined*/ static constexpr fmtflags right = /*implementation defined*/ static constexpr fmtflags internal = /*implementation defined*/ static constexpr fmtflags adjustfield = left | right | internal; ``` | | | | ``` static constexpr fmtflags scientific = /*implementation defined*/ static constexpr fmtflags fixed = /*implementation defined*/ static constexpr fmtflags floatfield = scientific | fixed; ``` | | | | ``` static constexpr fmtflags boolalpha = /*implementation defined*/ static constexpr fmtflags showbase = /*implementation defined*/ static constexpr fmtflags showpoint = /*implementation defined*/ static constexpr fmtflags showpos = /*implementation defined*/ static constexpr fmtflags skipws = /*implementation defined*/ static constexpr fmtflags unitbuf = /*implementation defined*/ static constexpr fmtflags uppercase = /*implementation defined*/ ``` | | | Specifies available formatting flags. It is a [BitmaskType](../../named_req/bitmasktype "cpp/named req/BitmaskType"). The following constants are defined: | Constant | Explanation | | --- | --- | | **`dec`** | use decimal base for integer I/O: see `[std::dec](../manip/hex "cpp/io/manip/hex")` | | **`oct`** | use octal base for integer I/O: see `[std::oct](../manip/hex "cpp/io/manip/hex")` | | **`hex`** | use hexadecimal base for integer I/O: see `[std::hex](../manip/hex "cpp/io/manip/hex")` | | **`basefield`** | `dec|oct|hex`. Useful for masking operations | | **`left`** | left adjustment (adds fill characters to the right): see `[std::left](../manip/left "cpp/io/manip/left")` | | **`right`** | right adjustment (adds fill characters to the left): see `[std::right](../manip/left "cpp/io/manip/left")` | | **`internal`** | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](../manip/left "cpp/io/manip/left")` | | **`adjustfield`** | `left|right|internal`. Useful for masking operations | | **`scientific`** | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](../manip/fixed "cpp/io/manip/fixed")` | | **`fixed`** | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](../manip/fixed "cpp/io/manip/fixed")` | | **`floatfield`** | `scientific|fixed`. Useful for masking operations | | **`boolalpha`** | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](../manip/boolalpha "cpp/io/manip/boolalpha")` | | **`showbase`** | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](../manip/showbase "cpp/io/manip/showbase")` | | **`showpoint`** | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](../manip/showpoint "cpp/io/manip/showpoint")` | | **`showpos`** | generate a `+` character for non-negative numeric output: see `[std::showpos](../manip/showpos "cpp/io/manip/showpos")` | | **`skipws`** | skip leading whitespace before certain input operations: see `[std::skipws](../manip/skipws "cpp/io/manip/skipws")` | | **`unitbuf`** | flush the output after each output operation: see `[std::unitbuf](../manip/unitbuf "cpp/io/manip/unitbuf")` | | **`uppercase`** | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](../manip/uppercase "cpp/io/manip/uppercase")` | ### Example The following example shows several different ways to print the same result. ``` #include <iostream> int main() { int num = 150; // using fmtflags as class member constants: std::cout.setf(std::ios_base::hex, std::ios_base::basefield); std::cout.setf(std::ios_base::showbase); std::cout << num << '\n'; // using fmtflags as inherited class member constants: std::cout.setf (std::ios::hex , std::ios::basefield); std::cout.setf (std::ios::showbase); std::cout << num << '\n'; // using fmtflags as object member constants: std::cout.setf(std::cout.hex, std::cout.basefield); std::cout.setf(std::cout.showbase); std::cout << num << '\n'; // using fmtflags as a type: std::ios_base::fmtflags ff; ff = std::cout.flags(); ff &= ~std::cout.basefield; // unset basefield bits ff |= std::cout.hex; // set hex ff |= std::cout.showbase; // set showbase std::cout.flags(ff); std::cout << num << '\n'; // not using fmtflags, but using manipulators: std::cout << std::hex << std::showbase << num << '\n'; } ``` Output: ``` 0x96 0x96 0x96 0x96 0x96 ``` ### See also | | | | --- | --- | | [flags](flags "cpp/io/ios base/flags") | manages format flags (public member function) | | [setf](setf "cpp/io/ios base/setf") | sets specific format flag (public member function) | | [unsetf](unsetf "cpp/io/ios base/unsetf") | clears specific format flag (public member function) | | [setbase](../manip/setbase "cpp/io/manip/setbase") | changes the base used for integer I/O (function) | | [setfill](../manip/setfill "cpp/io/manip/setfill") | changes the fill character (function template) | | [fixedscientifichexfloatdefaultfloat](../manip/fixed "cpp/io/manip/fixed") (C++11)(C++11) | changes formatting used for floating-point I/O (function) | | [showbasenoshowbase](../manip/showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | | [boolalphanoboolalpha](../manip/boolalpha "cpp/io/manip/boolalpha") | switches between textual and numeric representation of booleans (function) | | [showposnoshowpos](../manip/showpos "cpp/io/manip/showpos") | controls whether the `+` sign used with non-negative numbers (function) | | [showpointnoshowpoint](../manip/showpoint "cpp/io/manip/showpoint") | controls whether decimal point is always included in floating-point representation (function) | | [unitbufnounitbuf](../manip/unitbuf "cpp/io/manip/unitbuf") | controls whether output is flushed after each operation (function) | | [skipwsnoskipws](../manip/skipws "cpp/io/manip/skipws") | controls whether leading whitespace is skipped on input (function) | | [uppercasenouppercase](../manip/uppercase "cpp/io/manip/uppercase") | controls whether uppercase characters are used with some output formats (function) | cpp std::ios_base::seekdir std::ios\_base::seekdir ======================= | | | | | --- | --- | --- | | ``` typedef /*implementation defined*/ seekdir; ``` | | | | ``` static constexpr seekdir beg = /*implementation defined*/ static constexpr seekdir end = /*implementation defined*/ static constexpr seekdir cur = /*implementation defined*/ ``` | | | Specifies file seeking direction type. The following constants are defined: | Constant | Explanation | | --- | --- | | **`beg`** | the beginning of a stream | | **`end`** | the ending of a stream | | **`cur`** | the current position of stream position indicator | ### Example ``` #include <iostream> #include <string> #include <sstream> int main() { std::istringstream in("Hello, World!"); std::string word1, word2, word3, word4, word5; in >> word1; in.seekg(0, std::ios_base::beg); // <- rewind in >> word2; in.seekg(1, std::ios_base::cur); // -> seek from cur pos toward the end in >> word3; in.seekg(-6, std::ios_base::cur); // <- seek from cur pos (end) toward begin in >> word4; in.seekg(-6, std::ios_base::end); // <- seek from end toward begin in >> word5; std::cout << "word1 = " << word1 << '\n' << "word2 = " << word2 << '\n' << "word3 = " << word3 << '\n' << "word4 = " << word4 << '\n' << "word5 = " << word5 << '\n'; } ``` Output: ``` word1 = Hello, word2 = Hello, word3 = World! word4 = World! word5 = World! ``` ### See also | | | | --- | --- | | [seekg](../basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekp](../basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [pubseekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | cpp std::ios_base::operator= std::ios\_base::operator= ========================= | | | | | --- | --- | --- | | ``` private: ios_base& operator=( const ios_base& ); ``` | | (until C++11) | | ``` public: ios_base& operator=( const ios_base& ) = delete; ``` | | (since C++11) | The copy assignment operator is private (until C++11)deleted (since C++11): streams are not copy-assignable. ### 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 50](https://cplusplus.github.io/LWG/issue50) | C++98 | the copy assignment operator was not specified | specified as private | cpp std::ios_base::iostate std::ios\_base::iostate ======================= | | | | | --- | --- | --- | | ``` typedef /*implementation defined*/ iostate; ``` | | | | ``` static constexpr iostate goodbit = 0; ``` | | | | ``` static constexpr iostate badbit = /*implementation defined*/ static constexpr iostate failbit = /*implementation defined*/ static constexpr iostate eofbit = /*implementation defined*/ ``` | | | Specifies stream state flags. It is a [BitmaskType](../../named_req/bitmasktype "cpp/named req/BitmaskType"), the following constants are defined: | Constant | Explanation | | --- | --- | | **`goodbit`** | no error | | **`badbit`** | irrecoverable stream error | | **`failbit`** | input/output operation failed (formatting or extraction error) | | **`eofbit`** | associated input sequence has reached end-of-file | #### The eofbit The eofbit is set by the following standard library functions: * The string input function `[std::getline](../../string/basic_string/getline "cpp/string/basic string/getline")` if it completes by reaching the end of the stream, as opposed to reaching the specified terminating character. * The numeric input overloads of [`basic_istream::operator>>`](../basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") if the end of the stream was encountered while reading the next character, on Stage 2 of [`num_get::get`](../../locale/num_get/get "cpp/locale/num get/get") processing. Depending on the parsing state, `failbit` may or may not be set at the same time: for example, `int n; istringstream buf("1"); buf >> n;` sets `eofbit`, but not `failbit`: the integer `1` was successfully parsed and stored in `n`. On the other hand, `bool b; istringstream buf("tr"); buf >> boolalpha >> b;` sets both `eofbit` and `failbit`: there was not enough characters to complete the parsing of the boolean `true`. * The character extraction overloads of [`operator>>std::basic_istream`](../basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2"), if the end of the stream is reached before the limit (if any) on the number of characters to be extracted. * The `[std::get\_time](../manip/get_time "cpp/io/manip/get time")` I/O manipulator and any of the `[std::time\_get](../../locale/time_get "cpp/locale/time get")` parsing functions: [`time_get::get`](../../locale/time_get/get "cpp/locale/time get/get"), [`time_get::get_time`](../../locale/time_get/get_time "cpp/locale/time get/get time"), [`time_get::get_date`](../../locale/time_get/get_date "cpp/locale/time get/get date"), etc., if the end of the stream is reached before the last character needed to parse the expected date/time value was processed. * The `[std::get\_money](../manip/get_money "cpp/io/manip/get money")` I/O manipulator and [`money_get::get`](../../locale/money_get/get "cpp/locale/money get/get") function, if the end of the stream is reached before the last character needed to parse the expected monetary value was processed. * The [`basic_istream::sentry`](../basic_istream/sentry "cpp/io/basic istream/sentry") constructor, executed at the beginning of every formatted input function: unless the `skipws` bit is unset (e.g. by issuing `[std::noskipws](../manip/skipws "cpp/io/manip/skipws")`), sentry reads and discards the leading whitespace characters. If the end of the input stream is reached during this operation, both `eofbit` and `failbit` are set, and no input takes place. * The I/O manipulator `[std::ws](../manip/ws "cpp/io/manip/ws")`, if it reaches the end of the stream while consuming whitespace (but, unlike the formatted input sentry, it does not set `failbit` in this case) * The unformatted input functions [`basic_istream::read`](../basic_istream/read "cpp/io/basic istream/read"), [`basic_istream::get`](../basic_istream/get "cpp/io/basic istream/get"), [`basic_istream::peek`](../basic_istream/peek "cpp/io/basic istream/peek"), and [`basic_istream::getline`](../basic_istream/getline "cpp/io/basic istream/getline"), when reaching the end of the stream. * The discard input function [`basic_istream::ignore`](../basic_istream/ignore "cpp/io/basic istream/ignore"), when reaching the end of the stream before reaching the specified delimiter character. * The immediate input function [`basic_istream::readsome`](../basic_istream/readsome "cpp/io/basic istream/readsome"), if [`basic_streambuf::in_avail`](../basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") returns `-1` The following functions clear `eofbit` as a side-effect: * [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback") * [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") * [`basic_istream::seekg`](../basic_istream/seekg "cpp/io/basic istream/seekg") Note that in nearly all situations, if eofbit is set, the failbit is set as well. #### The failbit The failbit is set by the following standard library functions: * The [`basic_istream::sentry`](../basic_istream/sentry "cpp/io/basic istream/sentry") constructor, executed at the beginning of every input function, if either `eofbit` or `badbit` is already set on the stream, or if the end of stream is encountered while consuming leading whitespace. * The [`basic_ostream::sentry`](../basic_ostream/sentry "cpp/io/basic ostream/sentry") constructor, executed at the beginning of every output function, under implementation-defined conditions. * [`operator>>(std::basic_string<>)`](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") if the function extracts no characters from the input stream. * [`operator>>(std::complex<>)`](../../numeric/complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") if the function fails to extract a valid complex number. * The character array and single character overloads of [`operator>>`](../basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") if they fail to extract any characters. * The streambuf overload of [`basic_istream::operator>>`](../basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") if the streambuf argument is a null pointer or if no characters were inserted into the streambuf. * The streambuf overload of [`basic_ostream::operator<<`](../basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") if the function inserts no characters. * [`operator>>(std::bitset<>)`](../../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") if the function extracts no characters from the input stream. * `[std::getline](../../string/basic_string/getline "cpp/string/basic string/getline")` if the function extracts no characters or if it manages to extract [`basic_string::max_size`](../../string/basic_string/max_size "cpp/string/basic string/max size") characters from the input stream. * The numeric, pointer, and boolean input overloads of [`basic_istream::operator>>`](../basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") (technically, the overloads of [`num_get::get`](../../locale/num_get/get "cpp/locale/num get/get") they call), if the input cannot be parsed as a valid value or if the value parsed does not fit in the destination type. * The time input manipulator `[std::get\_time](../manip/get_time "cpp/io/manip/get time")` (technically, [`time_get::get`](../../locale/time_get/get "cpp/locale/time get/get") it calls), if the input cannot be unambiguously parsed as a time value according to the given format string. * The currency input manipulator `[std::get\_money](../manip/get_money "cpp/io/manip/get money")` (technically, [`money_get::get`](../../locale/money_get/get "cpp/locale/money get/get") it calls), if the input cannot be unambiguously parsed as a monetary value according to the locale rules. * The extraction operators of all [RandomNumberEngines](../../named_req/randomnumberengine "cpp/named req/RandomNumberEngine"), if bad input is encountered. * The extraction operators of all [RandomNumberDistributions](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"), if bad input is encountered. * The unformatted input functions [`basic_istream::get`](../basic_istream/get "cpp/io/basic istream/get") if they fails to extract any characters. * [`basic_istream::getline`](../basic_istream/getline "cpp/io/basic istream/getline"), if it extracts no characters, if it fills in the provided buffer without encountering the delimiter, or if the provided buffer size is less than 1. * [`basic_istream::read`](../basic_istream/read "cpp/io/basic istream/read"), if the end-of-file condition occurs on the input stream before all requested characters could be extracted. * [`basic_istream::seekg`](../basic_istream/seekg "cpp/io/basic istream/seekg") on failure * [`basic_ostream::tellp`](../basic_ostream/tellp "cpp/io/basic ostream/tellp") on failure * The constructors of `[std::basic\_fstream](../basic_fstream "cpp/io/basic fstream")`, `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")`, and `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` that takes a filename argument, if the file cannot be opened. * [`basic_fstream::open`](../basic_fstream/open "cpp/io/basic fstream/open"), [`basic_ifstream::open`](../basic_ifstream/open "cpp/io/basic ifstream/open"), and [`basic_ofstream::open`](../basic_ofstream/open "cpp/io/basic ofstream/open") if the file cannot be opened. * [`basic_fstream::close`](../basic_fstream/close "cpp/io/basic fstream/close"), [`basic_ifstream::close`](../basic_ifstream/close "cpp/io/basic ifstream/close"), and [`basic_ofstream::close`](../basic_ofstream/close "cpp/io/basic ofstream/close") if the file cannot be closed. #### The badbit The badbit is set by the following standard library functions: * [`basic_ostream::put`](../basic_ostream/put "cpp/io/basic ostream/put") if it fails to insert a character into the output stream, for any reason. * [`basic_ostream::write`](../basic_ostream/write "cpp/io/basic ostream/write") if it fails to insert a character into the output stream, for any reason. * Formatted output functions [operator<<](../basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt"), `[std::put\_money](../manip/put_money "cpp/io/manip/put money")`, and `[std::put\_time](../manip/put_time "cpp/io/manip/put time")`, if they encounter the end of the output stream before completing output. * [`basic_ios::init`](../basic_ios/init "cpp/io/basic ios/init") when called to initialize a stream with a null pointer for `rdbuf()`. * [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback") and [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") when called on a stream with a null `rdbuf()`. * [`basic_ostream::operator<<(basic_streambuf*)`](../basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") when a null pointer is passed as the argument. * [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback") and [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") if `rdbuf()->sputbackc()` or `rdbuf()->sungetc()` return `traits::eof()`. * [`basic_istream::sync`](../basic_istream/sync "cpp/io/basic istream/sync"), [`basic_ostream::flush`](../basic_ostream/flush "cpp/io/basic ostream/flush"), and every output function on a `unitbuf` output stream, if `rdbuf()->pubsync()` returns `-1`. * Every stream I/O function if an exception is thrown by any member function of the associated stream buffer (e.g. `sbumpc()`, `xsputn()`, `sgetc()`, `overflow()`, etc). * [`ios_base::iword`](iword "cpp/io/ios base/iword") and [`ios_base::pword`](pword "cpp/io/ios base/pword") on failure (e.g. failure to allocate memory). ### Example ### See also The following table shows the value of [`basic_ios`](../basic_ios "cpp/io/basic ios") accessors ([`good()`](../basic_ios/good "cpp/io/basic ios/good"), [`fail()`](../basic_ios/fail "cpp/io/basic ios/fail"), etc.) for all possible combinations of **`ios_base::iostate`** flags: | | | | --- | --- | | **`ios_base::iostate`** flags | `basic_ios` accessors | | `eofbit` | `failbit` | `badbit` | [`good()`](../basic_ios/good "cpp/io/basic ios/good") | [`fail()`](../basic_ios/fail "cpp/io/basic ios/fail") | [`bad()`](../basic_ios/bad "cpp/io/basic ios/bad") | [`eof()`](../basic_ios/eof "cpp/io/basic ios/eof") | [`operator bool`](../basic_ios/operator_bool "cpp/io/basic ios/operator bool") | [`operator!`](../basic_ios/operator- "cpp/io/basic ios/operator!") | | false | false | false | true | false | false | false | true | false | | false | false | true | false | true | true | false | false | true | | false | true | false | false | true | false | false | false | true | | false | true | true | false | true | true | false | false | true | | true | false | false | false | false | false | true | true | false | | true | false | true | false | true | true | true | false | true | | true | true | false | false | true | false | true | false | true | | true | true | true | false | true | true | true | false | true | | | | | --- | --- | | [rdstate](../basic_ios/rdstate "cpp/io/basic ios/rdstate") | returns state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [setstate](../basic_ios/setstate "cpp/io/basic ios/setstate") | sets state flags (public member function of `std::basic_ios<CharT,Traits>`) | | [clear](../basic_ios/clear "cpp/io/basic ios/clear") | modifies state flags (public member function of `std::basic_ios<CharT,Traits>`) |
programming_docs
cpp std::ios_base::openmode std::ios\_base::openmode ======================== | | | | | --- | --- | --- | | ``` typedef /*implementation defined*/ openmode; ``` | | | | ``` static constexpr openmode app = /*implementation defined*/ static constexpr openmode binary = /*implementation defined*/ static constexpr openmode in = /*implementation defined*/ static constexpr openmode out = /*implementation defined*/ static constexpr openmode trunc = /*implementation defined*/ static constexpr openmode ate = /*implementation defined*/ ``` | | | Specifies available file open flags. It is a [BitmaskType](../../named_req/bitmasktype "cpp/named req/BitmaskType"), the following constants are defined: | Constant | Explanation | | --- | --- | | **`app`** | seek to the end of stream before each write | | **`binary`** | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | **`in`** | open for reading | | **`out`** | open for writing | | **`trunc`** | discard the contents of the stream when opening | | **`ate`** | seek to the end of stream immediately after open | ### Example ### See also | | | | --- | --- | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | | [(constructor)](../basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::ios_base::~ios_base std::ios\_base::~ios\_base ========================== | | | | | --- | --- | --- | | ``` virtual ~ios_base(); ``` | | | Destroys the `ios_base` object. Before any of the member functions would yield undefined results, calls callbacks, registered by [`register_callback()`](register_callback "cpp/io/ios base/register callback") passing [`erase_event`](event "cpp/io/ios base/event") as parameter. Then, deallocates any memory obtained. No operations on `rdbuf` are performed, it is not destroyed. ### 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 3434](https://cplusplus.github.io/LWG/issue3434) | C++98 | the destructor was not required to reclaim memory for `iarray` and `parray` | required | cpp std::ios_base::event_callback std::ios\_base::event\_callback =============================== | | | | | --- | --- | --- | | ``` typedef void (*event_callback)(event type, ios_base& ios, int index); ``` | | | The type of function callbacks that can be registered using `[register\_callback()](register_callback "cpp/io/ios base/register callback")` to be called on specific events. `type` is a value of type [`ios_base::event`](event "cpp/io/ios base/event") which indicates the type of the event that will invoke this callback. `ios` refers to the stream object for which the callback is invoked: `*this` is passed as the argument when callbacks are invoked by `[std::ios\_base](../ios_base "cpp/io/ios base")` and `[std::basic\_ios](../basic_ios "cpp/io/basic ios")` member functions. `index` is the user-provided value passed to `[register\_callback()](register_callback "cpp/io/ios base/register callback")` when registering the function. ### See also | | | | --- | --- | | [copyfmt](../basic_ios/copyfmt "cpp/io/basic ios/copyfmt") | copies formatting information (public member function of `std::basic_ios<CharT,Traits>`) | | [imbue](imbue "cpp/io/ios base/imbue") | sets locale (public member function) | | [(destructor)](~ios_base "cpp/io/ios base/~ios base") [virtual] | destructs the object (virtual public member function) | | [register\_callback](register_callback "cpp/io/ios base/register callback") | registers event callback function (public member function) | cpp std::ios_base::unsetf std::ios\_base::unsetf ====================== | | | | | --- | --- | --- | | ``` void unsetf( fmtflags flags ); ``` | | | Unsets the formatting flags identified by `flags`. ### Parameters | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | flags | - | formatting flags to unset. It can be a combination of the following constants: | Constant | Explanation | | --- | --- | | [`dec`](fmtflags "cpp/io/ios base/fmtflags") | use decimal base for integer I/O: see `[std::dec](../manip/hex "cpp/io/manip/hex")` | | [`oct`](fmtflags "cpp/io/ios base/fmtflags") | use octal base for integer I/O: see `[std::oct](../manip/hex "cpp/io/manip/hex")` | | [`hex`](fmtflags "cpp/io/ios base/fmtflags") | use hexadecimal base for integer I/O: see `[std::hex](../manip/hex "cpp/io/manip/hex")` | | [`basefield`](fmtflags "cpp/io/ios base/fmtflags") | `dec|oct|hex`. Useful for masking operations | | [`left`](fmtflags "cpp/io/ios base/fmtflags") | left adjustment (adds fill characters to the right): see `[std::left](../manip/left "cpp/io/manip/left")` | | [`right`](fmtflags "cpp/io/ios base/fmtflags") | right adjustment (adds fill characters to the left): see `[std::right](../manip/left "cpp/io/manip/left")` | | [`internal`](fmtflags "cpp/io/ios base/fmtflags") | internal adjustment (adds fill characters to the internal designated point): see `[std::internal](../manip/left "cpp/io/manip/left")` | | [`adjustfield`](fmtflags "cpp/io/ios base/fmtflags") | `left|right|internal`. Useful for masking operations | | [`scientific`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using scientific notation, or hex notation if combined with fixed: see `[std::scientific](../manip/fixed "cpp/io/manip/fixed")` | | [`fixed`](fmtflags "cpp/io/ios base/fmtflags") | generate floating point types using fixed notation, or hex notation if combined with scientific: see `[std::fixed](../manip/fixed "cpp/io/manip/fixed")` | | [`floatfield`](fmtflags "cpp/io/ios base/fmtflags") | `scientific|fixed`. Useful for masking operations | | [`boolalpha`](fmtflags "cpp/io/ios base/fmtflags") | insert and extract `bool` type in alphanumeric format: see `[std::boolalpha](../manip/boolalpha "cpp/io/manip/boolalpha")` | | [`showbase`](fmtflags "cpp/io/ios base/fmtflags") | generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see `[std::showbase](../manip/showbase "cpp/io/manip/showbase")` | | [`showpoint`](fmtflags "cpp/io/ios base/fmtflags") | generate a decimal-point character unconditionally for floating-point number output: see `[std::showpoint](../manip/showpoint "cpp/io/manip/showpoint")` | | [`showpos`](fmtflags "cpp/io/ios base/fmtflags") | generate a `+` character for non-negative numeric output: see `[std::showpos](../manip/showpos "cpp/io/manip/showpos")` | | [`skipws`](fmtflags "cpp/io/ios base/fmtflags") | skip leading whitespace before certain input operations: see `[std::skipws](../manip/skipws "cpp/io/manip/skipws")` | | [`unitbuf`](fmtflags "cpp/io/ios base/fmtflags") | flush the output after each output operation: see `[std::unitbuf](../manip/unitbuf "cpp/io/manip/unitbuf")` | | [`uppercase`](fmtflags "cpp/io/ios base/fmtflags") | replace certain lowercase letters with their uppercaseequivalents in certain output operations: see `[std::uppercase](../manip/uppercase "cpp/io/manip/uppercase")` | | ### Return value (none). ### Example ### See also | | | | --- | --- | | [flags](flags "cpp/io/ios base/flags") | manages format flags (public member function) | | [setf](setf "cpp/io/ios base/setf") | sets specific format flag (public member function) | cpp std::ios_base::width std::ios\_base::width ===================== | | | | | --- | --- | --- | | ``` streamsize width() const; ``` | (1) | | | ``` streamsize width( streamsize new_width ); ``` | (2) | | Manages the minimum number of characters to generate on certain output operations and the maximum number of characters to generate on certain input operations. 1) Returns the current field width. 2) Sets the field width to the given one. Returns the previous field width. ### Parameters | | | | | --- | --- | --- | | new\_width | - | new field width setting | ### Return value The field width before the call to the function. ### Notes Some I/O functions call `width(0)` before returning, see `[std::setw](../manip/setw "cpp/io/manip/setw")` (this results in this field having effect on the next I/O function only, and not on any subsequent I/O). The exact effects this modifier has on the input and output vary between the individual I/O functions and are described at each `operator<<` and `operator>>` overload page individually. ### Example ``` #include <array> #include <tuple> #include <ctime> #include <string> #include <iostream> #include <sstream> #include <iomanip> int main() { auto str_time = [](int year, int mon, int day) { constexpr std::array<const char*, 7> week_day{ { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" } }; std::tm tm{}; tm.tm_year = year - 1900; tm.tm_mon = mon - 1; tm.tm_mday = day; day += mon < 3 ? year-- : year - 2; tm.tm_wday = (23 * mon / 9 + day + 4 + year / 4 - year / 100 + year / 400) % 7; std::ostringstream out; out << week_day[tm.tm_wday] << ", " << std::put_time(&tm, "%B %d, %Y"); return out.str(); }; constexpr int column_size = 4; using table_t = std::array<std::string, column_size>; table_t headers{ { "Name", "Birthdate", "Death date", "Language Created" } }; std::array<table_t, 5> data{ { { { "Dennis Ritchie", str_time(1941, 9, 9), str_time(2011, 10, 12), "C" } }, { { "Bjarne Stroustrup", str_time(1950, 12, 30), "", "C++" } }, { { "Anders Hejlsberg", str_time(1960, 12, 2), "", "C#" } }, { { "Guido van Rossum", str_time(1956, 1, 31), "", "Python" } }, { { "Brendan Eich", str_time(1961, 7, 4), "", "Javascript" } } } }; constexpr int name_wid = 20; constexpr int birth_wid = 30; constexpr int death_wid = 30; constexpr int lang_wid = 18; auto print_line = [](table_t const &tbl) { auto const &[Name, Birthdate, DeathDate, LanguageCreated] = tbl; std::cout.width(name_wid); std::cout << ("| " + Name) << '|'; std::cout.width(birth_wid); std::cout << (' ' + Birthdate) << '|'; std::cout.width(death_wid); std::cout << (' ' + DeathDate) << '|'; std::cout.width(lang_wid); std::cout << (' ' + LanguageCreated) << '|'; std::cout << '\n'; }; constexpr int total_wid = name_wid + birth_wid + death_wid + lang_wid + column_size; auto print_break = [] { std::cout.width(total_wid); std::cout.fill('-'); std::cout << '-' << '\n'; std::cout.fill(' '); }; std::cout.setf(std::ios::left, std::ios::adjustfield); print_break(); print_line(headers); print_break(); for (auto const &entry : data) print_line(entry); print_break(); } ``` Output: ``` ------------------------------------------------------------------------------------------------------ | Name | Birthdate | Death date | Language Created | ------------------------------------------------------------------------------------------------------ | Dennis Ritchie | Tuesday, September 09, 1941 | Wednesday, October 12, 2011 | C | | Bjarne Stroustrup | Saturday, December 30, 1950 | | C++ | | Anders Hejlsberg | Friday, December 02, 1960 | | C# | | Guido van Rossum | Tuesday, January 31, 1956 | | Python | | Brendan Eich | Tuesday, July 04, 1961 | | Javascript | ------------------------------------------------------------------------------------------------------ ``` ### See also | | | | --- | --- | | [precision](precision "cpp/io/ios base/precision") | manages decimal precision of floating point operations (public member function) | cpp std::ios_base::sync_with_stdio std::ios\_base::sync\_with\_stdio ================================= | | | | | --- | --- | --- | | ``` static bool sync_with_stdio( bool sync = true ); ``` | | | Sets whether the standard C++ streams are synchronized to the standard C streams after each input/output operation. The standard C++ streams are the following: `[std::cin](../cin "cpp/io/cin")`, `[std::cout](../cout "cpp/io/cout")`, `[std::cerr](../cerr "cpp/io/cerr")`, `[std::clog](../clog "cpp/io/clog")`, `[std::wcin](../cin "cpp/io/cin")`, `[std::wcout](../cout "cpp/io/cout")`, `[std::wcerr](../cerr "cpp/io/cerr")` and `[std::wclog](../clog "cpp/io/clog")`. The standard C streams are the following: `[stdin](../c/std_streams "cpp/io/c/std streams")`, `[stdout](../c/std_streams "cpp/io/c/std streams")` and `[stderr](../c/std_streams "cpp/io/c/std streams")`. For a standard stream `str`, synchronized with the C stream `f`, the following pairs of functions have identical effect: 1) `[std::fputc](http://en.cppreference.com/w/cpp/io/c/fputc)(f, c)` and `str.rdbuf()->sputc(c)` 2) `[std::fgetc](http://en.cppreference.com/w/cpp/io/c/fgetc)(f)` and `str.rdbuf()->sbumpc()` 3) `[std::ungetc](http://en.cppreference.com/w/cpp/io/c/ungetc)(c, f)` and `str.rdbuf()->sputbackc(c)` In practice, this means that the synchronized C++ streams are unbuffered, and each I/O operation on a C++ stream is immediately applied to the corresponding C stream's buffer. This makes it possible to freely mix C++ and C I/O. In addition, synchronized C++ streams are guaranteed to be thread-safe (individual characters output from multiple threads may interleave, but no data races occur). If the synchronization is turned off, the C++ standard streams are allowed to buffer their I/O independently, which may be considerably faster in some cases. By default, all eight standard C++ streams are synchronized with their respective C streams. If this function is called after I/O has occurred on the standard stream, the behavior is implementation-defined: implementations range from no effect to destroying the read buffer. ### Parameters | | | | | --- | --- | --- | | sync | - | the new synchronization setting | ### Return value synchronization state before the call to the function. ### Example ``` #include <iostream> #include <cstdio> int main() { std::ios::sync_with_stdio(false); std::cout << "a\n"; std::printf("b\n"); std::cout << "c\n"; } ``` Possible output: ``` b a c ``` ### 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 49](https://cplusplus.github.io/LWG/issue49) | C++98 | it was unspecified (1) which state is actually returned and(2) what does 'synchronized' between standard C and C++ streams mean | both specified | ### See also | | | | --- | --- | | [coutwcout](../cout "cpp/io/cout") | writes to the standard C output stream `[stdout](../c/std_streams "cpp/io/c/std streams")`(global object) | | [cerrwcerr](../cerr "cpp/io/cerr") | writes to the standard C error stream `[stderr](../c/std_streams "cpp/io/c/std streams")`, unbuffered(global object) | | [clogwclog](../clog "cpp/io/clog") | writes to the standard C error stream `[stderr](../c/std_streams "cpp/io/c/std streams")`(global object) | cpp std::basic_ostringstream::rdbuf std::basic\_ostringstream::rdbuf ================================ | | | | | --- | --- | --- | | ``` std::basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; ``` | | | Returns pointer to the underlying raw string device object. ### Parameters (none). ### Return value Pointer to the underlying raw string device. ### Example cpp std::basic_ostringstream<CharT,Traits,Allocator>::basic_ostringstream std::basic\_ostringstream<CharT,Traits,Allocator>::basic\_ostringstream ======================================================================= | | | | | --- | --- | --- | | ``` basic_ostringstream() : basic_ostringstream(std::ios_base::out) { } ``` | (1) | (since C++11) | | | (2) | | | ``` explicit basic_ostringstream( std::ios_base::openmode mode = std::ios_base::out ); ``` | (until C++11) | | ``` explicit basic_ostringstream( std::ios_base::openmode mode ); ``` | (since C++11) | | ``` explicit basic_ostringstream( const std::basic_string<CharT,Traits,Allocator>& str, std::ios_base::openmode mode = std::ios_base::out ); ``` | (3) | | | ``` basic_ostringstream( basic_ostringstream&& other ); ``` | (4) | (since C++11) | | ``` basic_ostringstream( std::ios_base::openmode mode, const Allocator& a ); ``` | (5) | (since C++20) | | ``` explicit basic_ostringstream( std::basic_string<CharT,Traits,Allocator>&& str, std::ios_base::openmode mode = std::ios_base::out ); ``` | (6) | (since C++20) | | ``` template<class SAlloc> basic_ostringstream( const std::basic_string<CharT,Traits,SAlloc>& str, const Allocator& a ) : basic_ostringstream(str, std::ios_base::out, a) { } ``` | (7) | (since C++20) | | ``` template<class SAlloc> basic_ostringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode, const Allocator& a ); ``` | (8) | (since C++20) | | ``` template<class SAlloc> explicit basic_ostringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode = std::ios_base::out ); ``` | (9) | (since C++20) | Constructs new string stream. 1) Default constructor. Constructs new underlying string device with the default open mode 2) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 3) Uses a copy of `str` as initial contents of the underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 4) Move constructor. Constructs the string stream with the state of `other` using move semantics. 5) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 6) Move-construct the contents of the underlying string device with `str`. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(std::move(str), mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 7) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 8) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 9) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. This overload participates in overload resolution only if `SAlloc` and `Allocator` are not the same type. ### Parameters | | | | | --- | --- | --- | | str | - | string to use as initial contents of the string stream | | a | - | allocator used for allocating the contents of the string stream | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another string stream to use as source | ### Notes Construction of one-off `basic_ostringstream` objects in a tight loop, such as when used for string conversion, may be significantly more costly than calling `[str](str "cpp/io/basic ostringstream/str")` to reuse the same object. ### Example ``` #include <iostream> #include <sstream> int main() { // default constructor (input/output stream) std::stringstream buf1; buf1 << 7; int n = 0; buf1 >> n; std::cout << "buf1 = " << buf1.str() << " n = " << n << '\n'; // input stream std::istringstream inbuf("-10"); inbuf >> n; std::cout << "n = " << n << '\n'; // output stream in append mode (C++11) std::ostringstream buf2("test", std::ios_base::ate); buf2 << '1'; std::cout << buf2.str() << '\n'; } ``` Output: ``` buf1 = 7 n = 7 n = -10 test1 ``` ### 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 | ### See also | | | | --- | --- | | [str](str "cpp/io/basic ostringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [(constructor)](../basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) |
programming_docs
cpp std::basic_ostringstream::swap std::basic\_ostringstream::swap =============================== | | | | | --- | --- | --- | | ``` void swap( basic_ostringstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_ostream<CharT, Traits>::swap(other)` and `rdbuf()->swap(*other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic ostringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](../basic_stringbuf/swap "cpp/io/basic stringbuf/swap") (C++11) | swaps two basic\_stringbuf objects (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_ostringstream<CharT,Traits,Allocator>::str std::basic\_ostringstream<CharT,Traits,Allocator>::str ====================================================== | | | | | --- | --- | --- | | | (1) | | | ``` std::basic_string<CharT,Traits,Allocator> str() const; ``` | (until C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() const&; ``` | (since C++20) | | ``` template<class SAlloc> std::basic_string<CharT,Traits,SAlloc> str( const SAlloc& a ) const; ``` | (2) | (since C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() &&; ``` | (3) | (since C++20) | | ``` void str( const std::basic_string<CharT,Traits,Allocator>& s ); ``` | (4) | | | ``` template<class SAlloc> void str( const std::basic_string<CharT,Traits, SAlloc>& s ); ``` | (5) | (since C++20) | | ``` void str( std::basic_string<CharT,Traits,Allocator>&& s ); ``` | (6) | (since C++20) | Manages the contents of the underlying string object. 1) Returns a copy of the underlying string. Equivalent to `return rdbuf()->str();`. 2) Returns a copy of the underlying string, using `a` as allocator. Equivalent to `return rdbuf()->str(a);`. 3) Returns a string move-constructed from the underlying string. Equivalent to `return std::move(*rdbuf()).str();`. 4-5) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(s);`. 6) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(std::move(s));`. ### Parameters | | | | | --- | --- | --- | | s | - | new contents of the underlying string | | a | - | allocator used to construct the returned string | ### Return value 1-2) a copy of the underlying string object. 3) a string move-constructed from the underlying string object. 4-6) (none) ### Notes The copy of the underlying string returned by `str` is a temporary object that will be destructed at the end of the expression, so directly calling [`c_str()`](../../string/basic_string/c_str "cpp/string/basic string/c str") on the result of `str()` (for example in `auto *ptr = out.str().c_str();`) results in a dangling pointer. ### Example ``` #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; } ``` Output: ``` after reading the first int from "1 2", the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2", str() = "3 2" after writing the int '3' to append stream "1 2", str() = "1 23" ``` ### See also | | | | --- | --- | | [rdbuf](rdbuf "cpp/io/basic ostringstream/rdbuf") | returns the underlying raw string device object (public member function) | | [str](../basic_stringbuf/str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::swap(std::basic_ostringstream) std::swap(std::basic\_ostringstream) ==================================== | Defined in header `[<sstream>](../../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_ostringstream<CharT,Traits,Alloc>& lhs, std::basic_ostringstream<CharT,Traits,Alloc>& rhs ); ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_ostringstream](http://en.cppreference.com/w/cpp/io/basic_ostringstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ostringstream/swap") (C++11) | swaps two string streams (public member function) | cpp std::basic_ostringstream<CharT,Traits,Allocator>::view std::basic\_ostringstream<CharT,Traits,Allocator>::view ======================================================= | | | | | --- | --- | --- | | ``` std::basic_string_view<CharT, Traits> view() const noexcept; ``` | | (since C++20) | Obtains a `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. Equivalent to `return rdbuf()->view();`. ### Parameters (none). ### Return value A `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. ### Example ### See also | | | | --- | --- | | [view](../basic_stringbuf/view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_ostringstream::operator= std::basic\_ostringstream::operator= ==================================== | | | | | --- | --- | --- | | ``` basic_ostringstream& operator=( basic_ostringstream&& other ); ``` | | (since C++11) | Move assigns the string stream `other` to `*this`, effectively move-assigning both the `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` base class and the associated `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | string stream to move from | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ostringstream/swap") (C++11) | swaps two string streams (public member function) | | [operator=](../basic_stringbuf/operator= "cpp/io/basic stringbuf/operator=") (C++11) | assigns a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [operator=](../basic_ostream/operator= "cpp/io/basic ostream/operator=") (C++11) | move-assigns from another `basic_ostream` (protected member function) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::get_allocator std::basic\_syncbuf<CharT,Traits,Allocator>::get\_allocator =========================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | | Returns a copy of the allocator that was passed in as the constructor argument or replaced through the assignment operator. ### Parameters (none). ### Example ### See also | | | | --- | --- | | [(constructor)](basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function) | | [operator=](operator= "cpp/io/basic syncbuf/operator=") | assigns a basic\_syncbuf object (public member function) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::get_wrapped std::basic\_syncbuf<CharT,Traits,Allocator>::get\_wrapped ========================================================= | | | | | --- | --- | --- | | ``` streambuf_type* get_wrapped() const noexcept; ``` | | | Returns a pointer to the wrapped `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")`. ### Parameters (none). ### Notes This function is not expected to be called directly: it is called through [`std::basic_osyncstream::get_wrapped`](../basic_osyncstream/get_wrapped "cpp/io/basic osyncstream/get wrapped"). ### Example ### See also | | | | --- | --- | | [get\_wrapped](../basic_osyncstream/get_wrapped "cpp/io/basic osyncstream/get wrapped") | obtains a pointer to the final destination stream buffer (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::basic_syncbuf std::basic\_syncbuf<CharT,Traits,Allocator>::basic\_syncbuf =========================================================== | | | | | --- | --- | --- | | ``` basic_syncbuf() : basic_syncbuf(nullptr) ``` | (1) | | | ``` explicit basic_syncbuf( streambuf_type* obuf ) : basic_syncbuf( obuf, Allocator() ) {} ``` | (2) | | | ``` basic_syncbuf( streambuf_type* obuf, const Allocator& a); ``` | (3) | | | ``` basic_syncbuf( basic_syncbuf&& rhs); ``` | (4) | | 1) Default constructor: creates an instance of `std::basic_syncbuf` with emit-on-sync policy set to `false`, wrapped streambuffer set to `nullptr`, and using default-constructed `Allocator` as the allocator for temporary storage. 2,3) Creates an instance of `std::basic_syncbuf` with emit-on-sync policy set to `false`, wrapped streambuffer set to `obuf`, and using `a` as the allocator for temporary storage. 4) Move constructor: move-constructs a `std::basic_syncbuf` object by moving all contents from another `std::basic_syncbuf` object `rhs`, including the temporary storage, the wrapped stream pointer, policy, and all other state (such as the mutex pointer). After move, `rhs` is not associated with a stream, and `rhs.get_wrapped()==nullptr`. The put area member pointers of the base class `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` of `rhs` are guaranteed to be null. Destroying a moved-from `rhs` will not produce any output. ### Parameters | | | | | --- | --- | --- | | obuf | - | pointer to the `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` to wrap | | a | - | the allocator to use for temporary storage | | rhs | - | another std::basic\_syncbuf to move from | ### Exceptions 2,3) May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` from the constructor of the internal temporary storage or `[std::system\_error](../../error/system_error "cpp/error/system error")` from the mutex construction. ### Notes Typically called by the appropriate constructors of `std::basic_osyncstream`. ### Example ### See also | | | | --- | --- | | [sync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [emit](emit "cpp/io/basic syncbuf/emit") | atomically transmits the entire internal buffer to the wrapped streambuf (public member function) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::swap std::basic\_syncbuf<CharT,Traits,Allocator>::swap ================================================= | | | | | --- | --- | --- | | ``` void swap( basic_syncbuf& other ); ``` | | | Exchanges the contents of the sync stream buffer with those of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | sync stream buffer to exchange contents with | ### Return value (none). ### Example cpp std::basic_syncbuf<CharT,Traits,Allocator>::emit std::basic\_syncbuf<CharT,Traits,Allocator>::emit ================================================= | | | | | --- | --- | --- | | ``` bool emit(); ``` | | | Atomically transmits all pending output to the wrapped stream. All `emit()` calls transferring characters to the same wrapped stream buffer object appear to execute in a total order, where each `emit()` call [synchronizes-with](../../atomic/memory_order "cpp/atomic/memory order") subsequent `emit()` calls in that total order, even if these calls are made through difference instances of `std::basic_syncbuf`/`std::basic_osyncstream`. In practice, this means that emit() takes a lock uniquely associated with the wrapped stream object: for example, it could be held in a static hash map where the address of the wrapped stream is used as the key. If a call had been made to [`sync`](sync "cpp/io/basic syncbuf/sync") since the last call to `emit()`, then also flushes the wrapped stream by calling [`pubsync()`](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") on it. ### Parameters (none). ### Return value `true` if all of the following is true: * there is a wrapped stream (the wrapped streambuf pointer is not null) * all characters from the temporary storage were successfully sent into the wrapped stream * the call to [`pubsync()`](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync"), if requested, also completed successfully. Returns `false` otherwise. ### Notes Normally called by the destructor of the owning `std::basic_osyncstream` or by [`std::basic_osyncstream::emit`](../basic_osyncstream/emit "cpp/io/basic osyncstream/emit"). ### Example ### See also | | | | --- | --- | | [(destructor)](../basic_osyncstream/~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | | [emit](../basic_osyncstream/emit "cpp/io/basic osyncstream/emit") | calls emit on the underlying basic\_syncbuf to transmit its internal data to the final destination (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | | [(constructor)](basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::set_emit_on_sync std::basic\_syncbuf<CharT,Traits,Allocator>::set\_emit\_on\_sync ================================================================ | | | | | --- | --- | --- | | ``` void set_emit_on_sync( bool b ) noexcept; ``` | | | Changes the current emit-on-sync policy. The value `false` (the default) indicates that any flush will be postponed until a call to emit. The value `true` makes flushes apply immediately. ### Parameters | | | | | --- | --- | --- | | b | - | new value for the emit-on-sync policy | ### Example ### See also | | | | --- | --- | | [sync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [emit](emit "cpp/io/basic syncbuf/emit") | atomically transmits the entire internal buffer to the wrapped streambuf (public member function) | | [emit\_on\_flushnoemit\_on\_flush](../manip/emit_on_flush "cpp/io/manip/emit on flush") (C++20) | controls whether a stream's [`basic_syncbuf`](../basic_syncbuf "cpp/io/basic syncbuf") emits on flush (function template) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::~basic_syncbuf std::basic\_syncbuf<CharT,Traits,Allocator>::~basic\_syncbuf ============================================================ | | | | | --- | --- | --- | | ``` ~basic_syncbuf(); ``` | | | Calls [`emit()`](emit "cpp/io/basic syncbuf/emit") to transmit all pending output (and delayed flush, if any) to the wrapped stream. If an exception is thrown by this call, it is caught and ignored. ### Parameters (none). ### Notes Normally called by the destructor of the owning `std::basic_osyncstream`. ### Example ### See also | | | | --- | --- | | [(destructor)](../basic_osyncstream/~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream") | destroys the basic\_osyncstream and emits its internal buffer (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | | [(constructor)](basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::sync std::basic\_syncbuf<CharT,Traits,Allocator>::sync ================================================= | | | | | --- | --- | --- | | ``` protected: int sync() override; ``` | | | First, records that a flush is pending, by updating the appropriate private flag. Then, if the current emit-on-sync policy is `true`, makes a call to [`emit()`](emit "cpp/io/basic syncbuf/emit"). Otherwise (if the emit-on-sync policy is `false`, which is the default), the flush is suspended until [`emit()`](emit "cpp/io/basic syncbuf/emit") is called, such as through [`std::basic_osyncstream::emit()`](../basic_osyncstream/emit "cpp/io/basic osyncstream/emit") or [`std::basic_osyncstream::~basic_osyncstream`](../basic_osyncstream/~basic_osyncstream "cpp/io/basic osyncstream/~basic osyncstream"). ### Parameters (none). ### Notes `sync()` or its equivalent is implicitly called by `close()`, `seekoff()`, and `seekpos()` and explicitly called by `[std::basic\_streambuf::pubsync()](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync")`. ### Example ### See also | | | | --- | --- | | [sync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [emit](../basic_osyncstream/emit "cpp/io/basic osyncstream/emit") | calls emit on the underlying basic\_syncbuf to transmit its internal data to the final destination (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | cpp std::swap(std::basic_syncbuf) std::swap(std::basic\_syncbuf) ============================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Allocator > void swap( std::basic_syncbuf<CharT, Traits, Allocator>& lhs, std::basic_syncbuf<CharT, Traits, Allocator>& rhs ); ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `std::basic_syncbuf`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `std::basic_syncbuf` objects whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic syncbuf/swap") | swaps two basic\_syncbuf objects (public member function) | | [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | cpp std::basic_syncbuf<CharT,Traits,Allocator>::operator= std::basic\_syncbuf<CharT,Traits,Allocator>::operator= ====================================================== | | | | | --- | --- | --- | | ``` basic_syncbuf& operator=(basic_syncbuf&& other); ``` | | | First, calls [`emit()`](emit "cpp/io/basic syncbuf/emit") to transmit all pending output (and delayed flush, if any) to the wrapped stream. Then performs move-assignment by moving all contents from `other`, including the temporary storage, the wrapped stream pointer, policy, and all other state (such as the mutex pointer). After move, `other` is not associated with a stream, and `other.get_wrapped()==nullptr`. The put area member pointers of the base class `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` of `other` are guaranteed to be null. Destroying a moved-from `other` will not produce any output. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::propagate\_on\_container\_move\_assignment::value` is `false`, then the allocator is unchanged. Otherwise, after move-assignment, `get_allocator()` equals `other.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | other | - | another std::basic\_syncbuf to move from | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [operator=](../basic_osyncstream/operator= "cpp/io/basic osyncstream/operator=") | assigns a basic\_osyncstream (public member function of `std::basic_osyncstream<CharT,Traits,Allocator>`) | | [(constructor)](basic_syncbuf "cpp/io/basic syncbuf/basic syncbuf") | constructs a basic\_syncbuf object (public member function) | | [emit](emit "cpp/io/basic syncbuf/emit") | atomically transmits the entire internal buffer to the wrapped streambuf (public member function) | | [swap](swap "cpp/io/basic syncbuf/swap") | swaps two basic\_syncbuf objects (public member function) |
programming_docs
cpp std::basic_ostream<CharT,Traits>::operator<< std::basic\_ostream<CharT,Traits>::operator<< ============================================= | | | | | --- | --- | --- | | ``` basic_ostream& operator<<( short value ); basic_ostream& operator<<( unsigned short value ); ``` | (1) | | | ``` basic_ostream& operator<<( int value ); basic_ostream& operator<<( unsigned int value ); ``` | (2) | | | ``` basic_ostream& operator<<( long value ); basic_ostream& operator<<( unsigned long value ); ``` | (3) | | | ``` basic_ostream& operator<<( long long value ); basic_ostream& operator<<( unsigned long long value ); ``` | (4) | (since C++11) | | ``` basic_ostream& operator<<( float value ); basic_ostream& operator<<( double value ); basic_ostream& operator<<( long double value ); ``` | (5) | | | ``` basic_ostream& operator<<( bool value ); ``` | (6) | | | ``` basic_ostream& operator<<( const void* value ); ``` | (7) | | | ``` basic_ostream& operator<<( const volatile void* value ); ``` | (8) | (since C++23) | | ``` basic_ostream& operator<<( std::nullptr_t ); ``` | (9) | (since C++17) | | ``` basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb ); ``` | (10) | | | ``` basic_ostream& operator<<( std::ios_base& (*func)(std::ios_base&) ); ``` | (11) | | | ``` basic_ostream& operator<<( std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) ); ``` | (12) | | | ``` basic_ostream& operator<<( std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) ); ``` | (13) | | Inserts data into the stream. 1-2) Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). After constructing and checking the sentry object, if `value` is `short` or `int`, then casts it to `unsigned short` or `unsigned int` if `ios_base::flags() & ios_base::basefield` is `ios_base::oct` or `ios_base::hex`. After that, casts it to `long` in any case and outputs as in (3). If `value` is `unsigned short` or `unsigned int`, casts it to `unsigned long` and outputs as in (3). 3-7) Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). If `value` is `float`, casts it to `double` and outputs as in (5). After constructing and checking the sentry object, inserts an integer, floating point, boolean or generic pointer value by calling [`std::num_put::put()`](../../locale/num_put/put "cpp/locale/num put/put"). If the end of file condition was encountered during output (`put().failed() == true`), sets `ios::badbit`. 8) Casts `value` to `const void*` and outputs as in (7). 9) Outputs an implementation-defined string as if by `*this << s`, where `s` is a null-terminated character type string. 10) Behaves as an [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction"). After constructing and checking the sentry object, checks if `sb` is a null pointer. If it is, executes `setstate(badbit)` and exits. Otherwise, extracts characters from the input sequence controlled by `sb` and inserts them into `*this` until one of the following conditions are met: * end-of-file occurs on the input sequence; * inserting in the output sequence fails (in which case the character to be inserted is not extracted); * an exception occurs (in which case the exception is caught). If no characters were inserted, executes `setstate(failbit)`. If an exception was thrown while extracting, sets `failbit` and, if `failbit` is set in `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")`, rethrows the exception. 11-13) Calls `func(*this)`. These overloads are used to implement output I/O manipulators such as `[std::endl](../manip/endl "cpp/io/manip/endl")`. ### Parameters | | | | | --- | --- | --- | | value | - | integer, floating-point, boolean, or pointer value to insert | | func | - | function to call | | sb | - | pointer to the stream buffer to read the data from | ### Return value 1-12) `*this` 13) `func(*this)` ### Notes There are no overloads for pointers to non-static members, pointers to volatiles, (until C++23) or function pointers (other than the ones with signatures accepted by the (11-13) overloads). Attempting to output such objects invokes implicit conversion to `bool`, and, for any non-null pointer value, the value `1` is printed (unless `boolalpha` was set, in which case `true` is printed). Character and character string arguments (e.g., of type `char` or `const char*`) are handled by the [non-member overloads](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") of `operator<<`. Attempting to output a character using the member function call syntax (e.g., `[std::cout](http://en.cppreference.com/w/cpp/io/cout).operator<<('c');`) will call one of overloads (2-4) and output the numerical value. Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead. ### Example ``` #include <iostream> #include <iomanip> #include <sstream> int fun() { return 42; } int main() { std::istringstream input(" \"Some text.\" "); double f = 3.14; bool b = true; std::cout << fun() // int overload (2) << ' ' // non-member overload << std::boolalpha // function overload (11) << b // bool overload (6) << " " // non-member overload << std::fixed // function overload (11) again << f // double overload (5) << input.rdbuf() // streambuf overload << fun // bool overload (6): there's no overload for int(*)() << std::endl; // function overload (11) again int x = 0; int* p1 = &x; volatile int* p2 = &x; std::cout << "p1: " << p1 << '\n' // `const void*` overload, prints address << "p2: " << p2 << '\n'; // before C++23 (P1147): bool overload :), because // operator<<(const void*) is not a match, as it discards the `volatile` // qualifier. To fix this, C++23 adds `const volatile void*` overload, // that prints the address as expected. } ``` Possible output: ``` 42 true 3.140000 "Some text." true p1: 0x7ffcea766600 p2: 0x7ffcea766600 ``` ### 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 117](https://cplusplus.github.io/LWG/issue117) | C++98 | overloads (1)-(7) delegated the insertion to[`num_put::put`](../../locale/num_put/put "cpp/locale/num put/put"), but it does not have overloads for `short`,`unsigned short`, `int`, `unsigned int`, and `float` | they are convertedbefore being passedto `num_put::put` | ### See also | | | | --- | --- | | [operator<<(std::basic\_ostream)](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [operator<<operator>>](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) | | [operator<<](../../string/basic_string_view/operator_ltlt "cpp/string/basic string view/operator ltlt") (C++17) | performs stream output on string views (function template) | | [operator<<operator>>](../../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") | performs stream input and output of bitsets (function template) | | [operator<<operator>>](../../numeric/complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") | serializes and deserializes a complex number (function template) | | [operator<<operator>>](../../numeric/random/linear_congruential_engine/operator_ltltgtgt "cpp/numeric/random/linear congruential engine/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number engine (function template) | | [operator<<operator>>](../../numeric/random/uniform_int_distribution/operator_ltltgtgt "cpp/numeric/random/uniform int distribution/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number distribution (function template) | | [put](put "cpp/io/basic ostream/put") | inserts a character (public member function) | | [write](write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function) | | [to\_chars](../../utility/to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | cpp std::basic_ostream<CharT,Traits>::seekp std::basic\_ostream<CharT,Traits>::seekp ======================================== | | | | | --- | --- | --- | | ``` basic_ostream& seekp( pos_type pos ); ``` | (1) | | | ``` basic_ostream& seekp( off_type off, std::ios_base::seekdir dir ); ``` | (2) | | Sets the output position indicator of the current associated `streambuf` object. | | | | --- | --- | | Behaves as [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction") (except without actually performing output). After constructing and checking the sentry object, | (since C++11) | 1) sets the output position indicator to absolute (relative to the beginning of the file) value `pos` by calling `rdbuf()->pubseekpos(pos, [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. If the call returns `(pos_type)-1`, executes `setstate(failbit)`. 2) sets the output position indicator to offset `off` relative to `dir` by calling `rdbuf()->pubseekoff(off, dir, [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. If the call returns `(pos_type)-1`, executes `setstate(failbit)`. ### Parameters | | | | | --- | --- | --- | | pos | - | absolute position to set the output position indicator to. | | off | - | relative position (positive or negative) to set the output position indicator to. | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | ### Return value `*this`. ### Exceptions 1-2) May throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` in case of failure, if `exceptions() & failbit != 0`. ### Example ``` #include <sstream> #include <iostream> int main() { std::ostringstream os("hello, world"); os.seekp(7); os << 'W'; os.seekp(0, std::ios_base::end); os << '!'; os.seekp(0); os << 'H'; std::cout << os.str() << '\n'; } ``` Output: ``` Hello, World! ``` ### 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 2341](https://cplusplus.github.io/LWG/issue2341) | C++98 | two overloads behaved differently on failure | made consistent | ### See also | | | | --- | --- | | [tellp](tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function) | | [tellg](../basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](../basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_ostream<CharT,Traits>::swap std::basic\_ostream<CharT,Traits>::swap ======================================= | | | | | --- | --- | --- | | ``` protected: void swap(basic_ostream& rhs); ``` | | (since C++11) | Calls `basic_ios::swap(rhs)` to swap all data members of the base class, except for `rdbuf()`, between `*this` and `rhs`. This swap function is protected: it is called by the swap functions of the swappable output stream classes `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` and `[std::basic\_ostringstream](../basic_ostringstream "cpp/io/basic ostringstream")`, which know how to correctly swap the associated streambuffers. ### Parameters | | | | | --- | --- | --- | | rhs | - | a basic\_ostream of the same type to swap with | ### Example ``` #include <sstream> #include <iostream> #include <utility> int main() { std::ostringstream s1("hello"); std::ostringstream s2("bye"); s1.swap(s2); // OK, ostringstream has a public swap() std::swap(s1, s2); // OK, calls s1.swap(s2) // std::cout.swap(s2); // ERROR: swap is a protected member std::cout << s1.str() << '\n'; } ``` Output: ``` hello ``` cpp std::basic_ostream<CharT,Traits>::basic_ostream std::basic\_ostream<CharT,Traits>::basic\_ostream ================================================= | | | | | --- | --- | --- | | ``` explicit basic_ostream( std::basic_streambuf<CharT, Traits>* sb ); ``` | (1) | | | ``` protected: basic_ostream( const basic_ostream& rhs ) = delete; ``` | (2) | (since C++11) | | ``` protected: basic_ostream( basic_ostream&& rhs ); ``` | (3) | (since C++11) | 1) Constructs the `basic_ostream` object, assigning initial values to the base class by calling `[basic\_ios::init(sb)](../basic_ios/init "cpp/io/basic ios/init")`. 2) The copy constructor is protected, and is deleted. Output streams are not copyable. 3) The move constructor uses `basic_ios<CharT, Traits>::move(rhs)` to move all `basic_ios` members, except for the `rdbuf()`, from `rhs` into `*this`. This move constructor is protected: it is called by the move constructors of movable output stream classes `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` and `[std::basic\_ostringstream](../basic_ostringstream "cpp/io/basic ostringstream")`, which know how to correctly move the associated streambuffer. ### Parameters | | | | | --- | --- | --- | | sb | - | streambuffer to use as output sequence | | rhs | - | basic\_ostream to initialize from | ### Notes Because `[basic\_ios::init(sb)](../basic_ios/init "cpp/io/basic ios/init")` sets `badbit` when `sb` is a null pointer, and because [`basic_ostream::sentry`](sentry "cpp/io/basic ostream/sentry") does nothing if the stream is already in a failed state, writing to a stream constructed from a null pointer `sb` is a no-op. ### Example ``` #include <sstream> #include <utility> #include <iostream> int main() { // ERROR: copy ctor is deleted // std::ostream myout(std::cout); // OK: shares buffer with cout std::ostream myout(std::cout.rdbuf()); // ERROR: move constructor is protected // std::ostream s2(std::move(std::ostringstream() << 7.1)); // OK: move ctor called through the derived class std::ostringstream s2(std::move(std::ostringstream() << 7.1)); myout << s2.str() << '\n'; std::ostream dev_null{nullptr}; // see Notes above dev_null << "no-op"; } ``` Output: ``` 7.1 ``` cpp std::basic_ostream<CharT,Traits>::sentry std::basic\_ostream<CharT,Traits>::sentry ========================================= | | | | | --- | --- | --- | | ``` class sentry; ``` | | | An object of class `basic_ostream::sentry` is constructed in local scope at the beginning of each member function of `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` that performs output (both formatted and unformatted). Its constructor prepares the output stream: checks if the stream is already in a failed state, flushes the tie()'d output streams, and performs other implementation-defined tasks if necessary. Implementation-defined cleanup, as well as flushing of the output stream if necessary, is performed in the destructor, so that it is guaranteed to happen if exceptions are thrown during output. ### Member functions | | | | --- | --- | | **(constructor)** | constructs the sentry object. All the preparation tasks are done here (public member function) | | **(destructor)** | finalizes the stream object after formatted output or after exception, if necessary (public member function) | | operator= | the assignment operator is deleted (public member function) | | **operator bool** | checks if the preparation of the stream object was successful (public member function) | std::basic\_ostream::sentry::sentry ------------------------------------ | | | | | --- | --- | --- | | ``` explicit sentry( std::basic_ostream<CharT,Traits>& os ); ``` | | | Prepares the stream for formatted output. If `os.good()` is `false`, returns. Otherwise, if `os.tie()` is not a null pointer, calls `os.tie()->flush()` to synchronize the output sequence with external streams. During preparation, the constructor may call `setstate(failbit)` (which may throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")`). If after preparation is completed, `os.good() == true`, then any subsequent calls to `operator bool` will return `true`. ### Parameters | | | | | --- | --- | --- | | os | - | output stream to prepare | ### Exceptions `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` if the end of file condition occurs. std::basic\_ostream::sentry::~sentry ------------------------------------- | | | | | --- | --- | --- | | ``` ~sentry(); ``` | | | If `(os.flags() & [std::ios\_base::unitbuf](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)) && ![std::uncaught\_exception](http://en.cppreference.com/w/cpp/error/uncaught_exception)() && os.good())` is `true`, calls `os.rdbuf()->pubsync()`. If that function returns `-1`, sets `badbit` in `os.rdstate()` without propagating an exception. std::basic\_ostream::sentry::operator bool ------------------------------------------- | | | | | --- | --- | --- | | ``` explicit operator bool() const; ``` | | | Checks whether the preparation of the output stream was successful. ### Parameters (none). ### Return value `true` if the preparation of the output stream was successful, `false` otherwise. ### Example ``` #include <iostream> #include <sstream> struct Foo { char n[6]; }; std::ostream& operator<<(std::ostream& os, Foo& f) { std::ostream::sentry s(os); if (s) { os.write(f.n, 5); } return os; } int main() { Foo f = { "abcde" }; std::cout << f << '\n'; } ``` Output: ``` abcde ``` ### See also | | | | --- | --- | | [operator<<](operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function) | cpp print(std::basic_ostream) print(std::basic\_ostream) ========================== | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | ``` template< class... Args > void print( std::ostream& os, std::format_string<Args...> fmt, Args&&... args ); ``` | | (since C++23) | Formats `args` according to the format string `fmt`, and inserts the result into `os` stream. If [ordinary literal encoding](../../language/charset "cpp/language/charset") of `fmt` or any parameter in `args...` is UTF-8 (where applicable), equivalent to: ``` std::vprint_unicode(os, fmt.get(), std::make_format_args(std::forward<Args>(args)...)); ``` Otherwise, equivalent to: ``` std::vprint_nonunicode(os, fmt.get(), std::make_format_args(std::forward<Args>(args)...)); ``` The behavior is undefined if `[std::formatter](http://en.cppreference.com/w/cpp/utility/format/formatter)<Ti, char>` does not model `std::formattable` for any `Ti` in `Args` (as required by `[std::make\_format\_args](http://en.cppreference.com/w/cpp/utility/format/make_format_args)`). ### Parameters | | | | | --- | --- | --- | | os | - | output stream to insert data into | | fmt | - | an object that represents the format string. The format string consists of * ordinary characters (except `{` and `}`), which are copied unchanged to the output, * escape sequences `{{` and `}}`, which are replaced with `{` and `}` respectively in the output, and * replacement fields. Each replacement field has the following format: | | | | | --- | --- | --- | | `{` arg-id (optional) `}` | (1) | | | `{` arg-id (optional) `:` format-spec `}` | (2) | | 1) replacement field without a format specification 2) replacement field with a format specification | | | | | --- | --- | --- | | arg-id | - | specifies the index of the argument in `args` whose value is to be used for formatting; if it is omitted, the arguments are used in order. The arg-ids in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error. | | format-spec | - | the format specification defined by the `[std::formatter](../../utility/format/formatter "cpp/utility/format/formatter")` specialization for the corresponding argument. | * For basic types and standard string types, the format specification is interpreted as [standard format specification](../../utility/format/formatter#Standard_format_specification "cpp/utility/format/formatter"). * For chrono types, the format specification is interpreted as [chrono format specification](../../chrono/system_clock/formatter#Format_specification "cpp/chrono/system clock/formatter"). * For other formattable types, the format specification is determined by user-defined `formatter` specializations. | | args... | - | arguments to be formatted | ### Return value (none). ### Exceptions ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_print`](../../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_format`](../../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | ### Example ### See also | | | | --- | --- | | [println](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/println&action=edit&redlink=1 "cpp/io/basic ostream/println (page does not exist)") (C++23) | outputs [formatted](../../utility/format "cpp/utility/format") representation of the arguments with appended `'\n'` (function template) | | [print](../print "cpp/io/print") (C++23) | prints to `[stdout](../c/std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../../utility/format "cpp/utility/format") representation of the arguments (function template) | | [format](../../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) |
programming_docs
cpp std::basic_ostream<CharT,Traits>::flush std::basic\_ostream<CharT,Traits>::flush ======================================== | | | | | --- | --- | --- | | ``` basic_ostream& flush(); ``` | | | Writes uncommitted changes to the underlying output sequence. If rdbuf() is a null pointer, does nothing. Otherwise, behaves as an [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction") (since C++11). After constructing and checking the sentry object, calls `rdbuf()->pubsync()`. If the call returns `-1`, calls `setstate(badbit)`. ### Parameters (none). ### Return value `*this`. ### Exceptions May throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` if `(exceptions() & badbit) != 0`. ### Example ``` #include <thread> #include <iostream> #include <chrono> using namespace std::chrono_literals; void f() { std::cout << "Output from thread... "; for (int i{1}; i != 10; ++i) { std::this_thread::sleep_for(250ms); std::cout << i << ' '; // output three numbers at once; // the effect is observable only in real-time if (0 == (i % 3)) { std::cout.flush(); } } std::cout << std::endl; // flushes as well } int main() { std::thread tr{f}; std::this_thread::sleep_for(150ms); std::clog << "Output from main\n"; tr.join(); } ``` Output: ``` Output from main Output from thread... 1 2 3 4 5 6 7 8 9 ``` ### See also | | | | --- | --- | | [pubsync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") | invokes `sync()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [flush](../manip/flush "cpp/io/manip/flush") | flushes the output stream (function template) | | [endl](../manip/endl "cpp/io/manip/endl") | outputs `'\n'` and flushes the output stream (function template) | | [sync](../basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_ostream<CharT,Traits>::~basic_ostream std::basic\_ostream<CharT,Traits>::~basic\_ostream ================================================== | | | | | --- | --- | --- | | ``` virtual ~basic_ostream(); ``` | | | Destroys the `basic_ostream` object. This destructor does not perform any operation on the underlying streambuffer (`rdbuf()`): the destructors of the derived output streams such as `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` and `[std::basic\_ostringstream](../basic_ostringstream "cpp/io/basic ostringstream")` are responsible for calling the destructors of the stream buffers. ### Example ``` #include <sstream> #include <iostream> void add_words(std::streambuf* p) { std::ostream buf(p); // buf shares the buffer with s buf << " is the answer"; } // calls the destructor of buf. p remains unaffected int main() { std::ostringstream s; s << 42; add_words(s.rdbuf()); s << "."; std::cout << s.str() << '\n'; } ``` Output: ``` 42 is the answer. ``` cpp std::basic_ostream<CharT,Traits>::tellp std::basic\_ostream<CharT,Traits>::tellp ======================================== | | | | | --- | --- | --- | | ``` pos_type tellp(); ``` | | | Returns the output position indicator of the current associated `streambuf` object. | | | | --- | --- | | Behaves as [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction") (except without actually performing output). After constructing and checking the sentry object, | (since C++11) | If `fail()==true`, returns `pos_type(-1)`. Otherwise, returns `rdbuf()->pubseekoff(0, [std::ios\_base::cur](http://en.cppreference.com/w/cpp/io/ios_base/seekdir), [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. ### Parameters (none). ### Return value current output position indicator on success, `pos_type(-1)` if a failure occurs. ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream s; std::cout << s.tellp() << '\n'; s << 'h'; std::cout << s.tellp() << '\n'; s << "ello, world "; std::cout << s.tellp() << '\n'; s << 3.14 << '\n'; std::cout << s.tellp() << '\n' << s.str(); } ``` Output: ``` 0 1 13 18 hello, world 3.14 ``` ### See also | | | | --- | --- | | [seekp](seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function) | | [tellg](../basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [seekg](../basic_istream/seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_ostream<CharT,Traits>::operator= std::basic\_ostream<CharT,Traits>::operator= ============================================ | | | | | --- | --- | --- | | ``` protected: basic_ostream& operator=( const basic_ostream& rhs ) = delete; ``` | (1) | | | ``` protected: basic_ostream& operator=( basic_ostream&& rhs ); ``` | (2) | (since C++11) | 1) The copy assignment operator is protected, and is deleted. Output streams are not CopyAssignable. 2) The move assignment operator exchanges all data members of the base class, except for `rdbuf()`, with `rhs`, as if by calling `swap(*rhs)`. This move assignment operator is protected: it is only called by the move assignment operators of the derived movable output stream classes `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` and `[std::basic\_ostringstream](../basic_ostringstream "cpp/io/basic ostringstream")`, which know how to correctly move-assign the associated streambuffers. ### Parameters | | | | | --- | --- | --- | | rhs | - | the basic\_ostream object from which to assign to `*this` | ### Example ``` #include <sstream> #include <utility> #include <iostream> int main() { std::ostringstream s; // std::cout = s; // ERROR: copy assignment operator is deleted // std::cout = std::move(s); // ERROR: move assignment operator is protected s = std::move(std::ostringstream() << 42); // OK, moved through derived std::cout << s.str() << '\n'; } ``` Output: ``` 42 ``` cpp std::basic_ostream<CharT,Traits>::put std::basic\_ostream<CharT,Traits>::put ====================================== | | | | | --- | --- | --- | | ``` basic_ostream& put( char_type ch ); ``` | | | Behaves as an [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction"). After constructing and checking the sentry object, writes the character `ch` to the output stream. If the output fails for any reason, sets `badbit`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to write | ### Return value `*this`. ### Notes This function is not overloaded for the types `signed char` or `unsigned char`, unlike the formatted [operator<<](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2"). Unlike formatted output functions, this function does not set the `failbit` if the output fails. ### Example ``` #include <fstream> #include <iostream> int main() { std::cout.put('a'); // normal usage std::cout.put('\n'); std::ofstream s("/does/not/exist/"); s.clear(); // pretend the stream is good std::cout << "Unformatted output: "; s.put('c'); // this will set badbit, but not failbit std::cout << " fail=" << bool(s.rdstate() & s.failbit); std::cout << " bad=" << s.bad() << '\n'; s.clear(); std::cout << "Formatted output: "; s << 'c'; // this will set badbit and failbit std::cout << " fail=" << bool(s.rdstate() & s.failbit); std::cout << " bad=" << s.bad() << '\n'; } ``` Output: ``` a Unformatted output: fail=0 bad=1 Formatted output: fail=1 bad=1 ``` ### See also | | | | --- | --- | | [operator<<(std::basic\_ostream)](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [write](write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function) | cpp std::basic_ostream<CharT,Traits>::write std::basic\_ostream<CharT,Traits>::write ======================================== | | | | | --- | --- | --- | | ``` basic_ostream& write( const char_type* s, std::streamsize count ); ``` | | | Behaves as an [UnformattedOutputFunction](../../named_req/unformattedoutputfunction "cpp/named req/UnformattedOutputFunction"). After constructing and checking the sentry object, outputs the characters from successive locations in the character array whose first element is pointed to by `s`. Characters are inserted into the output sequence until one of the following occurs: * exactly `count` characters are inserted * inserting into the output sequence fails (in which case `setstate(badbit)` is called) ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the character string to write | | count | - | number of characters to write | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Notes This function is not overloaded for the types `signed char` or `unsigned char`, unlike the formatted [operator<<](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") Also, unlike the formatted output functions, this function does not set the `failbit` on failure. When using a non-converting locale (the default locale is non-converting), the overrider of this function in `[std::basic\_ofstream](../basic_ofstream "cpp/io/basic ofstream")` may be optimized for zero-copy bulk I/O (by means of overriding `[std::streambuf::xsputn](../basic_streambuf/sputn "cpp/io/basic streambuf/sputn")`). ### Example This function may be used to output object representations, i.e. binary output. ``` #include <iostream> int main() { int n = 0x41424344; std::cout.write(reinterpret_cast<char*>(&n), sizeof n) << '\n'; char c[]="This is sample text."; std::cout.write(c, 4).write("!\n", 2); } ``` Possible output: ``` DCBA This! ``` ### See also | | | | --- | --- | | [operator<<(std::basic\_ostream)](operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [put](put "cpp/io/basic ostream/put") | inserts a character (public member function) | cpp operator<<(std::basic_ostream) operator<<(std::basic\_ostream) =============================== | Defined in header `[<ostream>](../../header/ostream "cpp/header/ostream")` | | | | --- | --- | --- | | basic\_ostream and character | | | | | (1) | | | ``` template< class CharT, class Traits> basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, CharT ch ); ``` | | | ``` template< class CharT, class Traits> basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, char ch ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, char ch ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, signed char ch ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, unsigned char ch ); ``` | | | basic\_ostream and character array | | | | | (2) | | | ``` template< class CharT, class Traits > basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, const CharT* s ); ``` | | | ``` template< class CharT, class Traits > basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, const char* s ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const char* s ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const signed char* s ); ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const unsigned char* s ); ``` | | | basic\_ostream rvalue | | | | ``` template< class Ostream, class T > Ostream&& operator<<( Ostream&& os, const T& value ); ``` | (3) | (since C++11) | | deleted overloads for basic\_ostream and UTF character/array | | | | | (4) | (since C++20) | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, wchar_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, char8_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, char16_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, char32_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, char8_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, char16_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, char32_t ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const wchar_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const char8_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const char16_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, const char32_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, const char8_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, const char16_t* ch ) = delete; ``` | | | ``` template< class Traits > basic_ostream<wchar_t,Traits>& operator<<( basic_ostream<wchar_t,Traits>& os, const char32_t* ch ) = delete; ``` | | Inserts a character or a character string. 1) Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). After constructing and checking the sentry object, inserts the character `ch`. If the type of the character is not `CharT`, it is first converted with `os.widen(ch)`. Padding is determined as follows: if `os.width()>1`, then `os.width()-1` copies of `os.fill()` are added to the output character to form the output character sequence. If `(out.flags()&[std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)) == [std::ios\_base::left](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, the fill characters are placed after the output character, otherwise before. After insertion, `os.width(0)` is called to cancel the effects of `[std::setw](../manip/setw "cpp/io/manip/setw")`, if any. 2) Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). After constructing and checking the sentry object, inserts successive characters from the character array whose first element is pointed to by `s`. * for the first and third overloads (where `CharT` matches the type of `ch`), exactly `traits::length(s)` characters are inserted. * for the second overload, exactly `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char>::length(s)` characters are inserted. * for the last two overloads, exactly `traits::length(reinterpret_cast<const char*>(s))` are inserted. Before insertion, first, all characters are widened using `os.widen()`, then padding is determined as follows: if the number of characters to insert is less than `os.width()`, then enough copies of `os.fill()` are added to the character sequence to make its length equal `os.width()`. If `(out.flags()&[std::ios\_base::adjustfield](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)) == [std::ios\_base::left](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`, the fill characters are added at the end of the output sequence, otherwise they are added before the output sequence. After insertion, `width(0)` is called to cancel the effects of `[std::setw](../manip/setw "cpp/io/manip/setw")`, if any. The behavior is undefined if `s` is a null pointer. 3) Calls the appropriate insertion operator, given an rvalue reference to an output stream object (equivalent to `os << value`). This overload participates in overload resolution only if the expression `os << value` is well-formed and `Ostream` is a class type publicly and unambiguously derived from `[std::ios\_base](../ios_base "cpp/io/ios base")`. 4) Overloads that accept `char16_t`, `char32_t` etc (or null terminated sequence thereof) are deleted: `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << u'X'` is not allowed. Previously, these would print an integer or pointer value. ### Parameters | | | | | --- | --- | --- | | os | - | output stream to insert data to | | ch | - | reference to a character to insert | | s | - | pointer to a character string to insert | ### Return value 1-2) `os` 3) `std::move(os)` ### Notes Before [LWG issue 1203](https://cplusplus.github.io/LWG/issue1203), code such as `([std::ostringstream](http://en.cppreference.com/w/cpp/io/basic_ostringstream)() << 1.2).str()` does not compile. ### Example ``` #include <iostream> #include <fstream> void foo() { // std::cout << u8'z' << '\n'; // error: operator<< (basic_ostream<char, // _Traits>&, char8_t) is deleted } std::ostream& operator<<(std::ostream& os, char8_t const& ch) { return os << static_cast<char>(ch); } int main() { std::cout << "Hello, world" // uses `const char*` overload << '\n'; // uses `char` overload std::ofstream{"test.txt"} << 1.2; // uses rvalue overload std::cout << u8'!' << '\n'; // uses program-defined operator<<(os, char8_t const&) } ``` Output: ``` Hello, world ! ``` ### 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 1203](https://cplusplus.github.io/LWG/issue1203) | C++11 | overload for rvalue stream returned lvalue reference to the base class | returns rvalue reference to the derived class | | [LWG 2534](https://cplusplus.github.io/LWG/issue2534) | C++11 | overload for rvalue stream was not constrained | constrained | ### See also | | | | --- | --- | | [operator<<](operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function) | | [widen](../basic_ios/widen "cpp/io/basic ios/widen") | widens characters (public member function of `std::basic_ios<CharT,Traits>`) |
programming_docs
cpp std::strstreambuf::freeze std::strstreambuf::freeze ========================= | | | | | --- | --- | --- | | ``` void freeze( bool freezefl = true ); ``` | | | If the buffer uses dynamic allocation, sets the frozen status of the stream to `freezefl`. While the stream is frozen, `[overflow()](overflow "cpp/io/strstreambuf/overflow")` will not reallocate the buffer and the `destructor` will not deallocate the buffer (thereby causing a memory leak). ### Parameters | | | | | --- | --- | --- | | freezefl | - | new value to set the freeze status to | ### Return value (none). ### Notes Every call to `[str()](str "cpp/io/strstreambuf/str")` freezes the stream to preserve the validity of the pointer it returns. To allow the destructor to deallocate the buffer, `freeze(false)` needs to be called explicitly. ### Example In this example, initial allocation of the underlying array was for 16 bytes. ``` #include <strstream> #include <iostream> int main() { { std::strstream dyn; // dynamically-allocated read/write buffer dyn << "Test: " << 1.23; // note: no std::ends to demonstrate append behavior std::cout << "dynamic buffer holds " << dyn.pcount() << " characters: '"; std::cout.write(dyn.str(), dyn.pcount()) << "'\n"; // the buffer is now frozen, further output will not make the buffer grow dyn << "more output, hopefully enough to run out of the allocated space" << std::ends; std::cout << "After more output, it holds " << dyn.pcount() << " characters: '" << dyn.str() << "'\n"; dyn.freeze(false); // unfreeze before destructor } // memory freed by the destructor { char arr[20]; std::ostrstream st(arr, sizeof arr); // fixed-size buffer st << 1.23; // note: no std::ends to demonstrate append behavior std::cout << "static buffer holds " << st.pcount() << " characters: '"; std::cout.write(st.str(), st.pcount()); std::cout << "'\n"; st << "more output, hopefully enough to run out of the allocated space" << std::ends; std::cout << "static buffer holds " << st.pcount() << " characters: '"; std::cout.write(st.str(), st.pcount()); std::cout << "'\n"; } // nothing to deallocate, no need to unfreeze, } ``` Output: ``` dynamic buffer holds 10 characters: 'Test: 1.23' After more output, it holds 16 characters: 'Test: 1.23more o' static buffer holds 4 characters: '1.23' static buffer holds 20 characters: '1.23more output, hop' ``` ### See also | | | | --- | --- | | [freeze](../strstream/freeze "cpp/io/strstream/freeze") | disables/enables automatic reallocation (public member function of `std::strstream`) | | [freeze](../ostrstream/freeze "cpp/io/ostrstream/freeze") | disables/enables automatic reallocation (public member function of `std::ostrstream`) | | [(destructor)](~strstreambuf "cpp/io/strstreambuf/~strstreambuf") [virtual] | destructs a strstreambuf object, optionally deallocating the character array (virtual public member function) | | [overflow](overflow "cpp/io/strstreambuf/overflow") [virtual] | appends a character to the output sequence, may reallocate or initially allocate the buffer if dynamic and not frozen (virtual protected member function) | cpp std::strstreambuf::underflow std::strstreambuf::underflow ============================ | | | | | --- | --- | --- | | ``` protected: virtual int_type underflow(); ``` | | | Reads the next character from the get area of the buffer. If the input sequence has a read position available (`gptr() < egptr()`, returns `(unsigned char)(*gptr())`. Otherwise, if `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` is not null and `pptr() > egptr()` (there is a put area and it is located after the get area), extends the end of the get area to include the characters that were recently written into the put area by incrementing `[egptr()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` to some value between `gptr()` and `[pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, and then returns `(unsigned char)(*gptr())`. Otherwise, returns `[EOF](../c "cpp/io/c")` to indicate failure. ### Parameters (none). ### Return value The next character in the get area, `(unsigned char)(*gptr())` on success, `[EOF](../c "cpp/io/c")` on failure. ### Example ``` #include <strstream> #include <iostream> struct mybuf : std::strstreambuf { int_type overflow(int_type c) { std::cout << "Before overflow(): size of the get area is " << egptr()-eback() << " size of the put area is " << epptr()-pbase() << '\n'; int_type rc = std::strstreambuf::overflow(c); std::cout << "After overflow(): size of the get area is " << egptr()-eback() << " size of the put area is " << epptr()-pbase() << '\n'; return rc; } int_type underflow() { std::cout << "Before underflow(): size of the get area is " << egptr()-eback() << " size of the put area is " << epptr()-pbase() << '\n'; int_type ch = std::strstreambuf::underflow(); std::cout << "After underflow(): size of the get area is " << egptr()-eback() << " size of the put area is " << epptr()-pbase() << '\n'; if (ch == EOF) { std::cout << "underflow() returns EOF\n"; } else { std::cout << "underflow() returns '" << char(ch) << "'\n"; } return ch; } }; int main() { mybuf sbuf; // read-write dynamic strstreambuf std::iostream stream(&sbuf); int n; stream >> n; stream.clear(); stream << "123"; stream >> n; std::cout << n << '\n'; } ``` Possible output: ``` Before underflow(): size of the get area is 0 size of the put area is 0 After underflow(): size of the get area is 0 size of the put area is 0 underflow() returns EOF Before overflow(): size of the get area is 0 size of the put area is 0 After overflow(): size of the get area is 0 size of the put area is 32 Before underflow(): size of the get area is 0 size of the put area is 32 After underflow(): size of the get area is 3 size of the put area is 32 underflow() returns '1' Before underflow(): size of the get area is 3 size of the put area is 32 After underflow(): size of the get area is 3 size of the put area is 32 underflow() returns EOF 123 ``` ### See also | | | | --- | --- | | [underflow](../basic_streambuf/underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [underflow](../basic_stringbuf/underflow "cpp/io/basic stringbuf/underflow") [virtual] | returns the next character available in the input sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [underflow](../basic_filebuf/underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [sgetc](../basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [get](../basic_istream/get "cpp/io/basic istream/get") | extracts characters (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::strstreambuf::pcount std::strstreambuf::pcount ========================= | | | | | --- | --- | --- | | ``` int pcount() const; ``` | | | Returns the number of characters written to the output sequence. If the next pointer for the put area (`[std::streambuf::pptr()](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`) is a null pointer, returns zero. Otherwise, returns the next pointer in the put area minus the beginning pointer in the put area, that is `pptr() - pbase()`. ### Parameters (none). ### Return value The number of characters written to the put area. ### Example ``` #include <strstream> #include <iostream> int main() { std::strstream dyn; // dynamically-allocated output buffer dyn << "Test: " << 1.23 << std::ends; std::strstreambuf* buf = dyn.rdbuf(); std::cout << "The size of the output is " << buf->pcount() // or just buf.pcount() << " and it holds \"" << dyn.str() << "\"\n"; dyn.freeze(false); // after calling .str() on a dynamic strstream char arr[10]; std::ostrstream user(arr, 10); // user-provided output buffer buf = user.rdbuf(); user << 1.23; // note: no std::ends std::cout.write(arr, buf->pcount()); // or just user.pcount() std::cout << '\n'; std::istrstream lit("1 2 3"); // read-only fixed-size buffer buf = lit.rdbuf(); // istrstream has no member pcount(), so lit.pcount() won't work std::cout << "Input-only pcount() = " << buf->pcount() << '\n'; } ``` Output: ``` The size of the output is 11 and it holds "Test: 1.23" 1.23 Input-only pcount() = 0 ``` ### See also | | | | --- | --- | | [pcount](../strstream/pcount "cpp/io/strstream/pcount") | obtains the number of characters written (public member function of `std::strstream`) | | [pcount](../ostrstream/pcount "cpp/io/ostrstream/pcount") | obtains the number of characters written (public member function of `std::ostrstream`) | cpp std::strstreambuf::str std::strstreambuf::str ====================== | | | | | --- | --- | --- | | ``` char* str() const; ``` | | | Calls `[freeze()](freeze "cpp/io/strstreambuf/freeze")`, then returns a copy of start pointer of the get area, `[std::streambuf::eback()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")`. The start of the get area, for all writeable `std::strstreambuf` objects constructed through the interface provided by `[std::strstream](../strstream "cpp/io/strstream")`, is also the start of the put area. ### Parameters (none). ### Return value A copy of `[eback()](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")`, which may be a null pointer. ### Notes This function is typically called through the `[std::strstream](../strstream "cpp/io/strstream")` interface. The call to `[freeze()](freeze "cpp/io/strstreambuf/freeze")` guarantees that the returned pointer remains valid until the next explicit call to `freeze(false)`: otherwise (on a dynamic buffer) any output operation could trigger buffer reallocation which would invalidate the pointer. It also causes a memory leak in the destructor of `std::strstreambuf`, unless `freeze(false)` is called before the buffer (or, more commonly, the `[std::strstream](http://en.cppreference.com/w/cpp/io/strstream)` that manages it) is destroyed. ### Example ``` #include <strstream> #include <iostream> int main() { std::strstream dyn; // dynamically-allocated read/write buffer dyn << "Test: " << 1.23 << std::ends; std::strstreambuf* buf = dyn.rdbuf(); std::cout << "R/W buffer holds \"" << buf->str() // or dyn.str() << "\"\n"; dyn.freeze(false); // after calling .str() on a dynamic strstream char arr[10]; std::ostrstream user(arr, 10); // fixed-size write-only buffer buf = user.rdbuf(); user << 1.23 << std::ends; std::cout << "Write-only buffer holds \"" << buf->str() // or user.str() << "\"\n"; std::istrstream lit("1 2 3"); // fixed-size read-only buffer buf = lit.rdbuf(); std::cout << "Read-only buffer holds \"" << buf->str() // or lit.str() << "\"\n"; } ``` Output: ``` R/W buffer holds "Test: 1.23" Write-only buffer holds "1.23" Read-only buffer holds "1 2 31 2 3" ``` ### See also | | | | --- | --- | | [str](../strstream/str "cpp/io/strstream/str") | accesses the output buffer (public member function of `std::strstream`) | | [str](../ostrstream/str "cpp/io/ostrstream/str") | accesses the output buffer (public member function of `std::ostrstream`) | | [str](../istrstream/str "cpp/io/istrstream/str") | accesses the output buffer (public member function of `std::istrstream`) | cpp std::strstreambuf::~strstreambuf std::strstreambuf::~strstreambuf ================================ | | | | | --- | --- | --- | | ``` virtual ~strstreambuf(); ``` | | | Destroys a `std::strstreambuf` object. if the object is managing a dynamically-allocated buffer (the buffer state is "allocated") and if the object is not frozen, then deallocates the buffer using the deallocation function provided at construction or `delete[]` if none was provided. ### Parameters (none). ### Notes This destructor is typically called by the destructor of `[std::strstream](../strstream "cpp/io/strstream")`. If `[str()](str "cpp/io/strstreambuf/str")` was called on a dynamic strstream and `[freeze(false)](freeze "cpp/io/strstreambuf/freeze")` was not called after that, this destructor leaks memory. ### Example ``` #include <strstream> #include <iostream> void* my_alloc(size_t n) { std::cout << "my_alloc(" << n << ") called\n"; return new char[n]; } void my_free(void* p) { std::cout << "my_free() called\n"; delete[] (char*)p; } int main() { { std::strstreambuf buf(my_alloc, my_free); std::ostream s(&buf); s << 1.23 << std::ends; std::cout << buf.str() << '\n'; buf.freeze(false); } // destructor called here, buffer deallocated { std::strstreambuf buf(my_alloc, my_free); std::ostream s(&buf); s << 1.23 << std::ends; std::cout << buf.str() << '\n'; // buf.freeze(false); } // destructor called here, memory leak! } ``` Output: ``` my_alloc(4096) called 1.23 my_free() called my_alloc(4096) called 1.23 ``` cpp std::strstreambuf::seekpos std::strstreambuf::seekpos ========================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekpos( pos_type sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | | | Repositions `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` and/or `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, if possible, to the position indicated by `sp`. If `[std::ios\_base::in](../ios_base/openmode "cpp/io/ios base/openmode")` is set in `which`, attempts to reposition `gptr()` (the next pointer in the get area). If `[std::ios\_base::out](../ios_base/openmode "cpp/io/ios base/openmode")` is set in `which`, attempts to reposition `pptr()` (the next pointer in the put area). If neither bit is set in `which`, the operation fails. Each next pointer is repositioned as follows: * If the next pointer is null, the operation fails. * Otherwise, the new offset `newoff` (of type `off_type`) is determined by calling `sp.offset()`. If `newoff` is negative, out of bounds of the buffer, or invalid, the operation fails. * Otherwise, the next pointer is assigned as if by `gptr() = eback() + newoff` or `pptr() = pbase() + newoff`. ### Parameters | | | | | --- | --- | --- | | sp | - | stream position, such as one obtained by `[seekoff()](seekoff "cpp/io/strstreambuf/seekoff")` or `seekpos()` | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value The resultant offset converted to `pos_type` on success or `pos_type(off_type(-1))` on failure. ### Notes `seekpos()` is called by `[std::basic\_streambuf::pubseekpos()](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos")`, which is called by the single-argument versions of `[std::basic\_istream::seekg()](../basic_istream/seekg "cpp/io/basic istream/seekg")` and `[std::basic\_ostream::seekp()](../basic_ostream/seekp "cpp/io/basic ostream/seekp")`. ### Example ``` #include <strstream> #include <cstring> #include <iostream> struct mybuf : std::strstreambuf { mybuf(const char* str) : std::strstreambuf(str, std::strlen(str)) {} pos_type seekpos(pos_type sp, std::ios_base::openmode which) { std::cout << "Before seekpos(" << sp << "), size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; pos_type rc = std::strstreambuf::seekpos(sp, which); std::cout << "seekpos() returns " << rc << ".\nAfter the call, " << "size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; return rc; } }; int main() { mybuf buf("12345"); std::iostream stream(&buf); stream.seekg(2); } ``` Output: ``` Before seekpos(2), size of the get area is 5 with 5 read positions available. seekpos() returns 2. After the call, size of the get area is 5 with 3 read positions available. ``` ### 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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | `seekpos` returned an undefinedinvalid stream position on failure | `pos_type(off_type(-1))`is returned on failure | ### See also | | | | --- | --- | | [seekoff](seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function) | | [seekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](../basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekpos](../basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::strstreambuf::overflow std::strstreambuf::overflow =========================== | | | | | --- | --- | --- | | ``` protected: virtual int_type overflow (int_type c = EOF); ``` | | | Appends the character `c` to the put area of the buffer, reallocating if possible. 1) If `c==EOF`, does nothing 2) Otherwise, if the put area has a write position available (`pptr() < epptr()`), stores the character as if by `*pptr()++ = c` 3) Otherwise, if the stream buffer mode is not dynamic or the stream buffer is currently frozen, the function fails and returns `[EOF](http://en.cppreference.com/w/cpp/io/c)` 4) Otherwise, the function reallocates (or initially allocates) a dynamic array large enough to hold the contents of the current dynamic array (if any) plus at least one additional write position. If a pointer to the allocating function `palloc` was used in the constructor, that function is called with `(*palloc)(n)` where `n` is the number of bytes to allocate, otherwise `new char[n]` is used. If a pointer to the deallocating function `pfree` was used in the constructor, that function is called with `(*pfree)(p)` to deallocate the previous array, if needed, otherwise `delete[] p` is used. If allocation fails, the function fails and returns `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | c | - | the character to store in the put area | ### Return value If `c==[EOF](http://en.cppreference.com/w/cpp/io/c)`, returns some value other than `[EOF](http://en.cppreference.com/w/cpp/io/c)`. Otherwise, returns `(unsigned char)(c)` on success, `[EOF](../c "cpp/io/c")` on failure. ### Example ``` #include <strstream> #include <iostream> struct mybuf : std::strstreambuf { int_type overflow(int_type c) { std::cout << "Before overflow(): size of the put area is " << epptr()-pbase() << " with " << epptr()-pptr() << " write positions available\n"; int_type rc = std::strstreambuf::overflow(c); std::cout << "After overflow(): size of the put area is " << epptr()-pbase() << " with " << epptr()-pptr() << " write positions available\n"; return rc; } }; int main() { mybuf sbuf; // read-write dynamic strstreambuf std::iostream stream(&sbuf); stream << "Sufficiently long string to overflow the initial allocation, at least " << " on some systems."; } ``` Possible output: ``` Before overflow(): size of the put area is 16 with 0 write positions available After overflow(): size of the put area is 32 with 15 write positions available Before overflow(): size of the put area is 32 with 0 write positions available After overflow(): size of the put area is 64 with 31 write positions available Before overflow(): size of the put area is 64 with 0 write positions available After overflow(): size of the put area is 128 with 63 write positions available ``` ### See also | | | | --- | --- | | [overflow](../basic_streambuf/overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [overflow](../basic_stringbuf/overflow "cpp/io/basic stringbuf/overflow") [virtual] | appends a character to the output sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [overflow](../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>`) | | [sputc](../basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) | | [put](../basic_ostream/put "cpp/io/basic ostream/put") | inserts a character (public member function of `std::basic_ostream<CharT,Traits>`) |
programming_docs
cpp std::strstreambuf::setbuf std::strstreambuf::setbuf ========================= | | | | | --- | --- | --- | | ``` protected: virtual streambuf<char>* setbuf(char* s, std::streamsize n); ``` | | | If `s` is a null pointer and `n` is zero, this function has no effect. Otherwise, the effect is implementation-defined: some implementations do nothing, while some implementations deallocate the dynamic member array used as the buffer and begin using the user-supplied character array of size `n`, whose first element is pointed to by `s`. This function is protected virtual, it may only be called through `pubsetbuf()` or from member functions of a user-defined class derived from `std::strstreambuf`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the first byte in the user-provided buffer | | n | - | the number of bytes in the user-provided buffer | ### Return value `this`. ### Example Implementation test to check if `setbuf()` is supported on a dynamic strstream (output obtained with Sun Studio): ``` #include <strstream> #include <iostream> int main() { char a[100] = {}; std::strstream str; str.rdbuf()->pubsetbuf(a, sizeof a); str << "Test string" << std::ends; std::cout << "user-provided buffer holds \"" << a << "\"\n"; } ``` Possible output: ``` user-provided buffer holds "Test string" ``` ### 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 66](https://cplusplus.github.io/LWG/issue66) | C++98 | the effect of `setbuf()` was "performs an operation that isdefined separately for each class derived from `strstreambuf`",but there are no classes derived from `strstreambuf` | the effect isimplementation-defined | ### See also | | | | --- | --- | | [pubsetbuf](../basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") | invokes `setbuf()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [setbuf](../basic_streambuf/pubsetbuf "cpp/io/basic streambuf/pubsetbuf") [virtual] | replaces the buffer with user-defined array, if permitted (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [setbuf](../basic_stringbuf/setbuf "cpp/io/basic stringbuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [setbuf](../basic_filebuf/setbuf "cpp/io/basic filebuf/setbuf") [virtual] | provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::strstreambuf::strstreambuf std::strstreambuf::strstreambuf =============================== | | | | | --- | --- | --- | | | (1) | | | ``` explicit strstreambuf( std::streamsize alsize = 0 ); ``` | (until C++11) | | ``` strstreambuf() : strstreambuf(0) {} explicit strstreambuf( std::streamsize alsize ); ``` | (since C++11) | | ``` strstreambuf( void* (*palloc)(std::size_t), void (*pfree)(void*) ); ``` | (2) | | | ``` strstreambuf( char* gnext, std::streamsize n, char* pbeg = 0 ); ``` | (3) | | | ``` strstreambuf( signed char* gnext, std::streamsize n, signed char* pbeg = 0 ); ``` | (4) | | | ``` strstreambuf( unsigned char* gnext, std::streamsize n, unsigned char* pbeg = 0 ); ``` | (5) | | | ``` strstreambuf( const char* gnext, std::streamsize n ); ``` | (6) | | | ``` strstreambuf( const signed char* gnext, std::streamsize n); ``` | (7) | | | ``` strstreambuf( const unsigned char* gnext, std::streamsize n ); ``` | (8) | | 1) Constructs a `std::strstreambuf` object: initializes the base class by calling the default constructor of `[std::streambuf](../basic_streambuf "cpp/io/basic streambuf")`, initializes the buffer state to "dynamic" (the buffer will be allocated as needed), initializes allocated size to the provided `alsize`, initializes the allocation and the deallocation functions to null (will use `new[]` and `delete[]`) 2) Constructs a `std::strstreambuf` object: initializes the base class by calling the default constructor of `[std::streambuf](../basic_streambuf "cpp/io/basic streambuf")`, initializes the buffer state to "dynamic" (the buffer will be allocated as needed), initializes allocated size to unspecified value, initializes the allocation function to `palloc` and the deallocation function to `pfree` 3-5) Constructs a `std::strstreambuf` object in following steps: a) Initializes the base class by calling the default constructor of `[std::streambuf](../basic_streambuf "cpp/io/basic streambuf")` b) Initializes the buffer state to "constant" (the buffer is a user-provided fixed-size buffer) c) Determines the number of elements in the user-provided array as follows: if `n` is greater than zero, `n` is used. If `n` is zero, `[std::strlen](http://en.cppreference.com/w/cpp/string/byte/strlen)(gnext)` is executed to determine the buffer size. If `n` is negative, `[INT\_MAX](../../types/climits "cpp/types/climits")` is used. d) Configures the `[std::basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf")` pointers as follows: If `pbeg` is a null pointer, calls `setg(gnext, gnext, gnext + N)`. If `pbeg` is not a null pointer, executes `setg(gnext, gnext, pbeg)` and `setp(pbeg, pbeg+N)`, where N is the number of elements in the array as determined earlier. 6-8) Same as `strstreambuf((char*)gnext, n)`, except the "constant" bit is set in the buffer state bitmask (output to this buffer is not allowed) ### Parameters | | | | | --- | --- | --- | | alsize | - | the initial size of the dynamically allocated buffer | | palloc | - | pointer to user-provided allocation function | | pfree | - | pointer to user-provided deallocation function | | gnext | - | pointer to the start of the get area in the user-provided array | | pbeg | - | pointer to the start of the put area in the user-provided array | | n | - | the number of bytes in the get area (if pbeg is null) or in the put area (if pbeg is not null) of the user-provided array | ### Notes These constructors are typically called by the constructors of `[std::strstream](http://en.cppreference.com/w/cpp/io/strstream)`. ### 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 <strstream> #include <iostream> int main() { std::strstreambuf dyn; // dynamic std::strstream dyn_s; // equivalent stream dyn_s << 1.23 << std::ends; std::cout << dyn_s.str() << '\n'; dyn_s.freeze(false); char buf[10]; std::strstreambuf user(buf, 10, buf); // user-provided output buffer std::ostrstream user_s(buf, 10); // equivalent stream user_s << 1.23 << std::ends; std::cout << buf << '\n'; std::strstreambuf lit("1 2 3", 5); // constant std::istrstream lit_s("1 2 3"); // equivalent stream int i, j, k; lit_s >> i >> j >> k; std::cout << i << ' ' << j << ' ' << k << '\n'; } ``` Output: ``` 1.23 1.23 1 2 3 ``` ### See also | | | | --- | --- | | [(constructor)](../strstream/strstream "cpp/io/strstream/strstream") | constructs an strstream, optionally allocating the buffer (public member function of `std::strstream`) | cpp std::strstreambuf::seekoff std::strstreambuf::seekoff ========================== | | | | | --- | --- | --- | | ``` protected: virtual pos_type seekoff( off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out ); ``` | | | Repositions `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` and/or `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")`, if possible, to the position that corresponds to exactly `off` characters from beginning, end, or current position of the get and/or put area of the buffer. * If `which` includes `ios_base::in` and this buffer is open for reading, then repositions the read pointer `[std::basic\_streambuf::gptr](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr")` inside the get area as described below. * If `which` includes `ios_base::out` and this buffer is open for writing, then repositions the write pointer `[std::basic\_streambuf::pptr](../basic_streambuf/pptr "cpp/io/basic streambuf/pptr")` inside the put area as described below. * If `which` includes both `ios_base::in` and `ios_base::out` and the buffer is open for both reading and writing, and `way` is either `ios_base::beg` or `ios_base::end`, then repositions both read and write pointers as described below. * Otherwise, this function fails. If the pointer (either `gptr` or `pptr` or both) is repositioned, it is done as follows: 1) If the pointer to be repositioned is a null pointer and the new offset `newoff` would be non-zero, this function fails. 2) The new pointer offset `newoff` of type `off_type` is determined a) if `way == ios_base::beg`, then `newoff` is zero b) if `way == ios_base::cur`, then `newoff` is the current position of the pointer (`gptr() - eback()` or `pptr() - pbase()`) c) if `way == ios_base::end`, then `newoff` is the length of the entire initialized part of the buffer (if overallocation is used, the high watermark pointer minus the beginning pointer) 3) If `newoff + off` is negative or out of bounds of the initialized part of the buffer, the function fails 4) Otherwise, the pointer is assigned as if by `gptr() = eback() + newoff + off` or `pptr() = pbase() + newoff + off` ### Parameters | | | | | --- | --- | --- | | off | - | relative position to set the next pointer(s) to | | way | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | | which | - | defines whether the input sequences, the output sequence, or both are affected. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value `pos_type(newoff)` on success, `pos_type(off_type(-1))` on failure and if pos\_type cannot represent the resulting stream position. ### Example ``` #include <iostream> #include <strstream> int main() { char a[] = "123"; std::strstream ss(a, sizeof a); // in/out std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // absolute positioning both pointers ss.rdbuf()->pubseekoff(1, std::ios_base::beg); // move both forward std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // try to move both pointers 1 forward from current position if (-1 == ss.rdbuf()->pubseekoff(1, std::ios_base::cur)) std::cout << "moving both pointers from current position failed\n"; std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // move the write pointer 1 forward, but not the read pointer // can also be called as ss.seekp(1, std::ios_base::cur); ss.rdbuf()->pubseekoff(1, std::ios_base::cur, std::ios_base::out); std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; ss << 'a'; // write at put position std::cout << "Wrote 'a' at put position, the buffer is now: '"; std::cout.write(a, sizeof a); std::cout << "'\n"; char ch; ss >> ch; std::cout << "reading at get position gives '" << ch << "'\n"; } ``` Output: ``` put pos = 0 get pos = 0 put pos = 1 get pos = 1 moving both pointers from current position failed put pos = 1 get pos = 1 put pos = 2 get pos = 1 Wrote 'a' at put position, the buffer is now: '12a' reading at get position gives '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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | `seekoff` returned an undefinedinvalid stream position on failure | `pos_type(off_type(-1))`is returned on failure | ### See also | | | | --- | --- | | [seekpos](seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function) | | [seekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](../basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekoff](../basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::strstreambuf::pbackfail std::strstreambuf::pbackfail ============================ | | | | | --- | --- | --- | | ``` protected: virtual int_type pbackfail( int_type c = EOF ); ``` | | | This protected virtual function is called by the public functions [`basic_streambuf::sungetc`](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") and [`basic_streambuf::sputbackc`](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") (which, in turn, are called by [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") and [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback")). 1) The caller is requesting that the get area is backed up by one character (`pbackfail()` is called with no arguments or with `[EOF](../c "cpp/io/c")` as the argument) a) First, checks if there is a putback position, and if there really isn't, fails. (strstreambuf has no external character source to re-read) b) If the caller was wrong and the putback position is in fact available, simply decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"), e.g. by calling `gbump(-1)`. 2) The caller attempts to putback a different character from the one retrieved earlier (`pbackfail()` is called with the character that needs to be put back), in which case a) First, checks if there is a putback position, and if there isn't, fails. b) Then checks what character is in the putback position. If the character held there is already equal to `(char)c`, then simply decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr"). c) Otherwise, if the buffer is unmodifiable (this strstreambuf was constructed with a string literal or some other `const` array), fails. d) Otherwise, decrements [`basic_streambuf::gptr()`](../basic_streambuf/gptr "cpp/io/basic streambuf/gptr") and writes `c` to the location pointed to gptr() after adjustment. ### Parameters | | | | | --- | --- | --- | | c | - | the character to put back, or Traits::eof() to indicate that backing up of the get area is requested | ### Return value `c` on success except if `c` was `[EOF](../c "cpp/io/c")`, in which case unspecified value other than `[EOF](../c "cpp/io/c")` is returned. `[EOF](../c "cpp/io/c")` on failure. ### Example ### See also | | | | --- | --- | | [pbackfail](../basic_streambuf/pbackfail "cpp/io/basic streambuf/pbackfail") [virtual] | puts a character back into the input sequence, possibly modifying the input sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [sungetc](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | | [sputbackc](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [unget](../basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) | | [putback](../basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_ofstream<CharT,Traits>::rdbuf std::basic\_ofstream<CharT,Traits>::rdbuf ========================================= | | | | | --- | --- | --- | | ``` std::basic_filebuf<CharT, Traits>* rdbuf() const; ``` | | (since C++11) | Returns pointer to the underlying raw file device object. ### Parameters (none). ### Return value Pointer to the underlying raw file device. ### Example cpp std::basic_ofstream<CharT,Traits>::swap std::basic\_ofstream<CharT,Traits>::swap ======================================== | | | | | --- | --- | --- | | ``` void swap( basic_ofstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_ostream<CharT, Traits>::swap(other)` and `rdbuf()->swap(other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <fstream> #include <iomanip> #include <iostream> #include <string> bool create_stream(std::fstream& fs, const std::string& path) { try { std::fstream fst { path, std::ios::trunc | std::ios::in | std::ios::out }; if (fst.is_open()) { fst.swap( fs ); return true; } } catch (...) { std::cout << "Exception!\n"; } return false; } void use_stream(std::fstream& fs) { fs.seekg(0); std::string data; fs >> data; std::cout << "data: " << std::quoted(data) << '\n'; } int main() { std::fstream fs; std::string path = "/tmp/test_file.txt"; if (create_stream(fs, path)) { fs.write(path.c_str(), path.length()); use_stream(fs); } } ``` Possible output: ``` data: "/tmp/test_file.txt" ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic ofstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](../basic_filebuf/swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_ofstream<CharT,Traits>::basic_ofstream std::basic\_ofstream<CharT,Traits>::basic\_ofstream =================================================== | | | | | --- | --- | --- | | ``` basic_ofstream(); ``` | (1) | | | ``` explicit basic_ofstream( const char* filename, std::ios_base::openmode mode = ios_base::out ); ``` | (2) | | | ``` explicit basic_ofstream( const std::filesystem::path::value_type* filename, std::ios_base::openmode mode = ios_base::out ); ``` | (3) | (since C++17) | | ``` explicit basic_ofstream( const std::string& filename, std::ios_base::openmode mode = ios_base::out ); ``` | (4) | (since C++11) | | ``` template< class FsPath > explicit basic_ofstream( const FsPath& filename, std::ios_base::openmode mode = ios_base::out ); ``` | (5) | (since C++17) | | ``` basic_ofstream( basic_ofstream&& other ); ``` | (6) | (since C++11) | | ``` basic_ofstream( const basic_ofstream& rhs) = delete; ``` | (7) | (since C++11) | Constructs new file stream. 1) Default constructor: constructs a stream that is not associated with a file: default-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` and constructs the base with the pointer to this default-constructed `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member. 2-3) First, performs the same steps as the default constructor, then associates the stream with a file by calling `rdbuf()->open(filename, mode | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode))` (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). If the `open()` call returns a null pointer, sets `setstate(failbit)`. Overload (3) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 4-5) Same as `basic_ofstream(filename.c_str(), mode)`. (5) participates in overload resolution only if `FsPath` is `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")`. (since C++17) Note that despite the default mode being `out`, the effects are identical to the effects of `out|trunc` as described in [`std::filebuf::open`](../basic_filebuf/open "cpp/io/basic filebuf/open") 6) Move constructor. First, move-constructs the base class from `other` (which does not affect the `rdbuf()` pointer), then move-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member, then calls `this->set_rdbuf()` to install the new `basic_filebuf` as the `rdbuf()` pointer in the base class. 7) The copy-constructor is deleted: this class is not copyable. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another file stream to use as source | ### Example ``` #include <fstream> #include <utility> #include <string> int main() { std::ofstream f0; std::ofstream f1("test.bin", std::ios::binary); std::string name = "example.txt"; std::ofstream f2(name); std::ofstream f3(std::move(f1)); } ``` ### 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 3430](https://cplusplus.github.io/LWG/issue3430) | C++17 | `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")` overload led to unwanted conversions | avoided by making it a template | ### See also | | | | --- | --- | | [open](open "cpp/io/basic ofstream/open") | opens a file and associates it with the stream (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | | [set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf") | replaces the `rdbuf` without clearing its error state (protected member function) | | [(constructor)](../basic_ostream/basic_ostream "cpp/io/basic ostream/basic ostream") | constructs the object (public member function of `std::basic_ostream<CharT,Traits>`) |
programming_docs
cpp std::swap(std::basic_ofstream) std::swap(std::basic\_ofstream) =============================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( basic_ofstream<CharT,Traits> &lhs, basic_ofstream<CharT,Traits> &rhs ); ``` | | | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_ofstream](http://en.cppreference.com/w/cpp/io/basic_ofstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ofstream/swap") (C++11) | swaps two file streams (public member function) | cpp std::basic_ofstream<CharT,Traits>::operator= std::basic\_ofstream<CharT,Traits>::operator= ============================================= | | | | | --- | --- | --- | | ``` basic_ofstream& operator=( basic_ofstream&& other ); ``` | | (since C++11) | Move assigns the file stream `other` to `*this`, effectively move-assigning both the `[std::basic\_ostream](../basic_ostream "cpp/io/basic ostream")` base class and the associated `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")`. `other` is left with no associated file. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | file stream to move. | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ofstream/swap") (C++11) | swaps two file streams (public member function) | | [operator=](../basic_filebuf/operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function of `std::basic_filebuf<CharT,Traits>`) | | [operator=](../basic_ostream/operator= "cpp/io/basic ostream/operator=") (C++11) | move-assigns from another `basic_ostream` (protected member function) | cpp std::basic_ofstream<CharT,Traits>::close std::basic\_ofstream<CharT,Traits>::close ========================================= | | | | | --- | --- | --- | | ``` void close(); ``` | | | Closes the associated file. Effectively calls [`rdbuf()->close()`](../basic_filebuf/close "cpp/io/basic filebuf/close"). If an error occurs during operation, `setstate(failbit)` is called. ### Parameters (none). ### Return value (none). ### Notes This function is called by the destructor of basic\_ofstream when the stream object goes out of scope and is not usually invoked directly. ### Example ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic ofstream/is open") | checks if the stream has an associated file (public member function) | | [open](open "cpp/io/basic ofstream/open") | opens a file and associates it with the stream (public member function) | | [close](../basic_filebuf/close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_ofstream<CharT,Traits>::open std::basic\_ofstream<CharT,Traits>::open ======================================== | | | | | --- | --- | --- | | ``` void open( const char *filename, ios_base::openmode mode = ios_base::out ); ``` | (1) | | | ``` void open( const std::filesystem::path::value_type *filename, ios_base::openmode mode = ios_base::out ); ``` | (2) | (since C++17) | | ``` void open( const std::string &filename, ios_base::openmode mode = ios_base::out ); ``` | (3) | (since C++11) | | ``` void open( const std::filesystem::path &filename, ios_base::openmode mode = ios_base::out ); ``` | (4) | (since C++17) | Opens and associates the file with name `filename` with the file stream. Calls `setstate(failbit)` on failure. | | | | --- | --- | | Calls `clear()` on success. | (since C++11) | 1-2) Effectively calls `rdbuf()->open(filename, mode | ios_base::out)`. (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). Overload (2) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 3-4) Effectively calls (1-2) as if by `open(filename.c_str(), mode)`. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Return value (none). ### 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 22](https://cplusplus.github.io/LWG/issue22) | C++98 | it was unclear how error state changes upon a successful open | the error state is unchanged | ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic ofstream/is open") | checks if the stream has an associated file (public member function) | | [close](close "cpp/io/basic ofstream/close") | closes the associated file (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_ofstream<CharT,Traits>::is_open std::basic\_ofstream<CharT,Traits>::is\_open ============================================ | | | | | --- | --- | --- | | ``` bool is_open(); ``` | | (until C++11) | | ``` bool is_open() const; ``` | | (since C++11) | Checks if the file stream has an associated file. Effectively calls [`rdbuf()->is_open()`](../basic_filebuf/is_open "cpp/io/basic filebuf/is open"). ### Parameters (none). ### Return value `true` if the file stream has an associated file, `false` otherwise. ### Example ### See also | | | | --- | --- | | [open](open "cpp/io/basic ofstream/open") | opens a file and associates it with the stream (public member function) | | [close](close "cpp/io/basic ofstream/close") | closes the associated file (public member function) | cpp std::basic_istream<CharT,Traits>::read std::basic\_istream<CharT,Traits>::read ======================================= | | | | | --- | --- | --- | | ``` basic_istream& read( char_type* s, std::streamsize count ); ``` | | | Extracts characters from stream. Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, extracts characters and stores them into successive locations of the character array whose first element is pointed to by `s`. Characters are extracted and stored until any of the following conditions occurs: * `count` characters were extracted and stored * end of file condition occurs on the input sequence (in which case, `setstate(failbit|eofbit)` is called). The number of successfully extracted characters can be queried using [`gcount()`](gcount "cpp/io/basic istream/gcount"). ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the character array to store the characters to | | count | - | number of characters to read | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Notes When using a non-converting locale (the default locale is non-converting), the overrider of this function in `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")` may be optimized for zero-copy bulk I/O (by means of overriding `[std::streambuf::xsgetn](../basic_streambuf/sgetn "cpp/io/basic streambuf/sgetn")`). ### Example ``` #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdint> int main() { // read() is often used for binary I/O std::string bin = {'\x12', '\x12', '\x12', '\x12'}; std::istringstream raw(bin); std::uint32_t n; if(raw.read(reinterpret_cast<char*>(&n), sizeof n)) std::cout << std::hex << std::showbase << n << '\n'; // prepare file for next snippet std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3"; // read entire file into string if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) { auto size = is.tellg(); std::string str(size, '\0'); // construct string to stream size is.seekg(0); if(is.read(&str[0], size)) std::cout << str << '\n'; } } ``` Output: ``` 0x12121212 abcd1 abcd2 abcd3 ``` ### See also | | | | --- | --- | | [write](../basic_ostream/write "cpp/io/basic ostream/write") | inserts blocks of characters (public member function of `std::basic_ostream<CharT,Traits>`) | | [operator>>](operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function) | | [readsome](readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function) | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [getline](getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function) | | [fread](../c/fread "cpp/io/c/fread") | reads from a file (function) | cpp std::basic_istream<CharT,Traits>::unget std::basic\_istream<CharT,Traits>::unget ======================================== | | | | | --- | --- | --- | | ``` basic_istream& unget(); ``` | | | Makes the most recently extracted character available again. | | | | --- | --- | | First clears [`eofbit`](../ios_base/iostate "cpp/io/ios base/iostate"). | (since C++11) | Then the function behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, if any `ios_base::iostate` flags are set, the function sets `failbit` and returns. Otherwise, calls `rdbuf()->sungetc()`. If `rdbuf()->sungetc()` returns `Traits::eof()`, calls `setstate(badbit)`. In any case, sets the `gcount()` counter to zero. ### Parameters (none). ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example ``` #include <sstream> #include <iostream> int main() { std::istringstream s1("Hello, world."); char c1 = s1.get(); if (s1.unget()) { char c2 = s1.get(); std::cout << "Got: " << c1 << " got again: " << c2 << '\n'; } } ``` Output: ``` Got: H got again: H ``` ### See also | | | | --- | --- | | [sungetc](../basic_streambuf/sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function of `std::basic_streambuf<CharT,Traits>`) | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [peek](peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function) | | [putback](putback "cpp/io/basic istream/putback") | puts character into input stream (public member function) | cpp std::basic_istream<CharT,Traits>::~basic_istream std::basic\_istream<CharT,Traits>::~basic\_istream ================================================== | | | | | --- | --- | --- | | ``` virtual ~basic_istream(); ``` | | | Destructs the input stream. ### Notes This destructor does not perform any operation on the underlying streambuffer (`rdbuf()`): the destructors of the derived input streams such as `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")` and `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")` are responsible for calling the destructors of the streambuffers. ### Example ``` #include <sstream> #include <iostream> void print_stringbuf(std::streambuf* p) { std::istream buf(p); // buf shares the buffer with s1 int n; buf >> n; std::cout << n; } // calls the destructor of buf. p remains unaffected int main() { std::istringstream s1("10 20"); print_stringbuf(s1.rdbuf()); int n; s1 >> n; std::cout << ',' << n << '\n'; } ``` Output: ``` 10,20 ``` cpp std::basic_istream<CharT,Traits>::putback std::basic\_istream<CharT,Traits>::putback ========================================== | | | | | --- | --- | --- | | ``` basic_istream& putback( char_type ch ); ``` | | | Puts the character `ch` back to the input stream so the next extracted character will be `ch`. First clears `eofbit`, then behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, if `rdbuf()` is not null, calls `rdbuf()->sputbackc(ch)`, which calls `rdbuf()->pbackfail(ch)` if `ch` does not equal the most recently extracted character. If `rdbuf()` is null or if `rdbuf->sputbackc(ch)` returns `Traits::eof()`, calls `setstate(badbit)`. In any case, sets the `gcount()` counter to zero. ### Parameters | | | | | --- | --- | --- | | ch | - | character to put into input stream | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example demonstrates the difference between modifying and non-modifying `putback()`. ``` #include <sstream> #include <iostream> int main() { std::stringstream s1("Hello, world"); // IO stream s1.get(); if (s1.putback('Y')) // modifies the buffer std::cout << s1.rdbuf() << '\n'; else std::cout << "putback failed\n"; std::cout << "--\n"; std::istringstream s2("Hello, world"); // input-only stream s2.get(); if (s2.putback('Y')) // cannot modify input-only buffer std::cout << s2.rdbuf() << '\n'; else std::cout << "putback failed\n"; s2.clear(); std::cout << "--\n"; if (s2.putback('H')) // non-modifying putback std::cout << s2.rdbuf() << '\n'; else std::cout << "putback failed\n"; } ``` Output: ``` Yello, world -- putback failed -- Hello, world ``` ### See also | | | | --- | --- | | [sputbackc](../basic_streambuf/sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [unget](unget "cpp/io/basic istream/unget") | unextracts a character (public member function) | | [peek](peek "cpp/io/basic istream/peek") | reads the next character without extracting it (public member function) | cpp std::basic_istream<CharT,Traits>::swap std::basic\_istream<CharT,Traits>::swap ======================================= | | | | | --- | --- | --- | | ``` protected: void swap(basic_istream& rhs); ``` | | (since C++11) | Calls `basic_ios::swap(rhs)` to swap all data members of the base class except for `rdbuf()`, and swaps the values of the `gcount()` counters between `*this` and `rhs`. This swap function is protected: it is called by the swap functions of the swappable input stream classes `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")` and `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")`, which know how to correctly swap the associated streambuffers. ### Parameters | | | | | --- | --- | --- | | rhs | - | different basic\_istream object of the same type to swap with | ### Example ``` #include <sstream> #include <iostream> #include <utility> int main() { std::istringstream s1("hello"); std::istringstream s2("bye"); s1.swap(s2); // OK, istringstream has a public swap() std::swap(s1, s2); // OK, calls s1.swap(s2) // std::cin.swap(s2); // ERROR: swap is a protected member std::cout << s1.rdbuf(); } ``` Output: ``` hello ``` cpp std::basic_istream<CharT,Traits>::ignore std::basic\_istream<CharT,Traits>::ignore ========================================= | | | | | --- | --- | --- | | ``` basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() ); ``` | | | Extracts and discards characters from the input stream until and including `delim`. `ignore` behaves as an [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, it extracts characters from the stream and discards them until any of the following conditions occurs: * `count` characters were extracted. This test is disabled in the special case when `count` equals `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::streamsize](http://en.cppreference.com/w/cpp/io/streamsize)>::max()` * end of file conditions occurs in the input sequence, in which case the function calls `setstate(eofbit)` * the next available character `c` in the input sequence is `delim`, as determined by `Traits::eq_int_type(Traits::to_int_type(c), delim)`. The delimiter character is extracted and discarded. This test is disabled if `delim` is `Traits::eof()` ### Parameters | | | | | --- | --- | --- | | count | - | number of characters to extract | | delim | - | delimiting character to stop the extraction at. It is also extracted. | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example The following example uses `ignore` to skip over non-numeric input: ``` #include <iostream> #include <sstream> #include <limits> int main() { std::istringstream input("1\n" "some non-numeric input\n" "2\n"); for(;;) { int n; input >> n; if (input.eof() || input.bad()) { break; } else if (input.fail()) { input.clear(); // unset failbit input.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input } else { std::cout << n << '\n'; } } } ``` Output: ``` 1 2 ``` ### See also | | | | --- | --- | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [getline](getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function) |
programming_docs
cpp std::basic_istream<CharT,Traits>::sentry std::basic\_istream<CharT,Traits>::sentry ========================================= | | | | | --- | --- | --- | | ``` class sentry; ``` | | | An object of class `basic_istream::sentry` is constructed in local scope at the beginning of each member function of `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` that performs input (both formatted and unformatted). Its constructor prepares the input stream: checks if the stream is already in a failed state, flushes the tie()'d output streams, skips leading whitespace unless `noskipws` flag is set, and performs other implementation-defined tasks if necessary. All cleanup, if necessary, is performed in the destructor, so that it is guaranteed to happen if exceptions are thrown during input. ### Member types | | | | --- | --- | | `traits_type` | `Traits` | ### Member functions | | | | --- | --- | | **(constructor)** | constructs the sentry object. All the preparation tasks are done here (public member function) | | **(destructor)** | finalizes the stream object after formatted input or after exception, if necessary (public member function) | | operator= [deleted] | not copy assignable (public member function) | | **operator bool** | checks if the preparation of the stream object was successful (public member function) | std::basic\_istream::sentry::sentry ------------------------------------ | | | | | --- | --- | --- | | ``` explicit sentry(std::basic_istream<CharT,Traits>& is, bool noskipws = false); ``` | | | Prepares the stream for formatted input. If `is.good()` is `false`, calls `is.setstate(failbit)`(since c++11) and returns. Otherwise, if `is.tie()` is not a null pointer, calls `is.tie()->flush()` to synchronize the output sequence with external streams. This call can be suppressed if the put area of `is.tie()` is empty. The implementation may defer the call to `flush` until a call of `is.rdbuf()->underflow()` occurs. If no such call occurs before the sentry object is destroyed, it may be eliminated entirely. If `noskipws` is zero and `is.flags() & ios_base::skipws` is nonzero, the function extracts and discards all whitespace characters until the next available character is not a whitespace character (as determined by the currently imbued locale in `is`). If `is.rdbuf()->sbumpc()` or `is.rdbuf()->sgetc()` returns `traits::eof()`, the function calls `setstate(failbit | eofbit)` (which may throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")`). Additional implementation-defined preparation may take place, which may call `setstate(failbit)` (which may throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")`). If after preparation is completed, `is.good() == true`, then any subsequent calls to `operator bool` will return `true`. ### Parameters | | | | | --- | --- | --- | | is | - | input stream to prepare | | noskipws | - | `true` if whitespace should not be skipped | ### Exceptions `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` if the end of file condition occurs when skipping whitespace. std::basic\_istream::sentry::~sentry ------------------------------------- | | | | | --- | --- | --- | | ``` ~sentry(); ``` | | | Does nothing. std::basic\_istream::sentry::operator bool ------------------------------------------- | | | | | --- | --- | --- | | ``` explicit operator bool() const; ``` | | | Checks whether the preparation of the input stream was successful. ### Parameters (none). ### Return value `true` if the initialization of the input stream was successful, `false` otherwise. ### Example ``` #include <iostream> #include <sstream> struct Foo { char n[5]; }; std::istream& operator>>(std::istream& is, Foo& f) { std::istream::sentry s(is); if (s) is.read(f.n, 5); return is; } int main() { std::string input = " abcde"; std::istringstream stream(input); Foo f; stream >> f; std::cout.write(f.n, 5); std::cout << '\n'; } ``` Output: ``` abcde ``` ### See also | | | | --- | --- | | [operator>>](operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function) | | [operator>>(std::basic\_istream)](operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) | cpp std::basic_istream<CharT,Traits>::tellg std::basic\_istream<CharT,Traits>::tellg ======================================== | | | | | --- | --- | --- | | ``` pos_type tellg(); ``` | | | Returns input position indicator of the current associated `streambuf` object. Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that `[gcount()](gcount "cpp/io/basic istream/gcount")` is not affected. After constructing and checking the sentry object, if `fail() == true`, returns `pos_type(-1)`. Otherwise, returns `rdbuf()->pubseekoff(0, [std::ios\_base::cur](http://en.cppreference.com/w/cpp/io/ios_base/seekdir), [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. ### Parameters (none). ### Return value The current position of the get pointer on success, `pos_type(-1)` on failure. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example ``` #include <iostream> #include <string> #include <sstream> int main() { std::string str = "Hello, world"; std::istringstream in(str); std::string word; in >> word; std::cout << "After reading the word \"" << word << "\" tellg() returns " << in.tellg() << '\n'; } ``` Output: ``` After reading the word "Hello," tellg() returns 6 ``` ### See also | | | | --- | --- | | [seekoff](../basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekoff](../basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekoff](../strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::strstreambuf`) | | [seekg](seekg "cpp/io/basic istream/seekg") | sets the input position indicator (public member function) | | [tellp](../basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](../basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::basic_istream<CharT,Traits>::basic_istream std::basic\_istream<CharT,Traits>::basic\_istream ================================================= | | | | | --- | --- | --- | | ``` explicit basic_istream( std::basic_streambuf<CharT, Traits>* sb); ``` | (1) | | | ``` protected: basic_istream( const basic_istream& rhs ) = delete; ``` | (2) | (since C++11) | | ``` protected: basic_istream( basic_istream&& rhs ); ``` | (3) | (since C++11) | 1) Constructs the `basic_istream` object, assigning initial values to the base class by calling `basic_ios::init(sb)`. The value of `gcount()` is initialized to zero. 2) The copy constructor is protected, and is deleted. Input streams are not copyable. 3) The move constructor copies the value of `gcount()` from `rhs`, sets the gcount() value of rhs to zero, and uses `basic_ios<CharT, Traits>::move(rhs)` to move all basic\_ios members, except for the `rdbuf()`, from `rhs` into `*this`. This move constructor is protected: it is called by the move constructors of movable input stream classes `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")` and `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")`, which know how to correctly move the associated stream buffer. ### Parameters | | | | | --- | --- | --- | | sb | - | streambuffer to use as underlying device | ### Example ``` #include <sstream> #include <iostream> int main() { std::istringstream s1("hello"); std::istream s2(s1.rdbuf()); // OK: s2 shares the buffer with s1 // std::istream s3(std::istringstream("test")); // ERROR: move constructor is protected // std::istream s4(s2); // ERROR: copy constructor is deleted std::istringstream s5(std::istringstream("world")); // OK: move ctor called by derived class std::cout << s2.rdbuf() << ' ' << s5.rdbuf() << '\n'; } ``` Output: ``` hello world ``` cpp std::basic_istream<CharT,Traits>::seekg std::basic\_istream<CharT,Traits>::seekg ======================================== | | | | | --- | --- | --- | | ``` basic_istream& seekg( pos_type pos ); ``` | | | | ``` basic_istream& seekg( off_type off, std::ios_base::seekdir dir); ``` | | | Sets input position indicator of the current associated `streambuf` object. In case of failure, calls `setstate([std::ios\_base::failbit](http://en.cppreference.com/w/cpp/io/ios_base/iostate))`. | | | | --- | --- | | Before doing anything else, `seekg` clears `eofbit`. | (since C++11) | `seekg` behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that `[gcount()](gcount "cpp/io/basic istream/gcount")` is not affected. After constructing and checking the sentry object, 1) sets the input position indicator to absolute (relative to the beginning of the file) value `pos`. Specifically, executes `rdbuf()->pubseekpos(pos, [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))` ([pubseekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos"), in turn, calls seekpos of the specific buffer, such as [filebuf::seekpos](../basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos"), [stringbuf::seekpos](../basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos"), or [strstreambuf::seekpos](../strstreambuf/seekpos "cpp/io/strstreambuf/seekpos")) 2) sets the input position indicator to position `off`, relative to position, defined by `dir`. Specifically, executes `rdbuf()->pubseekoff(off, dir, [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. ### Parameters | | | | | --- | --- | --- | | pos | - | absolute position to set the input position indicator to. | | off | - | relative position (positive or negative) to set the input position indicator to. | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Notes `seekg(n)` is not necessarily equivalent to `seekg(n, ios::beg)`. `[std::basic\_ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)`, for example, requires the absolute position `n` to come from `[tellg()](tellg "cpp/io/basic istream/tellg")`. ### Example ``` #include <iostream> #include <string> #include <sstream> int main() { std::string str = "Hello, world"; std::istringstream in(str); std::string word1, word2; in >> word1; in.seekg(0); // rewind in >> word2; std::cout << "word1 = " << word1 << '\n' << "word2 = " << word2 << '\n'; } ``` Output: ``` word1 = Hello, word2 = Hello, ``` ### See also | | | | --- | --- | | [tellg](tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function) | | [tellp](../basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [seekp](../basic_ostream/seekp "cpp/io/basic ostream/seekp") | sets the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [pubseekpos](../basic_streambuf/pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekpos](../basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekpos](../basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekpos](../strstreambuf/seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::strstreambuf`) | | [pubseekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function of `std::basic_streambuf<CharT,Traits>`) | | [seekoff](../basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekoff](../basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekoff](../strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::strstreambuf`) | cpp std::basic_istream<CharT,Traits>::sync std::basic\_istream<CharT,Traits>::sync ======================================= | | | | | --- | --- | --- | | ``` int sync(); ``` | | | Synchronizes the input buffer with the associated data source. Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that `[gcount()](gcount "cpp/io/basic istream/gcount")` is not affected. After constructing and checking the sentry object, If `[rdbuf()](../basic_ios/rdbuf "cpp/io/basic ios/rdbuf")` is a null pointer, returns `-1`. Otherwise, calls `rdbuf()->pubsync()`. If that function returns `-1`, calls `setstate(badbit)` and returns `-1`. Otherwise, returns `​0​`. ### Parameters (none). ### Return value `​0​` on success, `-1` on failure or if the stream does not support this operation (is unbuffered). ### Notes As with `[readsome()](readsome "cpp/io/basic istream/readsome")`, it is implementation-defined whether this function does anything with library-supplied streams. The intent is typically for the next read operation to pick up any changes that may have been made to the associated input sequence after the stream buffer last filled its get area. To achieve that, `sync()` may empty the get area, or it may refill it, or it may do nothing. A notable exception is Visual Studio, where this operation discards the unprocessed input when called with a standard input stream. ### Example Demonstrates the use of input stream `sync()` with file input, as implemented on some platforms. ``` #include <iostream> #include <fstream> void file_abc() { std::ofstream f("test.txt"); f << "abc\n"; } void file_123() { std::ofstream f("test.txt"); f << "123\n"; } int main() { file_abc(); // file now contains "abc" std::ifstream f("test.txt"); std::cout << "Reading from the file\n"; char c; f >> c; std::cout << c; file_123(); // file now contains "123" f >> c; std::cout << c; f >> c; std::cout << c << '\n'; f.close(); file_abc(); // file now contains "abc" f.open("test.txt"); std::cout << "Reading from the file, with sync()\n"; f >> c; std::cout << c; file_123(); // file now contains "123" f.sync(); f >> c; std::cout << c; f >> c; std::cout << c << '\n'; } ``` Possible output: ``` Reading from the file abc Reading from the file, with sync() a23 ``` ### 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 62](https://cplusplus.github.io/LWG/issue62) | C++98 | `sync()` returned `traits::eof()` if `rdbuf()->pubsync()` returns `-1` | returns `-1` in this case | ### See also | | | | --- | --- | | [sync](../basic_streambuf/pubsync "cpp/io/basic streambuf/pubsync") [virtual] | synchronizes the buffers with the associated character sequence (virtual protected member function of `std::basic_streambuf<CharT,Traits>`) | | [flush](../basic_ostream/flush "cpp/io/basic ostream/flush") | synchronizes with the underlying storage device (public member function of `std::basic_ostream<CharT,Traits>`) | cpp std::basic_istream<CharT,Traits>::readsome std::basic\_istream<CharT,Traits>::readsome =========================================== | | | | | --- | --- | --- | | ``` std::streamsize readsome( char_type* s, std::streamsize count ); ``` | | | Extracts up to `count` immediately available characters from the input stream. The extracted characters are stored into the character array pointed to by `s`. Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, * If `rdbuf()->in_avail() == -1`, calls `setstate(eofbit)` and extracts no characters. * If `rdbuf()->in_avail() == 0`, extracts no characters. * If `rdbuf()->in_avail() > 0`, extracts `[std::min](http://en.cppreference.com/w/cpp/algorithm/min)(rdbuf()->in_avail(), count)` characters and stores them into successive locations of the character array whose first element is pointed to by `s`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the character array to store the characters to | | count | - | maximum number of characters to read | ### Return value The number of characters actually extracted. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Notes The behavior of this function is highly implementation-specific. For example, when used with `[std::ifstream](../basic_ifstream "cpp/io/basic ifstream")`, some library implementations fill the underlying filebuf with data as soon as the file is opened (and readsome() on such implementations reads data, potentially, but not necessarily, the entire file), while other implementations only read from file when an actual input operation is requested (and readsome() issued after file opening never extracts any characters). Likewise, a call to `[std::cin](http://en.cppreference.com/w/cpp/io/cin).readsome()` may return all pending unprocessed console input, or may always return zero and extract no characters. ### Example ``` #include <iostream> #include <sstream> int main() { char c[10] = {}; std::istringstream input("This is sample text."); // std::stringbuf makes its entire // buffer available for unblocking read input.readsome(c, 5); // reads 'This ' and stores in c[0] .. c[4] input.readsome(c, 9); // reads 'is sample' and stores in c[0] .. c[8] std::cout << c; } ``` Output: ``` is sample ``` ### See also | | | | --- | --- | | [read](read "cpp/io/basic istream/read") | extracts blocks of characters (public member function) | | [in\_avail](../basic_streambuf/in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function of `std::basic_streambuf<CharT,Traits>`) |
programming_docs
cpp std::basic_istream<CharT,Traits>::gcount std::basic\_istream<CharT,Traits>::gcount ========================================= | | | | | --- | --- | --- | | ``` std::streamsize gcount() const; ``` | | | Returns the number of characters extracted by the last [unformatted input operation](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), or the maximum representable value of `[std::streamsize](../streamsize "cpp/io/streamsize")` if the number is not representable. The following member functions of `basic_istream` change the value of subsequent `gcount()` calls: * [move constructor](basic_istream "cpp/io/basic istream/basic istream") * `[swap()](../basic_ios/swap "cpp/io/basic ios/swap")` * `[get()](get "cpp/io/basic istream/get")` * `[getline()](getline "cpp/io/basic istream/getline")` * `[ignore()](ignore "cpp/io/basic istream/ignore")` * `[read()](read "cpp/io/basic istream/read")` * `[readsome()](readsome "cpp/io/basic istream/readsome")` * `[operator>>(basic\_streambuf\*)](operator_gtgt "cpp/io/basic istream/operator gtgt")` The following functions set `gcount()` to zero: * [constructor](basic_istream "cpp/io/basic istream/basic istream") * `[putback()](putback "cpp/io/basic istream/putback")` * `[unget()](unget "cpp/io/basic istream/unget")` * `[peek()](peek "cpp/io/basic istream/peek")` ### Parameters (none). ### Return value The number of characters extracted by the last unformatted input operation, or the maximum representable value of `[std::streamsize](../streamsize "cpp/io/streamsize")` if the number is not representable. ### Example ``` #include <iostream> #include <sstream> int main() { char x[20]; std::istringstream stream("Hello World"); stream.read(x, sizeof x); std::cout << "Characters extracted: " << stream.gcount(); } ``` Output: ``` Characters extracted: 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 3464](https://cplusplus.github.io/LWG/issue3464) | C++98 | the return value was unspecified when the result overflows | returns the maximum value | cpp std::basic_istream<CharT,Traits>::operator= std::basic\_istream<CharT,Traits>::operator= ============================================ | | | | | --- | --- | --- | | ``` protected: basic_istream& operator=( const basic_istream& rhs ) = delete; ``` | (1) | | | ``` protected: basic_istream& operator=( basic_istream&& rhs ); ``` | (2) | (since C++11) | 1) The copy assignment operator is protected, and is deleted. Input streams are not CopyAssignable. 2) The move assignment operator exchanges the gcount() values and all data members of the base class, except for `rdbuf()`, with `rhs`, as if by calling `swap(*rhs)`. This move assignment operator is protected: it is only called by the move assignment operators of the derived movable input stream classes `[std::basic\_ifstream](../basic_ifstream "cpp/io/basic ifstream")` and `[std::basic\_istringstream](../basic_istringstream "cpp/io/basic istringstream")`, which know how to correctly move-assign the associated streambuffers. ### Parameters | | | | | --- | --- | --- | | rhs | - | the basic\_istream object from which to assign to `*this` | ### Example ``` #include <sstream> #include <iostream> int main() { std::istringstream s1; s1 = std::istringstream("test"); // OK std::cin = std::istringstream("test"); // ERROR: 'operator=' is protected } ``` cpp std::basic_istream<CharT,Traits>::getline std::basic\_istream<CharT,Traits>::getline ========================================== | | | | | --- | --- | --- | | ``` basic_istream& getline( char_type* s, std::streamsize count ); ``` | (1) | | | ``` basic_istream& getline( char_type* s, std::streamsize count, char_type delim ); ``` | (2) | | Extracts characters from stream until end of line or the specified delimiter `delim`. The first overload is equivalent to `getline(s, count, widen('\n'))`. Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, extracts characters from `*this` and stores them in successive locations of the array whose first element is pointed to by `s`, until any of the following occurs (tested in the order shown): 1. end of file condition occurs in the input sequence (in which case `setstate(eofbit)` is executed) 2. the next available character `c` is the delimiter, as determined by `Traits::eq(c, delim)`. The delimiter is extracted (unlike [`basic_istream::get()`](get "cpp/io/basic istream/get")) and counted towards `[gcount()](gcount "cpp/io/basic istream/gcount")`, but is not stored. 3. `count-1` characters have been extracted (in which case `setstate(failbit)` is executed). If the function extracts no characters (e.g. if `count < 1`), `setstate(failbit)` is executed. In any case, if `count > 0`, it then stores a null character `CharT()` into the next successive location of the array and updates `[gcount()](gcount "cpp/io/basic istream/gcount")`. ### Notes Because condition #2 is tested before condition #3, the input line that exactly fits the buffer does not trigger `failbit`. Because the terminating character is counted as an extracted character, an empty input line does not trigger `failbit`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the character string to store the characters to | | count | - | size of character string pointed to by `s` | | delim | - | delimiting character to stop the extraction at. It is extracted but not stored. | ### Return value `*this`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example ``` #include <iostream> #include <sstream> #include <vector> #include <array> int main() { std::istringstream input("abc|def|gh"); std::vector<std::array<char, 4>> v; // note: the following loop terminates when std::ios_base::operator bool() // on the stream returned from getline() returns false for (std::array<char, 4> a; input.getline(&a[0], 4, '|'); ) { v.push_back(a); } for (auto& a : v) { std::cout << &a[0] << '\n'; } } ``` Output: ``` abc def gh ``` ### See also | | | | --- | --- | | [getline](../../string/basic_string/getline "cpp/string/basic string/getline") | read data from an I/O stream into a string (function template) | | [operator>>](operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function) | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [read](read "cpp/io/basic istream/read") | extracts blocks of characters (public member function) | cpp std::basic_istream<CharT,Traits>::peek std::basic\_istream<CharT,Traits>::peek ======================================= | | | | | --- | --- | --- | | ``` int_type peek(); ``` | | | Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and testing the sentry object, reads the next character from the input stream without extracting it. ### Parameters (none). ### Return value If `good() == true`, returns the next character as obtained by `rdbuf()->sgetc()`. Otherwise, returns `Traits::eof()`. ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example ``` #include <sstream> #include <iostream> int main() { std::istringstream s1("Hello, world."); char c1 = s1.peek(); char c2 = s1.get(); std::cout << "Peeked: " << c1 << " got: " << c2 << '\n'; } ``` Output: ``` Peeked: H got: H ``` ### See also | | | | --- | --- | | [sgetc](../basic_streambuf/sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function of `std::basic_streambuf<CharT,Traits>`) | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [unget](unget "cpp/io/basic istream/unget") | unextracts a character (public member function) | cpp std::basic_istream<CharT,Traits>::operator>> std::basic\_istream<CharT,Traits>::operator>> ============================================= | | | | | --- | --- | --- | | ``` basic_istream& operator>>( short& value ); basic_istream& operator>>( unsigned short& value ); ``` | (1) | | | ``` basic_istream& operator>>( int& value ); basic_istream& operator>>( unsigned int& value ); ``` | (2) | | | ``` basic_istream& operator>>( long& value ); basic_istream& operator>>( unsigned long& value ); ``` | (3) | | | ``` basic_istream& operator>>( long long& value ); basic_istream& operator>>( unsigned long long& value ); ``` | (4) | (since C++11) | | ``` basic_istream& operator>>( float& value ); basic_istream& operator>>( double& value ); basic_istream& operator>>( long double& value ); ``` | (5) | | | ``` basic_istream& operator>>( bool& value ); ``` | (6) | | | ``` basic_istream& operator>>( void*& value ); ``` | (7) | | | ``` basic_istream& operator>>( std::ios_base& (*func)(std::ios_base&) ); ``` | (8) | | | ``` basic_istream& operator>>( std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) ); ``` | (9) | | | ``` basic_istream& operator>>( basic_istream& (*func)(basic_istream&) ); ``` | (10) | | | ``` basic_istream& operator>>( std::basic_streambuf<CharT,Traits>* sb ); ``` | (11) | | Extracts values from an input stream. 1-4) Extracts an integer value potentially skipping preceding whitespace. The value is stored to a given reference `value`. This function behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, extracts an integer value by calling [`std::num_get::get()`](../../locale/num_get/get "cpp/locale/num get/get"). If `value` is `short` or `int`, a `long` value is extracted instead. 5) Extracts a floating-point value potentially skipping preceding whitespace. The value is stored to a given reference `value`. This function behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, extracts a floating-point value by calling [`std::num_get::get()`](../../locale/num_get/get "cpp/locale/num get/get"). 6) Extracts a boolean value potentially skipping preceding whitespace. The value is stored to a given reference `value`. This function behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, extracts an bool value by calling [`std::num_get::get()`](../../locale/num_get/get "cpp/locale/num get/get"). 7) Extracts a generic pointer value potentially skipping preceding whitespace. The value is stored to a given reference `value`. This function behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, extracts a generic pointer value by calling [`std::num_get::get()`](../../locale/num_get/get "cpp/locale/num get/get"). 8-10) Calls `func(*this)`, where `func` is an I/O manipulator. 11) Behaves as an [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, extracts all data from the input stream and stores it to `sb`. The extraction stops if one of the following conditions are met: * end-of-file occurs on the input sequence; * inserting in the output sequence fails (in which case the character to be inserted is not extracted); * an exception occurs (in which case the exception is caught, and only rethrown if it inserted no characters and `failbit` is enabled in `exceptions()`). In either case, stores the number of characters extracted in the member variable accessed by subsequent calls to `[gcount()](gcount "cpp/io/basic istream/gcount")`. If `sb` is a null pointer or if no characters were inserted into `sb`, calls `setstate(failbit)` (which may throw `[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` if enabled). If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to `value` and `failbit` is set. For signed integers, if extraction results in the value too large or too small to fit in `value`, `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max()` or `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::min()` (respectively) is written and `failbit` flag is set. For unsigned integers, if extraction results in the value too large or too small to fit in `value`, `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::max()` is written and `failbit` flag is set. ### Parameters | | | | | --- | --- | --- | | value | - | reference to an integer or floating-point value to store the extracted value to | | func | - | pointer to I/O manipulator function | | sb | - | pointer to the streambuffer to write all the data to | ### Return value 1-9,11) `*this` 10) `func(*this)` ### Example ``` #include <iostream> #include <iomanip> #include <sstream> int main() { std::string input = "41 3.14 false hello world"; std::istringstream stream(input); int n; double f; bool b; stream >> n >> f >> std::boolalpha >> b; std::cout << "n = " << n << '\n' << "f = " << f << '\n' << "b = " << std::boolalpha << b << '\n'; // extract the rest using the streambuf overload stream >> std::cout.rdbuf(); std::cout << '\n'; } ``` Output: ``` n = 41 f = 3.14 b = false hello world ``` ### 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 64](https://cplusplus.github.io/LWG/issue64) | C++98 | it was unclear whether overload (11) can only rethrow the`[std::ios\_base::failure](../ios_base/failure "cpp/io/ios base/failure")` thrown by calling `setstate(failbit)` | all exceptions caughtcan be rethrown | | [LWG 118](https://cplusplus.github.io/LWG/issue118) | C++98 | overloads (1)-(4) delegated the extraction to [`num_get::get`](../../locale/num_get/get "cpp/locale/num get/get"),but it does not have overloads for `short` and `int` | a `long` value is extractedinstead of `short` or `int` | | [LWG 696](https://cplusplus.github.io/LWG/issue696) | C++98 | `value` was unchanged on extraction failure | set to zero or minimum/maximum values | ### See also | | | | --- | --- | | [operator>>(std::basic\_istream)](operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) | | [operator<<operator>>](../../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) | | [operator<<operator>>](../../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") | performs stream input and output of bitsets (function template) | | [operator<<operator>>](../../numeric/complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") | serializes and deserializes a complex number (function template) | | [operator<<operator>>](../../numeric/random/linear_congruential_engine/operator_ltltgtgt "cpp/numeric/random/linear congruential engine/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number engine (function template) | | [operator<<operator>>](../../numeric/random/uniform_int_distribution/operator_ltltgtgt "cpp/numeric/random/uniform int distribution/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number distribution (function template) | | [read](read "cpp/io/basic istream/read") | extracts blocks of characters (public member function) | | [readsome](readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function) | | [get](get "cpp/io/basic istream/get") | extracts characters (public member function) | | [getline](getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | cpp std::basic_istream<CharT,Traits>::get std::basic\_istream<CharT,Traits>::get ====================================== | | | | | --- | --- | --- | | ``` int_type get(); ``` | (1) | | | ``` basic_istream& get( char_type& ch ); ``` | (2) | | | ``` basic_istream& get( char_type* s, std::streamsize count ); ``` | (3) | | | ``` basic_istream& get( char_type* s, std::streamsize count, char_type delim ); ``` | (4) | | | ``` basic_istream& get( basic_streambuf& strbuf ); ``` | (5) | | | ``` basic_istream& get( basic_streambuf& strbuf, char_type delim ); ``` | (6) | | Extracts character or characters from stream. All versions behave as [UnformattedInputFunctions](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"). After constructing and checking the sentry object, these functions perform the following: 1) Reads one character and returns it if available. Otherwise, returns `Traits::eof()` and sets `[failbit](../ios_base/iostate "cpp/io/ios base/iostate")` and `[eofbit](../ios_base/iostate "cpp/io/ios base/iostate")`. 2) Reads one character and stores it to `ch` if available. Otherwise, leaves `ch` unmodified and sets `[failbit](../ios_base/iostate "cpp/io/ios base/iostate")` and `[eofbit](../ios_base/iostate "cpp/io/ios base/iostate")`. Note that this function is not overloaded on the types `signed char` and `unsigned char`, unlike the formatted character input operator>>. 3) Same as `get(s, count, widen('\n'))`, that is, reads at most `count-1` characters and stores them into character string pointed to by `s` until `'\n'` is found. 4) Reads characters and stores them into the successive locations of the character array whose first element is pointed to by `s`. Characters are extracted and stored until any of the following occurs: * `count-1` characters have been stored * end of file condition occurs in the input sequence (`setstate(eofbit)` is called) * the next available input character `c` equals `delim`, as determined by `Traits::eq(c, delim)`. This character is not extracted (unlike [`basic_istream::getline()`](getline "cpp/io/basic istream/getline")) If no characters were extracted, calls `setstate(failbit)`. In any case, if `count>0`, a null character (`CharT()` is stored in the next successive location of the array. 5) same as `get(strbuf, widen('\n'))`, that is, reads available characters and inserts them to the given [`basic_streambuf`](../basic_streambuf "cpp/io/basic streambuf") object until `'\n'` is found. 6) reads characters and inserts them to the output sequence controlled by the given [`basic_streambuf`](../basic_streambuf "cpp/io/basic streambuf") object. Characters are extracted and inserted into `strbuf` until any of the following occurs: * end of file condition occurs in the input sequence * inserting into the output sequence fails (in which case the character that could not be inserted, is not extracted) * the next available input character `c` equals `delim`, as determined by `Traits::eq(c, delim)`. This character is not extracted. * an exception occurs (in which case the exception is caught and not rethrown) If no characters were extracted, calls `setstate(failbit)`. All versions set the value of `[gcount()](gcount "cpp/io/basic istream/gcount")` to the number of characters extracted. ### Parameters | | | | | --- | --- | --- | | ch | - | reference to the character to write the result to | | s | - | pointer to the character string to store the characters to | | count | - | size of character string pointed to by `s` | | delim | - | delimiting character to stop the extraction at. It is not extracted and not stored. | | strbuf | - | stream buffer to read the content to | ### Return value 1) the extracted character or `Traits::eof()` 2-6) `*this` ### Exceptions `[failure](../ios_base/failure "cpp/io/ios base/failure")` if an error occurred (the error state flag is not `[goodbit](../ios_base/iostate "cpp/io/ios base/iostate")`) and `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set to throw for that state. If an internal operation throws an exception, it is caught and `[badbit](../ios_base/iostate "cpp/io/ios base/iostate")` is set. If `[exceptions()](../basic_ios/exceptions "cpp/io/basic ios/exceptions")` is set for `badbit`, the exception is rethrown. ### Example ``` #include <sstream> #include <iostream> int main() { std::istringstream s1("Hello, world."); char c1 = s1.get(); // reads 'H' std::cout << "after reading " << c1 << ", gcount() == " << s1.gcount() << '\n'; char c2; s1.get(c2); // reads 'e' char str[5]; s1.get(str, 5); // reads "llo," std::cout << "after reading " << str << ", gcount() == " << s1.gcount() << '\n'; std::cout << c1 << c2 << str; s1.get(*std::cout.rdbuf()); // reads the rest, not including '\n' std::cout << "\nAfter the last get(), gcount() == " << s1.gcount() << '\n'; } ``` Output: ``` after reading H, gcount() == 1 after reading llo,, gcount() == 4 Hello, world. After the last get(), gcount() == 7 ``` ### See also | | | | --- | --- | | [read](read "cpp/io/basic istream/read") | extracts blocks of characters (public member function) | | [operator>>](operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function) | | [operator>>(std::basic\_istream)](operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) |
programming_docs
cpp std::basic_ifstream<CharT,Traits>::rdbuf std::basic\_ifstream<CharT,Traits>::rdbuf ========================================= | | | | | --- | --- | --- | | ``` std::basic_filebuf<CharT, Traits>* rdbuf() const; ``` | | (since C++11) | Returns pointer to the underlying raw file device object. ### Parameters (none). ### Return value Pointer to the underlying raw file device. ### Example cpp std::basic_ifstream<CharT,Traits>::swap std::basic\_ifstream<CharT,Traits>::swap ======================================== | | | | | --- | --- | --- | | ``` void swap( basic_ifstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_istream<CharT, Traits>::swap(other)` and `rdbuf()->swap(other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <fstream> #include <iomanip> #include <iostream> #include <string> bool create_stream(std::fstream& fs, const std::string& path) { try { std::fstream fst { path, std::ios::trunc | std::ios::in | std::ios::out }; if (fst.is_open()) { fst.swap( fs ); return true; } } catch (...) { std::cout << "Exception!\n"; } return false; } void use_stream(std::fstream& fs) { fs.seekg(0); std::string data; fs >> data; std::cout << "data: " << std::quoted(data) << '\n'; } int main() { std::fstream fs; std::string path = "/tmp/test_file.txt"; if (create_stream(fs, path)) { fs.write(path.c_str(), path.length()); use_stream(fs); } } ``` Possible output: ``` data: "/tmp/test_file.txt" ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic ifstream/operator=") (C++11) | moves the file stream (public member function) | | [swap](../basic_filebuf/swap "cpp/io/basic filebuf/swap") (C++11) | swaps two basic\_filebuf objects (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::swap(std::basic_ifstream) std::swap(std::basic\_ifstream) =============================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( basic_ifstream<CharT,Traits> &lhs, basic_ifstream<CharT,Traits> &rhs ); ``` | | | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ifstream/swap") (C++11) | swaps two file streams (public member function) | cpp std::basic_ifstream<CharT,Traits>::operator= std::basic\_ifstream<CharT,Traits>::operator= ============================================= | | | | | --- | --- | --- | | ``` basic_ifstream& operator=( basic_ifstream&& other ); ``` | | (since C++11) | Move assigns the file stream `other` to `*this`, effectively move-assigning both the `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` base class and the associated `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")`. `other` is left with no associated file. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | file stream to move. | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic ifstream/swap") (C++11) | swaps two file streams (public member function) | | [operator=](../basic_filebuf/operator= "cpp/io/basic filebuf/operator=") (C++11) | assigns a basic\_filebuf object (public member function of `std::basic_filebuf<CharT,Traits>`) | | [operator=](../basic_istream/operator= "cpp/io/basic istream/operator=") (C++11) | move-assigns from another `basic_istream` (protected member function) | cpp std::basic_ifstream<CharT,Traits>::close std::basic\_ifstream<CharT,Traits>::close ========================================= | | | | | --- | --- | --- | | ``` void close(); ``` | | | Closes the associated file. Effectively calls [`rdbuf()->close()`](../basic_filebuf/close "cpp/io/basic filebuf/close"). If an error occurs during operation, `setstate(failbit)` is called. ### Parameters (none). ### Return value (none). ### Notes This function is called by the destructor of basic\_ifstream when the stream object goes out of scope and is not usually invoked directly. ### Example ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic ifstream/is open") | checks if the stream has an associated file (public member function) | | [open](open "cpp/io/basic ifstream/open") | opens a file and associates it with the stream (public member function) | | [close](../basic_filebuf/close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_ifstream<CharT,Traits>::open std::basic\_ifstream<CharT,Traits>::open ======================================== | | | | | --- | --- | --- | | ``` void open( const char *filename, ios_base::openmode mode = ios_base::in ); ``` | (1) | | | ``` void open( const std::filesystem::path::value_type *filename, ios_base::openmode mode = ios_base::in ); ``` | (2) | (since C++17) | | ``` void open( const std::string &filename, ios_base::openmode mode = ios_base::in ); ``` | (3) | (since C++11) | | ``` void open( const std::filesystem::path &filename, ios_base::openmode mode = ios_base::in ); ``` | (4) | (since C++17) | Opens and associates the file with name `filename` with the file stream. Calls `setstate(failbit)` on failure. | | | | --- | --- | | Calls `clear()` on success. | (since C++11) | 1-2) Effectively calls `rdbuf()->open(filename, mode | ios_base::in)`. (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). Overload (2) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 3-4) Effectively calls (1-2) as if by `open(filename.c_str(), mode)`. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | ### Return value (none). ### 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 22](https://cplusplus.github.io/LWG/issue22) | C++98 | it was unclear how error state changes upon a successful open | the error state is unchanged | ### See also | | | | --- | --- | | [is\_open](is_open "cpp/io/basic ifstream/is open") | checks if the stream has an associated file (public member function) | | [close](close "cpp/io/basic ifstream/close") | closes the associated file (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_ifstream<CharT,Traits>::basic_ifstream std::basic\_ifstream<CharT,Traits>::basic\_ifstream =================================================== | | | | | --- | --- | --- | | ``` basic_ifstream(); ``` | (1) | | | ``` explicit basic_ifstream( const char* filename, std::ios_base::openmode mode = ios_base::in ); ``` | (2) | | | ``` explicit basic_ifstream( const std::filesystem::path::value_type* filename, std::ios_base::openmode mode = ios_base::in ); ``` | (3) | (since C++17) | | ``` explicit basic_ifstream( const std::string& filename, std::ios_base::openmode mode = ios_base::in ); ``` | (4) | (since C++11) | | ``` template< class FsPath > explicit basic_ifstream( const FsPath& filename, std::ios_base::openmode mode = ios_base::in ); ``` | (5) | (since C++17) | | ``` basic_ifstream( basic_ifstream&& other ); ``` | (6) | (since C++11) | | ``` basic_ifstream( const basic_ifstream& rhs) = delete; ``` | (7) | (since C++11) | Constructs new file stream. 1) Default constructor: constructs a stream that is not associated with a file: default-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` and constructs the base with the pointer to this default-constructed `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member. 2-3) First, performs the same steps as the default constructor, then associates the stream with a file by calling `rdbuf()->open(filename, mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))` (see `[std::basic\_filebuf::open](../basic_filebuf/open "cpp/io/basic filebuf/open")` for the details on the effects of that call). If the `open()` call returns a null pointer, sets `setstate(failbit)`. Overload (3) is only provided if `std::filesystem::path::value_type` is not `char`. (since C++17) 4-5) Same as `basic_ifstream(filename.c_str(), mode)`. (5) participates in overload resolution only if `FsPath` is `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")`. (since C++17) 6) Move constructor. First, move-constructs the base class from `other` (which does not affect the `rdbuf()` pointer), then move-constructs the `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")` member, then calls `this->set_rdbuf()` to install the new `basic_filebuf` as the `rdbuf()` pointer in the base class. 7) The copy-constructor is deleted: this class is not copyable. ### Parameters | | | | | --- | --- | --- | | filename | - | the name of the file to be opened | | mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another file stream to use as source | ### Example ``` #include <fstream> #include <utility> #include <string> int main() { std::ifstream f0; std::ifstream f1("test.bin", std::ios::binary); std::string name = "example.txt"; std::ifstream f2(name); std::ifstream f3(std::move(f1)); } ``` ### 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 3430](https://cplusplus.github.io/LWG/issue3430) | C++17 | `[std::filesystem::path](../../filesystem/path "cpp/filesystem/path")` overload led to unwanted conversions | avoided by making it a template | ### See also | | | | --- | --- | | [open](open "cpp/io/basic ifstream/open") | opens a file and associates it with the stream (public member function) | | [open](../basic_filebuf/open "cpp/io/basic filebuf/open") | opens a file and configures it as the associated character sequence (public member function of `std::basic_filebuf<CharT,Traits>`) | | [set\_rdbuf](../basic_ios/set_rdbuf "cpp/io/basic ios/set rdbuf") | replaces the `rdbuf` without clearing its error state (protected member function) | | [(constructor)](../basic_istream/basic_istream "cpp/io/basic istream/basic istream") | constructs the object (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_ifstream<CharT,Traits>::is_open std::basic\_ifstream<CharT,Traits>::is\_open ============================================ | | | | | --- | --- | --- | | ``` bool is_open(); ``` | | (until C++11) | | ``` bool is_open() const; ``` | | (since C++11) | Checks if the file stream has an associated file. Effectively calls [`rdbuf()->is_open()`](../basic_filebuf/is_open "cpp/io/basic filebuf/is open"). ### Parameters (none). ### Return value `true` if the file stream has an associated file, `false` otherwise. ### Example ``` #include <string> #include <fstream> #include <iostream> //this file is called main.cpp bool file_exists(const std::string& str) { std::ifstream fs(str); return fs.is_open(); } int main() { std::boolalpha(std::cout); std::cout << file_exists("main.cpp") << '\n' << file_exists("strange_file") << '\n'; } ``` Possible output: ``` true false ``` ### See also | | | | --- | --- | | [open](open "cpp/io/basic ifstream/open") | opens a file and associates it with the stream (public member function) | | [close](close "cpp/io/basic ifstream/close") | closes the associated file (public member function) | cpp std::basic_stringstream::rdbuf std::basic\_stringstream::rdbuf =============================== | | | | | --- | --- | --- | | ``` std::basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; ``` | | | Returns pointer to the underlying raw string device object. ### Parameters (none). ### Return value Pointer to the underlying raw string device. ### Example cpp std::basic_stringstream::swap std::basic\_stringstream::swap ============================== | | | | | --- | --- | --- | | ``` void swap( basic_stringstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_iostream<CharT, Traits>::swap(other)` and `rdbuf()->swap(*other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic stringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](../basic_stringbuf/swap "cpp/io/basic stringbuf/swap") (C++11) | swaps two basic\_stringbuf objects (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_stringstream<CharT,Traits,Allocator>::basic_stringstream std::basic\_stringstream<CharT,Traits,Allocator>::basic\_stringstream ===================================================================== | | | | | --- | --- | --- | | ``` basic_stringstream() : basic_stringstream(std::ios_base::in | std::ios_base::out) { } ``` | (1) | (since C++11) | | | (2) | | | ``` explicit basic_stringstream( std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (until C++11) | | ``` explicit basic_stringstream( std::ios_base::openmode mode ); ``` | (since C++11) | | ``` explicit basic_stringstream( const std::basic_string<CharT,Traits,Allocator>& str, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (3) | | | ``` basic_stringstream( basic_stringstream&& other ); ``` | (4) | (since C++11) | | ``` basic_stringstream( std::ios_base::openmode mode, const Allocator& a ); ``` | (5) | (since C++20) | | ``` explicit basic_stringstream( std::basic_string<CharT,Traits,Allocator>&& str, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (6) | (since C++20) | | ``` template<class SAlloc> basic_stringstream( const std::basic_string<CharT,Traits,SAlloc>& str, const Allocator& a ) : basic_stringstream(str, std::ios_base::in | std::ios_base::out, a) { } ``` | (7) | (since C++20) | | ``` template<class SAlloc> basic_stringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode, const Allocator& a ); ``` | (8) | (since C++20) | | ``` template<class SAlloc> explicit basic_stringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out ); ``` | (9) | (since C++20) | Constructs new string stream. 1) Default constructor. Constructs new underlying string device with the default open mode 2) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode)`. 3) Uses a copy of `str` as initial contents of the underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode)`. 4) Move constructor. Constructs the string stream with the state of `other` using move semantics. 5) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode, a)`. 6) Move-construct the contents of the underlying string device with `str`. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(std::move(str), mode)`. 7) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode) | [std::ios\_base::out](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 8) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode, a)`. 9) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode)`. This overload participates in overload resolution only if `SAlloc` and `Allocator` are not the same type. ### Parameters | | | | | --- | --- | --- | | str | - | string to use as initial contents of the string stream | | a | - | allocator used for allocating the contents of the string stream | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another string stream to use as source | ### Notes Construction of one-off `basic_stringstream` objects in a tight loop, such as when used for string conversion, may be significantly more costly than calling `[str](str "cpp/io/basic stringstream/str")` to reuse the same object. ### Example ``` #include <iostream> #include <sstream> int main() { // default constructor (input/output stream) std::stringstream buf1; buf1 << 7; int n = 0; buf1 >> n; std::cout << "buf1 = " << buf1.str() << " n = " << n << '\n'; // input stream std::istringstream inbuf("-10"); inbuf >> n; std::cout << "n = " << n << '\n'; // output stream in append mode (C++11) std::ostringstream buf2("test", std::ios_base::ate); buf2 << '1'; std::cout << buf2.str() << '\n'; } ``` Output: ``` buf1 = 7 n = 7 n = -10 test1 ``` ### 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 | ### See also | | | | --- | --- | | [str](str "cpp/io/basic stringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [(constructor)](../basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) |
programming_docs
cpp std::basic_stringstream<CharT,Traits,Allocator>::str std::basic\_stringstream<CharT,Traits,Allocator>::str ===================================================== | | | | | --- | --- | --- | | | (1) | | | ``` std::basic_string<CharT,Traits,Allocator> str() const; ``` | (until C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() const&; ``` | (since C++20) | | ``` template<class SAlloc> std::basic_string<CharT,Traits,SAlloc> str( const SAlloc& a ) const; ``` | (2) | (since C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() &&; ``` | (3) | (since C++20) | | ``` void str( const std::basic_string<CharT,Traits,Allocator>& s ); ``` | (4) | | | ``` template<class SAlloc> void str( const std::basic_string<CharT,Traits, SAlloc>& s ); ``` | (5) | (since C++20) | | ``` void str( std::basic_string<CharT,Traits,Allocator>&& s ); ``` | (6) | (since C++20) | Manages the contents of the underlying string object. 1) Returns a copy of the underlying string. Equivalent to `return rdbuf()->str();`. 2) Returns a copy of the underlying string, using `a` as allocator. Equivalent to `return rdbuf()->str(a);`. 3) Returns a string move-constructed from the underlying string. Equivalent to `return std::move(*rdbuf()).str();`. 4-5) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(s);`. 6) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(std::move(s));`. ### Parameters | | | | | --- | --- | --- | | s | - | new contents of the underlying string | | a | - | allocator used to construct the returned string | ### Return value 1-2) a copy of the underlying string object. 3) a string move-constructed from the underlying string object. 4-6) (none) ### Notes The copy of the underlying string returned by `str` is a temporary object that will be destructed at the end of the expression, so directly calling [`c_str()`](../../string/basic_string/c_str "cpp/string/basic string/c str") on the result of `str()` (for example in `auto *ptr = out.str().c_str();`) results in a dangling pointer. ### Example ``` #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; } ``` Output: ``` after reading the first int from "1 2", the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2", str() = "3 2" after writing the int '3' to append stream "1 2", str() = "1 23" ``` ### See also | | | | --- | --- | | [rdbuf](rdbuf "cpp/io/basic stringstream/rdbuf") | returns the underlying raw string device object (public member function) | | [str](../basic_stringbuf/str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::swap(std::basic_stringstream) std::swap(std::basic\_stringstream) =================================== | Defined in header `[<sstream>](../../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_stringstream<CharT,Traits,Alloc>& lhs, std::basic_stringstream<CharT,Traits,Alloc>& rhs ); ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_stringstream](http://en.cppreference.com/w/cpp/io/basic_stringstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic stringstream/swap") (C++11) | swaps two string streams (public member function) | cpp std::basic_stringstream<CharT,Traits,Allocator>::view std::basic\_stringstream<CharT,Traits,Allocator>::view ====================================================== | | | | | --- | --- | --- | | ``` std::basic_string_view<CharT, Traits> view() const noexcept; ``` | | (since C++20) | Obtains a `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. Equivalent to `return rdbuf()->view();`. ### Parameters (none). ### Return value A `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. ### Example ### See also | | | | --- | --- | | [view](../basic_stringbuf/view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_stringstream::operator= std::basic\_stringstream::operator= =================================== | | | | | --- | --- | --- | | ``` basic_stringstream& operator=( basic_stringstream&& other ); ``` | | (since C++11) | Move assigns the string stream `other` to `*this`, effectively move-assigning both the `[std::basic\_iostream](../basic_iostream "cpp/io/basic iostream")` base class and the associated `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | string stream to move from | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic stringstream/swap") (C++11) | swaps two string streams (public member function) | | [operator=](../basic_stringbuf/operator= "cpp/io/basic stringbuf/operator=") (C++11) | assigns a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [operator=](../basic_iostream/operator= "cpp/io/basic iostream/operator=") (C++11) | move-assigns another `basic_iostream` (protected member function) | cpp std::basic_streambuf<CharT,Traits>::underflow std::basic\_streambuf<CharT,Traits>::underflow ============================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type underflow(); ``` | | | Ensures that at least one character is available in the input area by updating the pointers to the input area (if needed) and reading more data in from the input sequence (if applicable). Returns the value of that character (converted to `int_type` with `Traits::to_int_type(c)`) on success or `Traits::eof()` on failure. The function may update `gptr`, `egptr` and `eback` pointers to define the location of newly loaded data (if any). On failure, the function ensures that either `gptr() == nullptr` or `gptr() == egptr`. The base class version of the function does nothing. The derived classes may override this function to allow updates to the get area in the case of exhaustion. ### Parameters (none). ### Return value The value of the character pointed to by the *get pointer* after the call on success, or `Traits::eof()` otherwise. The base class version of the function returns `traits::eof()`. ### Note The public functions of `[std::streambuf](../basic_streambuf "cpp/io/basic streambuf")` call this function only if `gptr() == nullptr` or `gptr() >= egptr()`. ### Example ``` #include <iostream> #include <sstream> class null_filter_buf : public std::streambuf { std::streambuf* src; char ch; // single-byte buffer protected: int underflow() { traits_type::int_type i; while ((i = src->sbumpc()) == '\0') ; // skip zeroes if (!traits_type::eq_int_type(i, traits_type::eof())) { ch = traits_type::to_char_type(i); setg(&ch, &ch, &ch+1); // make one read position available } return i; } public: null_filter_buf(std::streambuf* buf) : src(buf) { setg(&ch, &ch+1, &ch+1); // buffer is initially full } }; void filtered_read(std::istream& in) { std::streambuf* orig = in.rdbuf(); null_filter_buf buf(orig); in.rdbuf(&buf); for(char c; in.get(c); ) std::cout << c; in.rdbuf(orig); } int main() { char a[] = "This i\0s \0an e\0\0\0xample"; std::istringstream in(std::string(std::begin(a), std::end(a))); filtered_read(in); } ``` Output: ``` This is an example ``` ### See also | | | | --- | --- | | [uflow](uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function) | | [overflow](overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function) | | [underflow](../basic_filebuf/underflow "cpp/io/basic filebuf/underflow") [virtual] | reads from the associated file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [underflow](../basic_stringbuf/underflow "cpp/io/basic stringbuf/underflow") [virtual] | returns the next character available in the input sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [underflow](../strstreambuf/underflow "cpp/io/strstreambuf/underflow") [virtual] | reads a character from the input sequence without advancing the next pointer (virtual protected member function of `std::strstreambuf`) | cpp std::basic_streambuf<CharT,Traits>::setg std::basic\_streambuf<CharT,Traits>::setg ========================================= | | | | | --- | --- | --- | | ``` protected: void setg( char_type* gbeg, char_type* gcurr, char_type* gend ); ``` | | | Sets the values of the pointers defining the get area. Specifically, after the call `eback() == gbeg`, `gptr() == gcurr`, `egptr() == gend`. ### Parameters | | | | | --- | --- | --- | | gbeg | - | pointer to the new beginning of the get area | | gcurr | - | pointer to the new current character (*get pointer*) in the get area | | gend | - | pointer to the new end of the get area | ### Return value (none). ### Example ``` #include <iostream> #include <sstream> class null_filter_buf : public std::streambuf { std::streambuf* src; char ch; // single-byte buffer protected: int underflow() { traits_type::int_type i; while ((i = src->sbumpc()) == '\0') ; // skip zeroes if (!traits_type::eq_int_type(i, traits_type::eof())) { ch = traits_type::to_char_type(i); setg(&ch, &ch, &ch+1); // make one read position available } return i; } public: null_filter_buf(std::streambuf* buf) : src(buf) { setg(&ch, &ch+1, &ch+1); // buffer is initially full } }; void filtered_read(std::istream& in) { std::streambuf* orig = in.rdbuf(); null_filter_buf buf(orig); in.rdbuf(&buf); for(char c; in.get(c); ) std::cout << c; in.rdbuf(orig); } int main() { char a[] = "This i\0s \0an e\0\0\0xample"; std::istringstream in(std::string(std::begin(a), std::end(a))); filtered_read(in); } ``` Output: ``` This is an example ``` ### See also | | | | --- | --- | | [setp](setp "cpp/io/basic streambuf/setp") | repositions the beginning, next, and end pointers of the output sequence (protected member function) | cpp std::basic_streambuf<CharT,Traits>::pbump std::basic\_streambuf<CharT,Traits>::pbump ========================================== | | | | | --- | --- | --- | | ``` protected: void pbump( int count ); ``` | | | Repositions the *put pointer* (`[pptr()](pptr "cpp/io/basic streambuf/pptr")`) by `count` characters, where `count` may be positive or negative. No checks are done for moving the pointer outside the put area `[pbase(), epptr())`. If the pointer is advanced and then `[overflow()](overflow "cpp/io/basic streambuf/overflow")` is called to flush the put area to the associated character sequence, the effect is that extra `count` characters with undefined values are output. ### Parameters | | | | | --- | --- | --- | | count | - | number to add to the put pointer | ### Return value (none). ### Notes Because this function takes an `int`, it cannot manipulate buffers larger than `std::numeric_limits<int>::max()` characters ([LWG 255](http://wg21.link/lwg255)). ### Example ``` #include <iostream> #include <string> #include <fstream> struct showput_streambuf : std::filebuf { using std::filebuf::pbump; // expose protected std::string showput() const { return std::string(pbase(), pptr()); } }; int main() { showput_streambuf mybuf; mybuf.open("test.txt", std::ios_base::out); std::ostream str(&mybuf); str << "This is a test" << std::flush << "1234"; std::cout << "The put area contains: " << mybuf.showput() << '\n'; mybuf.pbump(10); std::cout << "after pbump(10), it contains " << mybuf.showput() << '\n'; } ``` Output: ``` The put area contains: 1234 after pbump(10), it contains 1234 is a test ``` ### See also | | | | --- | --- | | [gbump](gbump "cpp/io/basic streambuf/gbump") | advances the next pointer in the input sequence (protected member function) | cpp std::basic_streambuf<CharT,Traits>::pubseekoff, std::basic_streambuf<CharT,Traits>::seekoff std::basic\_streambuf<CharT,Traits>::pubseekoff, std::basic\_streambuf<CharT,Traits>::seekoff ============================================================================================= | | | | | --- | --- | --- | | ``` pos_type pubseekoff( off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which = ios_base::in | ios_base::out ); ``` | (1) | | | ``` protected: virtual pos_type seekoff( off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which = ios_base::in | ios_base::out ); ``` | (2) | | Sets the position indicator of the input and/or output sequence relative to some other position. 1) Calls `seekoff(off, dir, which)` of the most derived class. 2) The base class version of this function has no effect. The derived classes may override this function to allow relative positioning of the position indicator. ### Parameters | | | | | --- | --- | --- | | off | - | relative position to set the position indicator to. | | dir | - | defines base position to apply the relative offset to. It can be one of the following constants: | Constant | Explanation | | --- | --- | | [`beg`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the beginning of a stream | | [`end`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the ending of a stream | | [`cur`](../ios_base/seekdir "cpp/io/ios base/seekdir") | the current position of stream position indicator | | | which | - | defines which of the input and/or output sequences to affect. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Note Not all combinations of parameters may be valid, see the derived versions of `seekoff` for details. ### Return value 1) The return value of `seekoff(off, dir, which)` 2) The resulting absolute position as defined by the position indicator. The base class version returns `pos_type(off_type(-1))`. ### 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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | the base class version of `seekoff` returnedan undefined invalid stream position | returns `pos_type(off_type(-1))` | ### See also | | | | --- | --- | | [pubseekpos](pubseekpos "cpp/io/basic streambuf/pubseekpos") | invokes `seekpos()` (public member function) | | [seekoff](../basic_filebuf/seekoff "cpp/io/basic filebuf/seekoff") [virtual] | repositions the file position, using relative addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekoff](../basic_stringbuf/seekoff "cpp/io/basic stringbuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekoff](../strstreambuf/seekoff "cpp/io/strstreambuf/seekoff") [virtual] | repositions the next pointer in the input sequence, output sequence, or both, using relative addressing (virtual protected member function of `std::strstreambuf`) | cpp std::basic_streambuf<CharT,Traits>::pubsync, std::basic_streambuf<CharT,Traits>::sync std::basic\_streambuf<CharT,Traits>::pubsync, std::basic\_streambuf<CharT,Traits>::sync ======================================================================================= | | | | | --- | --- | --- | | ``` int pubsync(); ``` | (1) | | | ``` protected: virtual int sync(); ``` | (2) | | Synchronizes the controlled character sequence (the buffers) with the associated character sequence. 1) Calls `sync()` of the most derived class. 2) The base class version of this function has no effect. The derived classes may override this function to allow synchronizing the underlying device with the buffers. For output streams, this typically results in writing the contents of the put area into the associated sequence, i.e. flushing of the output buffer. For input streams, this typically empties the get area and forces a re-read from the associated sequence to pick up recent changes. The default behavior (found, for example, in `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`), is to do nothing. ### Parameters (none). ### Return value 1) The return value of `sync()`. 2) Returns `​0​` on success, `-1` otherwise. The base class version returns `​0​`. ### Example ### See also | | | | --- | --- | | [sync](../basic_istream/sync "cpp/io/basic istream/sync") | synchronizes with the underlying storage device (public member function of `std::basic_istream<CharT,Traits>`) | | [sync](../basic_filebuf/sync "cpp/io/basic filebuf/sync") [virtual] | writes characters to the associated file from the put area (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_streambuf<CharT,Traits>::sgetc std::basic\_streambuf<CharT,Traits>::sgetc ========================================== | | | | | --- | --- | --- | | ``` int_type sgetc(); ``` | | | Reads one character from the input sequence. If the input sequence read position is not available, returns `[underflow()](underflow "cpp/io/basic streambuf/underflow")`. Otherwise returns `Traits::to_int_type(*gptr())`. ### Parameters (none). ### Return value The value of the character pointed to by the *get pointer*. ### Example ``` #include <iostream> #include <sstream> int main() { std::stringstream stream("Hello, world"); std::cout << "sgetc() returned '" << (char)stream.rdbuf()->sgetc() << "'\n"; std::cout << "peek() returned '" << (char)stream.peek() << "'\n"; std::cout << "get() returned '" << (char)stream.get() << "'\n"; } ``` Output: ``` sgetc() returned 'H' peek() returned 'H' get() returned 'H' ``` ### See also | | | | --- | --- | | [sbumpcstossc](sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function) | | [snextc](snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function) |
programming_docs
cpp std::basic_streambuf<CharT,Traits>::sputc std::basic\_streambuf<CharT,Traits>::sputc ========================================== | | | | | --- | --- | --- | | ``` int_type sputc( char_type ch ); ``` | | | Writes one character to the output sequence. If the output sequence write position is not available (the buffer is full), then calls `overflow(ch)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to write | ### Return value The written character, converted to `int_type` with `Traits::to_int_type(ch)` on success. `Traits::eof()` (as returned by `[overflow()](overflow "cpp/io/basic streambuf/overflow")`) on failure. ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream s; s.rdbuf()->sputc('a'); std::cout << s.str() << '\n'; } ``` Output: ``` a ``` ### See also | | | | --- | --- | | [sputn](sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function) | cpp std::basic_streambuf<CharT,Traits>::swap std::basic\_streambuf<CharT,Traits>::swap ========================================= | | | | | --- | --- | --- | | ``` void swap( basic_streambuf& other ); ``` | | (since C++11) | Exchanges the contents of the stream buffer with those of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | stream buffer to exchange contents with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example cpp std::basic_streambuf<CharT,Traits>::getloc std::basic\_streambuf<CharT,Traits>::getloc =========================================== | | | | | --- | --- | --- | | ``` std::locale getloc() const; ``` | | | Returns the associated locale. The associated locale is the value supplied to `[pubimbue()](pubimbue "cpp/io/basic streambuf/pubimbue")` on the last call, or, if that function has not been called, the value of the global locale (`[std::locale](../../locale/locale "cpp/locale/locale")`) at the time of the construction of the streambuf. ### Parameters (none). ### Return value The associated locale. ### Example ### See also | | | | --- | --- | | [pubimbue](pubimbue "cpp/io/basic streambuf/pubimbue") | invokes `imbue()` (public member function) | cpp std::basic_streambuf<CharT,Traits>::sputn, std::basic_streambuf<CharT,Traits>::xsputn std::basic\_streambuf<CharT,Traits>::sputn, std::basic\_streambuf<CharT,Traits>::xsputn ======================================================================================= | | | | | --- | --- | --- | | ``` std::streamsize sputn( const char_type* s, std::streamsize count ); ``` | (1) | | | ``` protected: virtual std::streamsize xsputn( const char_type* s, std::streamsize count ); ``` | (2) | | 1) Calls `xsputn(s, count)` of the most derived class. 2) Writes `count` characters to the output sequence from the character array whose first element is pointed to by `s`. The characters are written as if by repeated calls to `[sputc()](sputc "cpp/io/basic streambuf/sputc")`. Writing stops when either `count` characters are written or a call to `[sputc()](sputc "cpp/io/basic streambuf/sputc")` would have returned `Traits::eof()`. If the put area becomes full (`pptr() == epptr()`), this function may call `[overflow()](overflow "cpp/io/basic streambuf/overflow")`, or achieve the effect of calling `overflow()` by some other, unspecified, means. ### Parameters (none). ### Return value The number of characters successfully written. ### Notes "achieving effects of `overflow()` by unspecified means" permits bulk I/O without intermediate buffering: that's how `[std::ofstream::write](../basic_ostream/write "cpp/io/basic ostream/write")` simply passes the pointer to the suitable system call in some implementations of iostreams. ### Example ``` #include <iostream> #include <sstream> int main() { std::ostringstream s1; std::streamsize sz = s1.rdbuf()->sputn("This is a test", 14); s1 << '\n'; std::cout << "The call to sputn() returned " << sz << '\n' << "The output sequence contains " << s1.str(); std::istringstream s2; sz = s2.rdbuf()->sputn("This is a test", 14); std::cout << "The call to sputn() on an input stream returned " << sz << '\n'; } ``` Output: ``` The call to sputn() returned 14 The output sequence contains This is a test The call to sputn() on an input stream returned 0 ``` ### See also | | | | --- | --- | | [sgetn](sgetn "cpp/io/basic streambuf/sgetn") | invokes `xsgetn()` (public member function) | cpp std::basic_streambuf<CharT,Traits>::sgetn, std::basic_streambuf<CharT,Traits>::xsgetn std::basic\_streambuf<CharT,Traits>::sgetn, std::basic\_streambuf<CharT,Traits>::xsgetn ======================================================================================= | | | | | --- | --- | --- | | ``` std::streamsize sgetn( char_type* s, std::streamsize count ); ``` | (1) | | | ``` protected: virtual std::streamsize xsgetn( char_type* s, std::streamsize count ); ``` | (2) | | 1) Calls `xsgetn(s, count)` of the most derived class. 2) Reads `count` characters from the input sequence and stores them into a character array pointed to by `s`. The characters are read as if by repeated calls to `[sbumpc()](sbumpc "cpp/io/basic streambuf/sbumpc")`. That is, if less than `count` characters are immediately available, the function calls `[uflow()](uflow "cpp/io/basic streambuf/uflow")` to provide more until `Traits::eof()` is returned. Classes derived from `std::basic_streambuf` are permitted to provide more efficient implementations of this function. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the beginning of a char\_type array | | count | - | maximum number of characters to read. | ### Return value The number of characters successfully read. If it is less than `count` the input sequence has reached the end. ### Notes The rule about "more efficient implementations" permits bulk I/O without intermediate buffering: that's how `[std::ifstream::read](../basic_istream/read "cpp/io/basic istream/read")` simply passes the pointer to the POSIX `read()` system call in some implementations of iostreams. ### Example ### See also | | | | --- | --- | | [sputn](sputn "cpp/io/basic streambuf/sputn") | invokes `xsputn()` (public member function) | cpp std::basic_streambuf<CharT,Traits>::basic_streambuf std::basic\_streambuf<CharT,Traits>::basic\_streambuf ===================================================== | | | | | --- | --- | --- | | ``` protected: basic_streambuf(); ``` | (1) | | | ``` protected: basic_streambuf(const basic_streambuf& rhs); ``` | (2) | (since C++11) | 1) Constructs the `basic_streambuf` object, initializes the six pointer members (`eback()`, `gptr()`, `egptr()`, `pbase()`, `pptr()`, and `epptr()`) to null pointer values, and the locale member to `[std::locale](http://en.cppreference.com/w/cpp/locale/locale)()`, a copy of the global C++ locale at the time of construction. 2) Constructs a copy of `rhs`, initializing the six pointers and the locale object with the copies of the values held by `rhs`. Note that this is a shallow copy: the pointers of the newly-constructed basic\_streambuf are pointing into the same character array as the pointers of `rhs`. Both constructors are protected, and are only called by the concrete streambuf classes, such as `[std::basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf")`, `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`, or `[std::strstreambuf](../strstreambuf "cpp/io/strstreambuf")`. ### Parameters | | | | | --- | --- | --- | | rhs | - | a streambuf object to copy | ### Notes Until C++11, it was unspecified whether `basic_streambuf` or any of its derived classes is [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") ([LWG issue 421](https://cplusplus.github.io/LWG/issue421)), and different C++ library implementations provided different options. ### Example ### See also | | | | --- | --- | | [(constructor)](../basic_filebuf/basic_filebuf "cpp/io/basic filebuf/basic filebuf") | constructs a basic\_filebuf object (public member function of `std::basic_filebuf<CharT,Traits>`) | | [(constructor)](../basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [(constructor)](../strstreambuf/strstreambuf "cpp/io/strstreambuf/strstreambuf") | constructs a strstreambuf object (public member function of `std::strstreambuf`) | cpp std::basic_streambuf<CharT,Traits>::pubseekpos, std::basic_streambuf<CharT,Traits>::seekpos std::basic\_streambuf<CharT,Traits>::pubseekpos, std::basic\_streambuf<CharT,Traits>::seekpos ============================================================================================= | | | | | --- | --- | --- | | ``` pos_type pubseekpos( pos_type pos, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out ); ``` | (1) | | | ``` protected: virtual pos_type seekpos( pos_type pos, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out); ``` | (2) | | Sets the position indicator of the input and/or output sequence to an absolute position. 1) Calls `seekpos(pos, which)` of the most derived class. 2) The base class version of this function has no effect. The derived classes may override this function to allow absolute positioning of the position indicator. ### Parameters | | | | | --- | --- | --- | | pos | - | absolute position to set the position indicator to. | | which | - | defines which of the input and/or output sequences to affect. It can be one or a combination of the following constants: | Constant | Explanation | | --- | --- | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the input sequence | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | affect the output sequence | | ### Return value 1) The return value of `seekpos(pos, which)` 2) The resulting absolute position as defined by the position indicator. The base class version returns `pos_type(off_type(-1))`. ### 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 55](https://cplusplus.github.io/LWG/issue55) | C++98 | the base class version of `seekpos` returnedan undefined invalid stream position | returns `pos_type(off_type(-1))` | ### See also | | | | --- | --- | | [pubseekoff](pubseekoff "cpp/io/basic streambuf/pubseekoff") | invokes `seekoff()` (public member function) | | [seekpos](../basic_filebuf/seekpos "cpp/io/basic filebuf/seekpos") [virtual] | repositions the file position, using absolute addressing (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [seekpos](../basic_stringbuf/seekpos "cpp/io/basic stringbuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [seekpos](../strstreambuf/seekpos "cpp/io/strstreambuf/seekpos") [virtual] | repositions the next pointer in the input sequence, output sequence, or both using absolute addressing (virtual protected member function of `std::strstreambuf`) | cpp std::basic_streambuf<CharT,Traits>::eback, gptr, egptr std::basic\_streambuf<CharT,Traits>::eback, gptr, egptr ======================================================= | | | | | --- | --- | --- | | ``` char_type* eback() const; ``` | (1) | | | ``` char_type* gptr() const; ``` | (2) | | | ``` char_type* egptr() const; ``` | (3) | | Returns pointers defining the get area. 1) Returns the pointer to the beginning of the get area. 2) Returns the pointer to the current character (*get pointer*) in the get area. 3) Returns the pointer one past the end of the get area. ### Parameters (none). ### Return value 1) The pointer to the beginning of the get area. 2) The pointer to the current character (*get pointer*) in the get area. 3) The pointer one past the end of the get area. ### Notes While the names "gptr" and "egptr" refer to the get area, the name "eback" refers to the end of the putback area: stepping backwards from gptr, characters can be put back until eback. ### Example ### See also | | | | --- | --- | | [pbasepptrepptr](pptr "cpp/io/basic streambuf/pptr") | returns a pointer to the beginning, current character and the end of the put area (protected member function) | cpp std::basic_streambuf<CharT,Traits>::pubsetbuf, std::basic_streambuf<CharT,Traits>::setbuf std::basic\_streambuf<CharT,Traits>::pubsetbuf, std::basic\_streambuf<CharT,Traits>::setbuf =========================================================================================== | | | | | --- | --- | --- | | ``` basic_streambuf<CharT, Traits>* pubsetbuf( char_type* s, std::streamsize n ) ``` | (1) | | | ``` protected: virtual basic_streambuf<CharT, Traits>* setbuf( char_type* s, std::streamsize n ) ``` | (2) | | 1) Calls `setbuf(s, n)` of the most derived class 2) The base class version of this function has no effect. The derived classes may override this function to allow removal or replacement of the controlled character sequence (the buffer) with a user-provided array, or for any other implementation-specific purpose. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the first CharT in the user-provided buffer | | n | - | the number of CharT elements in the user-provided buffer | ### Return value 1) The return value of `setbuf(s, n)` 2) `this` ### Example provide a 10k buffer for reading. On linux, the strace utility may be used to observe the actual number of bytes read. ``` #include <fstream> #include <iostream> #include <string> int main() { int cnt = 0; std::ifstream file; char buf[1024*10 + 1]; file.rdbuf()->pubsetbuf(buf, sizeof buf); file.open("/usr/share/dict/words"); for (std::string line; getline(file, line);) { cnt++; } std::cout << cnt << '\n'; } ``` ### See also | | | | --- | --- | | [setbuf](../basic_stringbuf/setbuf "cpp/io/basic stringbuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [setbuf](../basic_filebuf/setbuf "cpp/io/basic filebuf/setbuf") [virtual] | provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [setbuf](../strstreambuf/setbuf "cpp/io/strstreambuf/setbuf") [virtual] | attempts to replace the controlled character sequence with an array (virtual protected member function of `std::strstreambuf`) | | [setbuf](../c/setbuf "cpp/io/c/setbuf") | sets the buffer for a file stream (function) | cpp std::basic_streambuf<CharT,Traits>::overflow std::basic\_streambuf<CharT,Traits>::overflow ============================================= | | | | | --- | --- | --- | | ``` protected: virtual int_type overflow( int_type ch = Traits::eof() ); ``` | | | Ensures that there is space at the [put area](../basic_streambuf "cpp/io/basic streambuf") for at least one character by saving some initial subsequence of characters starting at `[pbase()](pptr "cpp/io/basic streambuf/pptr")` to the output sequence and updating the pointers to the put area (if needed). If `ch` is not `Traits::eof()` (i.e. `Traits::eq_int_type(ch, Traits::eof()) != true`), it is either put to the put area or directly saved to the output sequence. The function may update `pptr`, `epptr` and `pbase` pointers to define the location to write more data. On failure, the function ensures that either `pptr() == nullptr` or `pptr() == epptr`. The base class version of the function does nothing. The derived classes may override this function to allow updates to the put area in the case of exhaustion. ### Parameters | | | | | --- | --- | --- | | ch | - | the character to store in the put area | ### Return value Returns unspecified value not equal to `Traits::eof()` on success, `Traits::eof()` on failure. The base class version of the function returns `Traits::eof()`. ### Note The `[sputc()](sputc "cpp/io/basic streambuf/sputc")` and `[sputn()](sputn "cpp/io/basic streambuf/sputn")` call this function in case of an overflow (`pptr() == nullptr` or `pptr() >= epptr()`). ### Example ``` #include <iostream> #include <array> // Buffer for std::ostream implemented by std::array template<std::size_t SIZE, class CharT = char> class ArrayedStreamBuffer : public std::basic_streambuf<CharT> { public: using Base = std::basic_streambuf<CharT>; using char_type = typename Base::char_type; using int_type = typename Base::int_type; ArrayedStreamBuffer() : buffer_{} // value-initialize buffer_ to all zeroes { Base::setp(buffer_.begin(), buffer_.end()); // set std::basic_streambuf // put area pointers to work with 'buffer_' } int_type overflow(int_type ch) { std::cout << "overflow\n"; return Base::overflow(ch); } void print_buffer() { for (const auto& i: buffer_) { if (i == 0) { std::cout << "\\0"; } else { std::cout << i; } std::cout << ' '; } std::cout << '\n'; } private: std::array<char_type, SIZE> buffer_; }; int main() { ArrayedStreamBuffer<10> streambuf; std::ostream stream(&streambuf); stream << "hello"; streambuf.print_buffer(); if (stream.good()) { std::cout << "stream is good\n"; } stream << "world"; streambuf.print_buffer(); if (stream.good()) { std::cout << "stream is good\n"; } stream << "!"; streambuf.print_buffer(); if (!stream.good()) { std::cout << "stream is not good\n"; } } ``` Output: ``` h e l l o \0 \0 \0 \0 \0 stream is good h e l l o w o r l d stream is good overflow h e l l o w o r l d stream is not good ``` ### See also | | | | --- | --- | | [uflow](uflow "cpp/io/basic streambuf/uflow") [virtual] | reads characters from the associated input sequence to the get area and advances the next pointer (virtual protected member function) | | [underflow](underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function) | | [overflow](../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>`) | | [overflow](../basic_stringbuf/overflow "cpp/io/basic stringbuf/overflow") [virtual] | appends a character to the output sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [overflow](../strstreambuf/overflow "cpp/io/strstreambuf/overflow") [virtual] | appends a character to the output sequence, may reallocate or initially allocate the buffer if dynamic and not frozen (virtual protected member function of `std::strstreambuf`) | cpp std::basic_streambuf<CharT,Traits>::sungetc std::basic\_streambuf<CharT,Traits>::sungetc ============================================ | | | | | --- | --- | --- | | ``` int_type sungetc(); ``` | | | If a putback position is available in the get area (`gptr() > eback()`), then decrements the next pointer (`[gptr()](gptr "cpp/io/basic streambuf/gptr")`) and returns the character it now points to. If a putback position is not available, then calls `[pbackfail()](pbackfail "cpp/io/basic streambuf/pbackfail")` to back up the input sequence if possible. The I/O stream function [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") is implemented in terms of this function. ### Parameters (none). ### Return value If putback position was available, returns the character that the next pointer is now pointing at, converted to `int_type` with `Traits::to_int_type(*gptr())`. The next single-character input from this streambuf will return this character. If putback position was not available, returns what `[pbackfail()](pbackfail "cpp/io/basic streambuf/pbackfail")` returns, which is `Traits::eof()` on failure. ### Example ``` #include <iostream> #include <sstream> int main() { std::stringstream s("abcdef"); // gptr() points to 'a' char c1 = s.get(); // c = 'a', gptr() now points to 'b' char c2 = s.rdbuf()->sungetc(); // same as s.unget(): gptr() points to 'a' again char c3 = s.get(); // c3 = 'a', gptr() now points to 'b' char c4 = s.get(); // c4 = 'b', gptr() now points to 'c' std::cout << c1 << c2 << c3 << c4 << '\n'; s.rdbuf()->sungetc(); // back to 'b' s.rdbuf()->sungetc(); // back to 'a' int eof = s.rdbuf()->sungetc(); // nothing to unget: pbackfail() fails if (eof == EOF) std::cout << "Nothing to unget after 'a'\n"; } ``` Output: ``` aaab Nothing to unget after 'a' ``` ### See also | | | | --- | --- | | [sputbackc](sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function) | | [unget](../basic_istream/unget "cpp/io/basic istream/unget") | unextracts a character (public member function of `std::basic_istream<CharT,Traits>`) |
programming_docs
cpp std::basic_streambuf<CharT,Traits>::in_avail std::basic\_streambuf<CharT,Traits>::in\_avail ============================================== | | | | | --- | --- | --- | | ``` std::streamsize in_avail(); ``` | | | Returns the number of characters available in the get area. If a read position is available, effectively returns `egptr() - gptr()`, the size of the get area. In this case, the number of bytes returned is the number of bytes that can be extracted from the buffer without calling `[underflow()](underflow "cpp/io/basic streambuf/underflow")`. If the get area is empty, calls `[showmanyc()](showmanyc "cpp/io/basic streambuf/showmanyc")` to determine the number of bytes available in the associated character sequence. In this case, the value returned is the number of bytes that can be extracted from the buffer while it's guaranteed that `[underflow()](underflow "cpp/io/basic streambuf/underflow")` would not return `Traits::eof`. ### Parameters (none). ### Return value The number of characters available for non-blocking read (either the size of the get area or the number of characters ready for reading from the associated character sequence), or `-1` if no characters are available in the associated sequence as far as `[showmanyc()](showmanyc "cpp/io/basic streambuf/showmanyc")` can tell. ### Example ### See also | | | | --- | --- | | [showmanyc](../basic_filebuf/showmanyc "cpp/io/basic filebuf/showmanyc") [virtual] | optionally provides the number of characters available for input from the file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [readsome](../basic_istream/readsome "cpp/io/basic istream/readsome") | extracts already available blocks of characters (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_streambuf<CharT,Traits>::operator= std::basic\_streambuf<CharT,Traits>::operator= ============================================== | | | | | --- | --- | --- | | ``` basic_streambuf& operator=( const basic_streambuf& other ); ``` | | (since C++11) | Assigns the data members of `other` to `*this`. ### Parameters | | | | | --- | --- | --- | | other | - | stream buffer to assign | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example cpp std::basic_streambuf<CharT,Traits>::pubimbue, std::basic_streambuf<CharT,Traits>::imbue std::basic\_streambuf<CharT,Traits>::pubimbue, std::basic\_streambuf<CharT,Traits>::imbue ========================================================================================= | | | | | --- | --- | --- | | ``` std::locale pubimbue( const std::locale& loc ); ``` | (1) | | | ``` protected: virtual void imbue( const std::locale& loc ); ``` | (2) | | Changes the associated locale. 1) Sets `loc` as the associated locale. Calls `imbue(loc)` of the most derived class. 2) The base class version of this function has no effect. The derived classes may override this function in order to be informed about the changes of the locale. The derived class may cache the locale and member facets between calls to `imbue()`. ### Parameters | | | | | --- | --- | --- | | loc | - | locale object to associate | ### Return value 1) Previous associated locale. ### Example ### See also | | | | --- | --- | | [getloc](getloc "cpp/io/basic streambuf/getloc") | obtains a copy of the associated locale (public member function) | cpp std::basic_streambuf<CharT,Traits>::gbump std::basic\_streambuf<CharT,Traits>::gbump ========================================== | | | | | --- | --- | --- | | ``` protected: void gbump( int count ); ``` | | | Skips `count` characters in the get area. This is done by adding `count` to the *get pointer*. No checks are done for underflow. ### Parameters | | | | | --- | --- | --- | | count | - | number of characters to skip | ### Return value (none). ### Notes Because this function takes an `int`, it cannot manipulate buffers larger than `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<int>::max()` characters ([LWG 255](http://wg21.link/lwg255)). ### 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 59](https://cplusplus.github.io/LWG/issue59) | C++98 | it was unclear whether `gbump` can be implemented ascalling [`sbumpc`](sbumpc "cpp/io/basic streambuf/sbumpc") `count` times (which may check underflow) | only add `count`to the get pointer | ### See also | | | | --- | --- | | [pbump](pbump "cpp/io/basic streambuf/pbump") | advances the next pointer of the output sequence (protected member function) | cpp std::basic_streambuf<CharT,Traits>::sputbackc std::basic\_streambuf<CharT,Traits>::sputbackc ============================================== | | | | | --- | --- | --- | | ``` int_type sputbackc( char_type c ); ``` | | | Puts back a character back to the get area. If a putback position is available in the get area (`gptr() > eback()`), and the character `c` is equal to the character one position to the left of `[gptr()](gptr "cpp/io/basic streambuf/gptr")` (as determined by `Traits::eq(c, gptr()[-1])`, then simply decrements the next pointer (`[gptr()](gptr "cpp/io/basic streambuf/gptr")`). Otherwise, calls `pbackfail(Traits::to_int_type(c))` to either back up the get area or to modify both the get area and possibly the associated character sequence. The I/O stream function [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback") is implemented in terms of this function. ### Parameters | | | | | --- | --- | --- | | c | - | character to put back | ### Return value If putback position was available, returns the character that the next pointer is now pointing at, converted to `int_type` with `Traits::to_int_type(*gptr())`. The next single-character input from this streambuf will return this character. If putback position was not available, returns what `[pbackfail()](pbackfail "cpp/io/basic streambuf/pbackfail")` returns, which is `Traits::eof()` on failure. ### Example ``` #include <iostream> #include <sstream> int main() { std::stringstream s("abcdef"); // gptr() points to 'a' in "abcdef" std::cout << "Before putback, string holds " << s.str() << '\n'; char c1 = s.get(); // c1 = 'a', gptr() now points to 'b' in "abcdef" char c2 = s.rdbuf()->sputbackc('z'); // same as s.putback('z') // gptr() now points to 'z' in "zbcdef" std::cout << "After putback, string holds " << s.str() << '\n'; char c3 = s.get(); // c3 = 'z', gptr() now points to 'b' in "zbcdef" char c4 = s.get(); // c4 = 'b', gptr() now points to 'c' in "zbcdef" std::cout << c1 << c2 << c3 << c4 << '\n'; s.rdbuf()->sputbackc('b'); // gptr() now points to 'b' in "zbcdef" s.rdbuf()->sputbackc('z'); // gptr() now points to 'z' in "zbcdef" int eof = s.rdbuf()->sputbackc('x'); // nothing to unget: pbackfail() fails if (eof == EOF) std::cout << "No room to putback after 'z'\n"; } ``` Output: ``` Before putback, string holds abcdef After putback, string holds zbcdef azzb No room to putback after 'z' ``` ### See also | | | | --- | --- | | [sungetc](sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function) | | [putback](../basic_istream/putback "cpp/io/basic istream/putback") | puts character into input stream (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_streambuf<CharT,Traits>::snextc std::basic\_streambuf<CharT,Traits>::snextc =========================================== | | | | | --- | --- | --- | | ``` int_type snextc(); ``` | | | Advances the input sequence by one character and reads one character. The function calls `[sbumpc()](sbumpc "cpp/io/basic streambuf/sbumpc")` to advance the input sequence. If that function returns `Traits::eof()` meaning that input sequence has been exhausted and `[uflow()](uflow "cpp/io/basic streambuf/uflow")` could not retrieve more data, `Traits::eof()` is returned. Otherwise `[sgetc()](sgetc "cpp/io/basic streambuf/sgetc")` is called in order to read the character. ### Parameters (none). ### Return value The value of the next character. If the input sequence has been exhausted, `Traits::eof()` is returned. ### Example ### See also | | | | --- | --- | | [sgetc](sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function) | | [sbumpcstossc](sbumpc "cpp/io/basic streambuf/sbumpc") (removed in C++17) | reads one character from the input sequence and advances the sequence (public member function) | cpp std::basic_streambuf<CharT,Traits>::showmanyc std::basic\_streambuf<CharT,Traits>::showmanyc ============================================== | | | | | --- | --- | --- | | ``` protected: virtual std::streamsize showmanyc(); ``` | | | Estimates the number of characters available for input in the associated character sequence. `[underflow()](underflow "cpp/io/basic streambuf/underflow")` is guaranteed not to return `Traits::eof()` or throw an exception until at least that many characters are extracted. ### Parameters (none). ### Return value The number of characters that are certainly available in the associated character sequence, or `-1` if `showmanyc` can determine, without blocking, that no characters are available. If `showmanyc` returns `-1`, `[underflow()](underflow "cpp/io/basic streambuf/underflow")` and `[uflow()](uflow "cpp/io/basic streambuf/uflow")` will definitely return `Traits::eof` or throw. The base class version returns `​0​`, which has the meaning of "unsure if there are characters available in the associated sequence". ### Notes The name of this function stands for "stream: how many characters?", so it is pronounced "S how many C", rather than "show many C" ### Example ### See also | | | | --- | --- | | [in\_avail](in_avail "cpp/io/basic streambuf/in avail") | obtains the number of characters immediately available in the get area (public member function) | | [showmanyc](../basic_filebuf/showmanyc "cpp/io/basic filebuf/showmanyc") [virtual] | optionally provides the number of characters available for input from the file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | cpp std::basic_streambuf<CharT,Traits>::uflow std::basic\_streambuf<CharT,Traits>::uflow ========================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type uflow(); ``` | | | Ensures that at least one character is available in the input area by updating the pointers to the input area (if needed). On success returns the value of that character and advances the value of the *get pointer* by one character. On failure returns `traits::eof()`. The function may update `gptr`, `egptr` and `eback` pointers to define the location of newly loaded data (if any). On failure, the function ensures that either `gptr() == nullptr` or `gptr() == egptr`. The base class version of the function calls `[underflow()](underflow "cpp/io/basic streambuf/underflow")` and increments `[gptr()](gptr "cpp/io/basic streambuf/gptr")`. ### Parameters (none). ### Return value The value of the character that was pointed to by the *get pointer* before it was advanced by one, or `traits::eof()` otherwise. The base class version of the function returns the value returned by `[underflow()](underflow "cpp/io/basic streambuf/underflow")`. ### Note The public functions of `[std::streambuf](../basic_streambuf "cpp/io/basic streambuf")` call this function only if `gptr() == nullptr` or `gptr() >= egptr()`. The custom streambuf classes that do not use the get area and do not set the get area pointers in basic\_streambuf are required to override this function. ### Example ### See also | | | | --- | --- | | [underflow](underflow "cpp/io/basic streambuf/underflow") [virtual] | reads characters from the associated input sequence to the get area (virtual protected member function) | | [overflow](overflow "cpp/io/basic streambuf/overflow") [virtual] | writes characters to the associated output sequence from the put area (virtual protected member function) | cpp std::basic_streambuf<CharT,Traits>::sbumpc, std::basic_streambuf<CharT,Traits>::stossc std::basic\_streambuf<CharT,Traits>::sbumpc, std::basic\_streambuf<CharT,Traits>::stossc ======================================================================================== | | | | | --- | --- | --- | | ``` int_type sbumpc(); ``` | (1) | | | ``` void stossc(); ``` | (2) | (deprecated in C++98) (removed in C++17) | Reads one character and advances the input sequence by one character. 1) If the input sequence read position is not available, returns `[uflow()](uflow "cpp/io/basic streambuf/uflow")`. Otherwise returns `Traits::to_int_type(*gptr())`. 2) Same as (1), but discards the result. ### Parameters (none). ### Return value 1) The value of the character pointed to by the *get pointer*, or `Traits::eof()` if the read position is not available. ### Example ### See also | | | | --- | --- | | [sgetc](sgetc "cpp/io/basic streambuf/sgetc") | reads one character from the input sequence without advancing the sequence (public member function) | | [snextc](snextc "cpp/io/basic streambuf/snextc") | advances the input sequence, then reads one character without advancing again (public member function) | cpp std::basic_streambuf<CharT,Traits>::setp std::basic\_streambuf<CharT,Traits>::setp ========================================= | | | | | --- | --- | --- | | ``` protected: void setp( char_type* pbeg, char_type* pend ); ``` | | | Sets the values of the pointers defining the put area. Specifically, after the call `pbase() == pbeg`, `pptr() == pbeg`, `epptr() == pend`. ### Parameters | | | | | --- | --- | --- | | pbeg | - | pointer to the new beginning of the put area | | pend | - | pointer to the new end of the put area | ### Return value (none). ### Example ``` #include <iostream> #include <array> // Buffer for std::ostream implemented by std::array template<std::size_t SIZE, class CharT = char> class ArrayedStreamBuffer : public std::basic_streambuf<CharT> { public: using Base = std::basic_streambuf<CharT>; using char_type = typename Base::char_type; ArrayedStreamBuffer() : buffer_{} // value-initialize buffer_ to all zeroes { Base::setp(buffer_.begin(), buffer_.end()); // set std::basic_streambuf // put area pointers to work with 'buffer_' } void print_buffer() { for (const auto& i: buffer_) { if (i == 0) { std::cout << "\\0"; } else { std::cout << i; } std::cout << ' '; } std::cout << '\n'; } private: std::array<char_type, SIZE> buffer_; }; int main() { ArrayedStreamBuffer<10> streambuf; std::ostream stream(&streambuf); stream << "hello"; stream << ","; streambuf.print_buffer(); } ``` Output: ``` h e l l o , \0 \0 \0 \0 ``` ### See also | | | | --- | --- | | [setg](setg "cpp/io/basic streambuf/setg") | repositions the beginning, next, and end pointers of the input sequence (protected member function) | cpp std::basic_streambuf<CharT,Traits>::~basic_streambuf std::basic\_streambuf<CharT,Traits>::~basic\_streambuf ====================================================== | | | | | --- | --- | --- | | ``` virtual ~basic_streambuf(); ``` | | | This destructor has no effect: the members of this `basic_streambuf` (the pointers and the locale) are destructed in accordance with the usual object destruction sequence after this destructor returns. However, since it is declared public virtual, it allows the objects that are derived from `std::basic_streambuf` to be deleted through a pointer to base class. ### Parameters (none). ### Example ``` #include <iostream> #include <fstream> int main() { std::filebuf* fbp = new std::filebuf; fbp->open("test.txt", std::ios_base::out); fbp->sputn("Hello\n", 6); std::streambuf* sbp = fbp; delete sbp; // the file is closed, output flushed and written std::ifstream f("test.txt"); std::cout << f.rdbuf(); // proof } ``` Output: ``` Hello ``` ### 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 54](https://cplusplus.github.io/LWG/issue54) | C++98 | the effect of the destructor was not specified | specified as no effect | ### See also | | | | --- | --- | | [(constructor)](basic_streambuf "cpp/io/basic streambuf/basic streambuf") | constructs a basic\_streambuf object (protected member function) | cpp std::basic_streambuf<CharT,Traits>::pbase, std::basic_streambuf<CharT,Traits>::pptr, std::basic_streambuf<CharT,Traits>::epptr std::basic\_streambuf<CharT,Traits>::pbase, std::basic\_streambuf<CharT,Traits>::pptr, std::basic\_streambuf<CharT,Traits>::epptr ================================================================================================================================= | | | | | --- | --- | --- | | ``` char_type* pbase() const; ``` | (1) | | | ``` char_type* pptr() const; ``` | (2) | | | ``` char_type* epptr() const; ``` | (3) | | Returns pointers defining the put area. 1) Returns the pointer to the beginning ("base") of the put area. 2) Returns the pointer to the current character (*put pointer*) in the put area. 3) Returns the pointer one past the end of the put area. ### Parameters (none). ### Return value 1) The pointer to the beginning of the put area. 2) The pointer to the current character (*put pointer*) in the put area. 3) The pointer one past the end of the put area. ### Example ### See also | | | | --- | --- | | [ebackgptregptr](gptr "cpp/io/basic streambuf/gptr") | returns a pointer to the beginning, current character and the end of the get area (protected member function) | cpp std::basic_streambuf<CharT,Traits>::pbackfail std::basic\_streambuf<CharT,Traits>::pbackfail ============================================== | | | | | --- | --- | --- | | ``` protected: virtual int_type pbackfail( int_type c = Traits::eof() ); ``` | | | This function can only be called if any of the following condition is satisfied: * `gptr()` is [null](../../language/pointer#Null_pointers "cpp/language/pointer"), * `gptr() == eback()`, or * `traits::eq(traits::to_char_type(c), gptr()[-1])` returns `false`. This function is called by the public functions `[sungetc()](sungetc "cpp/io/basic streambuf/sungetc")` and `[sputbackc()](sputbackc "cpp/io/basic streambuf/sputbackc")` (which, in turn, are called by [`basic_istream::unget`](../basic_istream/unget "cpp/io/basic istream/unget") and [`basic_istream::putback`](../basic_istream/putback "cpp/io/basic istream/putback")) when either: 1) There is no putback position in the get area (`pbackfail()` is called with no arguments). In this situation, the purpose of `pbackfail()` is to back up the get area by one character, if the associated character sequence allows this (e.g. a file-backed streambuf may reload the buffer from a file, starting one character earlier). 2) The caller attempts to putback a different character from the one retrieved earlier (`pbackfail()` is called with the character that needs to be put back). In this situation, the purpose of `pbackfail()` is to place the character `c` into the get area at the position just before [`basic_streambuf::gptr()`](gptr "cpp/io/basic streambuf/gptr"), and, if possible, to modify the associated character sequence to reflect this change. This may involve backing up the get area as in the first variant. The default base class version of this function does nothing and returns `Traits::eof()` in all situations. This function is overridden by the derived classes: [`basic_stringbuf::pbackfail`](../basic_stringbuf/pbackfail "cpp/io/basic stringbuf/pbackfail"), [`basic_filebuf::pbackfail`](../basic_filebuf/pbackfail "cpp/io/basic filebuf/pbackfail"), [`strstreambuf::pbackfail`](../strstreambuf/pbackfail "cpp/io/strstreambuf/pbackfail"), and is expected to be overridden by user-defined and third-party library stream classes. ### Parameters | | | | | --- | --- | --- | | ch | - | character to put back or `Traits::eof()` if only back out is requested | ### Return value `Traits::eof()` in case of failure, some other value to indicate success. The base class version always fails. ### 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 32](https://cplusplus.github.io/LWG/issue32) | C++98 | the calling condition '`traits::eq(*gptr(),traits::to_char_type(c))`returns `false`' did not match the description of `[sputbackc()](sputbackc "cpp/io/basic streambuf/sputbackc")` | corrected to matchthe description | ### See also | | | | --- | --- | | [pbackfail](../basic_filebuf/pbackfail "cpp/io/basic filebuf/pbackfail") [virtual] | backs out the input sequence to unget a character, not affecting the associated file (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [pbackfail](../basic_stringbuf/pbackfail "cpp/io/basic stringbuf/pbackfail") [virtual] | puts a character back into the input sequence (virtual protected member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [pbackfail](../strstreambuf/pbackfail "cpp/io/strstreambuf/pbackfail") [virtual] | backs out the input sequence to unget a character (virtual protected member function of `std::strstreambuf`) | | [sungetc](sungetc "cpp/io/basic streambuf/sungetc") | moves the next pointer in the input sequence back by one (public member function) | | [sputbackc](sputbackc "cpp/io/basic streambuf/sputbackc") | puts one character back in the input sequence (public member function) |
programming_docs
cpp std::basic_istringstream::rdbuf std::basic\_istringstream::rdbuf ================================ | | | | | --- | --- | --- | | ``` std::basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; ``` | | | Returns pointer to the underlying raw string device object. ### Parameters (none). ### Return value Pointer to the underlying raw string device. ### Example cpp std::basic_istringstream::swap std::basic\_istringstream::swap =============================== | | | | | --- | --- | --- | | ``` void swap( basic_istringstream& other ); ``` | | (since C++11) | Exchanges the state of the stream with those of `other`. This is done by calling `basic_istream<CharT, Traits>::swap(other)` and `rdbuf()->swap(*other.rdbuf())`. ### Parameters | | | | | --- | --- | --- | | other | - | stream to exchange the state with | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/io/basic istringstream/operator=") (C++11) | moves the string stream (public member function) | | [swap](../basic_stringbuf/swap "cpp/io/basic stringbuf/swap") (C++11) | swaps two basic\_stringbuf objects (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_istringstream<CharT,Traits,Allocator>::str std::basic\_istringstream<CharT,Traits,Allocator>::str ====================================================== | | | | | --- | --- | --- | | | (1) | | | ``` std::basic_string<CharT,Traits,Allocator> str() const; ``` | (until C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() const&; ``` | (since C++20) | | ``` template<class SAlloc> std::basic_string<CharT,Traits,SAlloc> str( const SAlloc& a ) const; ``` | (2) | (since C++20) | | ``` std::basic_string<CharT,Traits,Allocator> str() &&; ``` | (3) | (since C++20) | | ``` void str( const std::basic_string<CharT,Traits,Allocator>& s ); ``` | (4) | | | ``` template<class SAlloc> void str( const std::basic_string<CharT,Traits, SAlloc>& s ); ``` | (5) | (since C++20) | | ``` void str( std::basic_string<CharT,Traits,Allocator>&& s ); ``` | (6) | (since C++20) | Manages the contents of the underlying string object. 1) Returns a copy of the underlying string. Equivalent to `return rdbuf()->str();`. 2) Returns a copy of the underlying string, using `a` as allocator. Equivalent to `return rdbuf()->str(a);`. 3) Returns a string move-constructed from the underlying string. Equivalent to `return std::move(*rdbuf()).str();`. 4-5) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(s);`. 6) Replaces the contents of the underlying string. Equivalent to `rdbuf()->str(std::move(s));`. ### Parameters | | | | | --- | --- | --- | | s | - | new contents of the underlying string | | a | - | allocator used to construct the returned string | ### Return value 1-2) a copy of the underlying string object. 3) a string move-constructed from the underlying string object. 4-6) (none) ### Notes The copy of the underlying string returned by `str` is a temporary object that will be destructed at the end of the expression, so directly calling [`c_str()`](../../string/basic_string/c_str "cpp/string/basic string/c str") on the result of `str()` (for example in `auto *ptr = out.str().c_str();`) results in a dangling pointer. ### Example ``` #include <sstream> #include <iostream> int main() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstream out("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstream ate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; } ``` Output: ``` after reading the first int from "1 2", the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2", str() = "3 2" after writing the int '3' to append stream "1 2", str() = "1 23" ``` ### See also | | | | --- | --- | | [rdbuf](rdbuf "cpp/io/basic istringstream/rdbuf") | returns the underlying raw string device object (public member function) | | [str](../basic_stringbuf/str "cpp/io/basic stringbuf/str") | replaces or obtains a copy of the associated character string (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::swap(std::basic_istringstream) std::swap(std::basic\_istringstream) ==================================== | Defined in header `[<sstream>](../../header/sstream "cpp/header/sstream")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_istringstream<CharT,Traits,Alloc>& lhs, std::basic_istringstream<CharT,Traits,Alloc>& rhs ); ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_istringstream](http://en.cppreference.com/w/cpp/io/basic_istringstream)`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | streams whose state to swap | ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic istringstream/swap") (C++11) | swaps two string streams (public member function) | cpp std::basic_istringstream<CharT,Traits,Allocator>::view std::basic\_istringstream<CharT,Traits,Allocator>::view ======================================================= | | | | | --- | --- | --- | | ``` std::basic_string_view<CharT, Traits> view() const noexcept; ``` | | (since C++20) | Obtains a `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. Equivalent to `return rdbuf()->view();`. ### Parameters (none). ### Return value A `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")` over the underlying string object. ### Example ### See also | | | | --- | --- | | [view](../basic_stringbuf/view "cpp/io/basic stringbuf/view") (C++20) | obtains a view over the underlying character sequence (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::basic_istringstream::operator= std::basic\_istringstream::operator= ==================================== | | | | | --- | --- | --- | | ``` basic_istringstream& operator=( basic_istringstream&& other ); ``` | | (since C++11) | Move assigns the string stream `other` to `*this`, effectively move-assigning both the `[std::basic\_istream](../basic_istream "cpp/io/basic istream")` base class and the associated `[std::basic\_stringbuf](../basic_stringbuf "cpp/io/basic stringbuf")`. Note that the base class move assignment swaps all stream state variables (except for `rdbuf`) between `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | string stream to move from | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/io/basic istringstream/swap") (C++11) | swaps two string streams (public member function) | | [operator=](../basic_stringbuf/operator= "cpp/io/basic stringbuf/operator=") (C++11) | assigns a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | | [operator=](../basic_istream/operator= "cpp/io/basic istream/operator=") (C++11) | move-assigns from another `basic_istream` (protected member function) | cpp std::basic_istringstream<CharT,Traits,Allocator>::basic_istringstream std::basic\_istringstream<CharT,Traits,Allocator>::basic\_istringstream ======================================================================= | | | | | --- | --- | --- | | ``` basic_istringstream() : basic_istringstream(std::ios_base::in) { } ``` | (1) | (since C++11) | | | (2) | | | ``` explicit basic_istringstream( std::ios_base::openmode mode = std::ios_base::in ); ``` | (until C++11) | | ``` explicit basic_istringstream( std::ios_base::openmode mode ); ``` | (since C++11) | | ``` explicit basic_istringstream( const std::basic_string<CharT,Traits,Allocator>& str, std::ios_base::openmode mode = std::ios_base::in ); ``` | (3) | | | ``` basic_istringstream( basic_istringstream&& other ); ``` | (4) | (since C++11) | | ``` basic_istringstream( std::ios_base::openmode mode, const Allocator& a ); ``` | (5) | (since C++20) | | ``` explicit basic_istringstream( std::basic_string<CharT,Traits,Allocator>&& str, std::ios_base::openmode mode = std::ios_base::in ); ``` | (6) | (since C++20) | | ``` template<class SAlloc> basic_istringstream( const std::basic_string<CharT,Traits,SAlloc>& str, const Allocator& a ) : basic_istringstream(str, std::ios_base::in, a) { } ``` | (7) | (since C++20) | | ``` template<class SAlloc> basic_istringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode, const Allocator& a ); ``` | (8) | (since C++20) | | ``` template<class SAlloc> explicit basic_istringstream( const std::basic_string<CharT,Traits,SAlloc>& str, std::ios_base::openmode mode = std::ios_base::in ); ``` | (9) | (since C++20) | Constructs new string stream. 1) Default constructor. Constructs new underlying string device with the default open mode 2) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 3) Uses a copy of `str` as initial contents of the underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 4) Move constructor. Constructs the string stream with the state of `other` using move semantics. 5) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 6) Move-construct the contents of the underlying string device with `str`. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(std::move(str), mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. 7) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 8) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode), a)`. 9) Constructs new underlying string device. The underlying `basic_stringbuf` object is constructed as `basic_stringbuf<Char,Traits,Allocator>(str, mode | [std::ios\_base::in](http://en.cppreference.com/w/cpp/io/ios_base/openmode))`. ### Parameters | | | | | --- | --- | --- | | str | - | string to use as initial contents of the string stream | | a | - | allocator used for allocating the contents of the string stream | | mode | - | specifies stream open mode. It is bitmask type, the following constants are defined: | Constant | Explanation | | --- | --- | | [`app`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream before each write | | [`binary`](../ios_base/openmode "cpp/io/ios base/openmode") | open in [binary mode](../c/file#Binary_and_text_modes "cpp/io/c/FILE") | | [`in`](../ios_base/openmode "cpp/io/ios base/openmode") | open for reading | | [`out`](../ios_base/openmode "cpp/io/ios base/openmode") | open for writing | | [`trunc`](../ios_base/openmode "cpp/io/ios base/openmode") | discard the contents of the stream when opening | | [`ate`](../ios_base/openmode "cpp/io/ios base/openmode") | seek to the end of stream immediately after open | | | other | - | another string stream to use as source | ### Notes Construction of one-off `basic_istringstream` objects in a tight loop, such as when used for string conversion, may be significantly more costly than calling `[str](str "cpp/io/basic istringstream/str")` to reuse the same object. ### Example ``` #include <iostream> #include <sstream> int main() { // default constructor (input/output stream) std::stringstream buf1; buf1 << 7; int n = 0; buf1 >> n; std::cout << "buf1 = " << buf1.str() << " n = " << n << '\n'; // input stream std::istringstream inbuf("-10"); inbuf >> n; std::cout << "n = " << n << '\n'; // output stream in append mode (C++11) std::ostringstream buf2("test", std::ios_base::ate); buf2 << '1'; std::cout << buf2.str() << '\n'; } ``` Output: ``` buf1 = 7 n = 7 n = -10 test1 ``` ### 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 | ### See also | | | | --- | --- | | [str](str "cpp/io/basic istringstream/str") | gets or sets the contents of underlying string device object (public member function) | | [(constructor)](../basic_stringbuf/basic_stringbuf "cpp/io/basic stringbuf/basic stringbuf") | constructs a basic\_stringbuf object (public member function of `std::basic_stringbuf<CharT,Traits,Allocator>`) | cpp std::fseek std::fseek ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fseek( std::FILE* stream, long offset, int origin ); ``` | | | Sets the file position indicator for the file stream `stream`. If the `stream` is open in binary mode, the new position is exactly `offset` bytes measured from the beginning of the file if `origin` is `[SEEK\_SET](../c "cpp/io/c")`, from the current file position if `origin` is `[SEEK\_CUR](../c "cpp/io/c")`, and from the end of the file if `origin` is `[SEEK\_END](../c "cpp/io/c")`. Binary streams are not required to support `[SEEK\_END](../c "cpp/io/c")`, in particular if additional null bytes are output. If the `stream` is open in text mode, the only supported values for `offset` are zero (which works with any `origin`) and a value returned by an earlier call to `[std::ftell](ftell "cpp/io/c/ftell")` on a stream associated with the same file (which only works with `origin` of `[SEEK\_SET](../c "cpp/io/c")`). If the `stream` is wide-oriented, the restrictions of both text and binary streams apply (result of `[std::ftell](ftell "cpp/io/c/ftell")` is allowed with SEEK\_SET and zero offset is allowed from SEEK\_SET and SEEK\_CUR, but not SEEK\_END). In addition to changing the file position indicator, `fseek` undoes the effects of `[std::ungetc](ungetc "cpp/io/c/ungetc")` and clears the end-of-file status, if applicable. If a read or write error occurs, the error indicator for the stream (`[std::ferror](ferror "cpp/io/c/ferror")`) is set and the file position is unaffected. ### Parameters | | | | | --- | --- | --- | | stream | - | file stream to modify | | offset | - | number of characters to shift the position relative to origin | | origin | - | position to which `offset` is added. It can have one of the following values: `[SEEK\_SET](../c "cpp/io/c")`, `[SEEK\_CUR](../c "cpp/io/c")`, `[SEEK\_END](../c "cpp/io/c")` | ### Return value `​0​` upon success, nonzero value otherwise. ### Notes After seeking to a non-end position in a wide stream, the next call to any output function may render the remainder of the file undefined, e.g. by outputting a multibyte sequence of a different length. POSIX allows seeking beyond the existing end of file. If an output is performed after this seek, any read from the gap will return zero bytes. Where supported by the filesystem, this creates a *sparse file*. POSIX also requires that fseek first performs `fflush` if there are any unwritten data (but whether the shift state is restored is implementation-defined). The standard C++ file streams guarantee both flushing and unshifting: `[std::basic\_filebuf::seekoff](../basic_streambuf/pubseekoff "cpp/io/basic streambuf/pubseekoff")`. ### Example ``` #include <cstdio> #include <cstdint> #include <vector> #include <fstream> #include <cassert> int main() { std::ofstream("dummy.nfo") << "sample data\n"; std::FILE* fp = std::fopen("dummy.nfo", "rb"); assert(fp); std::fseek(fp, 0, SEEK_END); // seek to end std::size_t filesize = std::ftell(fp); std::fseek(fp, 0, SEEK_SET); // seek to start std::vector<uint8_t> buffer(filesize); std::fread(buffer.data(), sizeof(uint8_t), buffer.size(), fp); std::fclose(fp); std::printf("i've read %zi bytes\n", filesize); } ``` Output: ``` i've read 12 bytes ``` ### See also | | | | --- | --- | | [fsetpos](fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [fgetpos](fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [ftell](ftell "cpp/io/c/ftell") | returns the current file position indicator (function) | | [rewind](rewind "cpp/io/c/rewind") | moves the file position indicator to the beginning in a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fseek "c/io/fseek") for `fseek` | cpp std::wprintf, std::fwprintf, std::swprintf std::wprintf, std::fwprintf, std::swprintf ========================================== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int wprintf( const wchar_t* format, ... ); ``` | (1) | | | ``` int fwprintf( std::FILE* stream, const wchar_t* format, ... ); ``` | (2) | | | ``` int swprintf( wchar_t* buffer, std::size_t size, const wchar_t* format, ... ); ``` | (3) | | Loads the data from the given locations, converts them to wide string equivalents and writes the results to a variety of sinks. 1) Writes the results to `[stdout](std_streams "cpp/io/c/std streams")`. 2) Writes the results to a file stream `stream`. 3) Writes the results to a wide string `buffer`. At most `size-1` wide characters are written followed by null wide character. ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | buffer | - | pointer to a wide character string to write to | | size | - | up to `size - 1` characters may be written, plus the null terminator | | format | - | pointer to a null-terminated wide string specifying how to interpret the data | | ... | - | arguments specifying data to print. If any argument after [default conversions](../../language/variadic_arguments#Default_conversions "cpp/language/variadic arguments") is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by `format`, the behavior is undefined. If there are more arguments than required by `format`, the extraneous arguments are evaluated and ignored. | The **format** string consists of ordinary wide characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format: * introductory `%` character * (optional) one or more flags that modify the behavior of the conversion: + `-`: the result of the conversion is left-justified within the field (by default it is right-justified) + `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative) + *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present. + `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined. + `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present. * (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.) + (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*. + (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument) + conversion format specifier The following format specifiers are available: | ConversionSpecifier | Explanation | ExpectedArgument Type | | --- | --- | --- | | **LengthModifier****→** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | writes literal `%`. The full conversion specification must be `%%`. | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | writes a **single character**. The argument is first converted to `wchar_t` as if by calling `btowc`. If the **l** modifier is used, the `wint_t` argument is first converted to `wchar_t`. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A | | `s` | writes a **character string** The argument must be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state, which is converted to wide character array as if by a call to `mbrtowc` with zero-initialized conversion state. *Precision* specifies the maximum number of wide characters to be written. If *Precision* is not specified, writes every wide characters up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `d` `i` | converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `intmax_t` | signed `size_t` | `ptrdiff_t` | N/A | | `o` | converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `uintmax_t` | `size_t` | unsigned version of `ptrdiff_t` | N/A | | `x` `X` | converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A | | `u` | converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A | | `f` `F` | converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | `double` (C++11) | N/A | N/A | N/A | N/A | `long double` | | `e` `E` | converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `a` `A` (C++11). | converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `g` `G` | converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*. * otherwise, the conversion is with style `e` or `E` and precision *P − 1*. Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `n` | returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*. | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `intmax_t*` | signed `size_t*` | `ptrdiff_t*` | N/A | | `p` | writes an implementation defined character sequence defining a **pointer**. | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A | The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined. Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined. The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead. Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called. The correct conversion specifications for the fixed-width character types (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although `[PRIdMAX](../../types/integer "cpp/types/integer")`, `[PRIuMAX](../../types/integer "cpp/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc). The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions. There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call. If a conversion specification is invalid, the behavior is undefined. ### Return value 1,2) Number of wide characters written if successful or negative value if an error occurred. 3) Number of wide characters written (not counting the terminating null wide character) if successful or negative value if an encoding error occurred or if the number of characters to be generated was equal or greater than `size` (including when `size` is zero) ### Notes While narrow strings provide `[std::snprintf](fprintf "cpp/io/c/fprintf")`, which makes it possible to determine the required output buffer size, there is no equivalent for wide strings, and in order to determine the buffer size, the program may need to call `std::swprintf`, check the result value, and reallocate a larger buffer, trying again until successful. ### Example ``` #include <iostream> #include <locale> #include <clocale> #include <cwchar> int main() { char narrow_str[] = "z\u00df\u6c34\U0001f34c"; // or "zß水🍌" // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c"; wchar_t warr[29]; // the expected string is 28 characters plus 1 null terminator std::setlocale(LC_ALL, "en_US.utf8"); std::swprintf(warr, sizeof warr/sizeof *warr, L"Converted from UTF-8: '%s'", narrow_str); std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << warr << '\n'; } ``` Output: ``` Converted from UTF-8: 'zß水🍌' ``` ### See also | | | | --- | --- | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vwprintfvfwprintfvswprintf](vfwprintf "cpp/io/c/vfwprintf") | prints formatted wide character output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [fputws](fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fwprintf "c/io/fwprintf") for `wprintf, fwprintf, swprintf` |
programming_docs
cpp std::vprintf, std::vfprintf, std::vsprintf, std::vsnprintf std::vprintf, std::vfprintf, std::vsprintf, std::vsnprintf ========================================================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int vprintf( const char* format, va_list vlist ); ``` | (1) | | | ``` int vfprintf( std::FILE* stream, const char* format, va_list vlist ); ``` | (2) | | | ``` int vsprintf( char* buffer, const char* format, va_list vlist ); ``` | (3) | | | ``` int vsnprintf( char* buffer, std::size_t buf_size, const char* format, va_list vlist ); ``` | (4) | (since C++11) | Loads the data from the locations, defined by `vlist`, converts them to character string equivalents and writes the results to a variety of sinks. 1) Writes the results to `[stdout](std_streams "cpp/io/c/std streams")`. 2) Writes the results to a file stream `stream`. 3) Writes the results to a character string `buffer`. 4) Writes the results to a character string `buffer`. At most `buf_size-1` characters are written. The resulting character string will be terminated with a null character, unless `buf_size` is zero. If `buf_size` is zero, nothing is written and `buffer` may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned. ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | buffer | - | pointer to a character string to write to | | buf\_size | - | maximum number of characters to write | | format | - | pointer to a null-terminated character string specifying how to interpret the data | | vlist | - | variable argument list containing the data to print. | The **format** string consists of ordinary multibyte characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format: * introductory `%` character * (optional) one or more flags that modify the behavior of the conversion: + `-`: the result of the conversion is left-justified within the field (by default it is right-justified) + `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative) + *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present. + `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined. + `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present. * (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.) + (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*. + (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument) + conversion format specifier The following format specifiers are available: | ConversionSpecifier | Explanation | ExpectedArgument Type | | --- | --- | --- | | **LengthModifier****→** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | writes literal `%`. The full conversion specification must be `%%`. | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | writes a **single character**. The argument is first converted to `unsigned char`. If the **l** modifier is used, the argument is first converted to a character string as if by **%ls** with a `wchar_t[2]` argument. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A | | `s` | writes a **character string** The argument must be a pointer to the initial element of an array of characters. *Precision* specifies the maximum number of bytes to be written. If *Precision* is not specified, writes every byte up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`, which is converted to char array as if by a call to `wcrtomb` with zero-initialized conversion state. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `d` `i` | converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `intmax_t` | signed `size_t` | `ptrdiff_t` | N/A | | `o` | converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `uintmax_t` | `size_t` | unsigned version of `ptrdiff_t` | N/A | | `x` `X` | converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A | | `u` | converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A | | `f` `F` | converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | `double` (C++11) | N/A | N/A | N/A | N/A | `long double` | | `e` `E` | converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `a` `A` (C++11). | converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `g` `G` | converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*. * otherwise, the conversion is with style `e` or `E` and precision *P − 1*. Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `n` | returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*. | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `intmax_t*` | signed `size_t*` | `ptrdiff_t*` | N/A | | `p` | writes an implementation defined character sequence defining a **pointer**. | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A | The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined. Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined. The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead. Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called. The correct conversion specifications for the fixed-width character types (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although `[PRIdMAX](../../types/integer "cpp/types/integer")`, `[PRIuMAX](../../types/integer "cpp/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc). The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions. There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call. If a conversion specification is invalid, the behavior is undefined. ### Return value 1-3) Number of characters written if successful or negative value if an error occurred. 4) Number of characters written if successful or negative value if an error occurred. If the resulting string gets truncated due to `buf_size` limit, function returns the total number of characters (not including the terminating null-byte) which would have been written, if the limit was not imposed. ### Notes All these functions invoke `[va\_arg](../../utility/variadic/va_arg "cpp/utility/variadic/va arg")` at least once, the value of `arg` is indeterminate after the return. These functions do not invoke `[va\_end](../../utility/variadic/va_end "cpp/utility/variadic/va end")`, and it must be done by the caller. ### Example ``` #include <vector> #include <cstdio> #include <cstdarg> #include <ctime> void debug_log(const char *fmt, ...) { std::time_t t = std::time(nullptr); char time_buf[100]; std::strftime(time_buf, sizeof time_buf, "%D %T", std::gmtime(&t)); va_list args1; va_start(args1, fmt); va_list args2; va_copy(args2, args1); std::vector<char> buf(1+std::vsnprintf(nullptr, 0, fmt, args1)); va_end(args1); std::vsnprintf(buf.data(), buf.size(), fmt, args2); va_end(args2); std::printf("%s [debug]: %s\n", time_buf, buf.data()); } int main() { debug_log("Logging, %d, %d, %d", 1, 2, 3); } ``` Output: ``` 04/13/15 15:09:18 [debug]: Logging, 1, 2, 3 ``` ### See also | | | | --- | --- | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vscanfvfscanfvsscanf](vfscanf "cpp/io/c/vfscanf") (C++11)(C++11)(C++11) | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [vprint\_unicode](../vprint_unicode "cpp/io/vprint unicode") (C++23) | prints to Unicode capable `[stdout](std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_nonunicode](../vprint_nonunicode "cpp/io/vprint nonunicode") (C++23) | prints to `[stdout](std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [C documentation](https://en.cppreference.com/w/c/io/vfprintf "c/io/vfprintf") for `vprintf, vfprintf, vsprintf, vsnprintf` | cpp std::clearerr std::clearerr ============= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` void clearerr( std::FILE* stream ); ``` | | | Resets the error flags and the [`EOF`](../c#Macro_constants "cpp/io/c") indicator for the given file stream. ### Parameters | | | | | --- | --- | --- | | stream | - | the file to reset the error flags for | ### Return value (none). ### Example ``` #include <cassert> #include <cstdio> int main() { std::FILE* tmpf = std::tmpfile(); std::fputs("cppreference.com\n", tmpf); std::rewind(tmpf); for (int ch; (ch = std::fgetc(tmpf)) != EOF; std::putchar(ch)) { } assert(std::feof(tmpf)); // the loop is expected to terminate by EOF std::puts("End of file reached"); std::clearerr(tmpf); // clear EOF std::puts(std::feof(tmpf) ? "EOF indicator set" : "EOF indicator cleared"); } ``` Output: ``` cppreference.com End of file reached EOF indicator cleared ``` ### See also | | | | --- | --- | | [feof](feof "cpp/io/c/feof") | checks for the end-of-file (function) | | [perror](perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](std_streams "cpp/io/c/std streams")` (function) | | [ferror](ferror "cpp/io/c/ferror") | checks for a file error (function) | | [C documentation](https://en.cppreference.com/w/c/io/clearerr "c/io/clearerr") for `clearerr` | cpp std::tmpnam std::tmpnam =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` char* tmpnam( char* filename ); ``` | | | Creates a unique filename that does not name a currently existing file, and stores it in the character string pointed to by `filename`. The function is capable of generating up to `[TMP\_MAX](../c "cpp/io/c")` of unique filenames, but some or all of them may already be in use, and thus not suitable return values. `std::tmpnam` modifies static state and is not required to be thread-safe. ### Parameters | | | | | --- | --- | --- | | filename | - | pointer to the character array capable of holding at least `[L\_tmpnam](../c "cpp/io/c")` bytes, to be used as a result buffer. If a null pointer is passed, a pointer to an internal static buffer is returned. | ### Return value `filename` if `filename` was not a null pointer. Otherwise a pointer to an internal static buffer is returned. If no suitable filename can be generated, a null pointer is returned. ### Notes Although the names generated by `std::tmpnam` are difficult to guess, it is possible that a file with that name is created by another process between the moment `std::tmpnam` returns and the moment this program attempts to use the returned name to create a file. The standard function `[std::tmpfile](tmpfile "cpp/io/c/tmpfile")` and the POSIX function [`mkstemp`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html) do not have this problem (creating a unique directory using only the standard C library still requires the use of `tmpnam`). POSIX systems additionally define the similarly named function [`tempnam`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tempnam.html), which offers the choice of a directory (which defaults to the optionally defined macro [`P_tmpdir`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdio.h.html)). ### Example ``` #include <iostream> #include <cstdio> #include <string> int main() { std::string name1 = std::tmpnam(nullptr); std::cout << "temporary file name: " << name1 << '\n'; char name2[L_tmpnam]; if (std::tmpnam(name2)) { std::cout << "temporary file name: " << name2 << '\n'; } } ``` Possible output: ``` temporary file name: /tmp/fileDjwifs temporary file name: /tmp/fileEv2bfW ``` ### See also | | | | --- | --- | | [tmpfile](tmpfile "cpp/io/c/tmpfile") | creates and opens a temporary, auto-removing file (function) | | [temp\_directory\_path](../../filesystem/temp_directory_path "cpp/filesystem/temp directory path") (C++17) | returns a directory suitable for temporary files (function) | | [C documentation](https://en.cppreference.com/w/c/io/tmpnam "c/io/tmpnam") for `tmpnam` | cpp std::feof std::feof ========= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int feof( std::FILE* stream ); ``` | | | Checks if the end of the given file stream has been reached. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to check | ### Return value Nonzero value if the end of the stream has been reached, otherwise `​0​`. ### Notes This function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a `[std::fgetc](fgetc "cpp/io/c/fgetc")`, which returned the last byte of a file, `std::feof` returns zero. The next `[std::fgetc](fgetc "cpp/io/c/fgetc")` fails and changes the stream state to *end-of-file*. Only then `std::feof` returns non-zero. In typical usage, input stream processing stops on any error; `feof` and `[std::ferror](ferror "cpp/io/c/ferror")` are then used to distinguish between different error conditions. ### Example ``` #include <cstdio> #include <cstdlib> int main() { int is_ok = EXIT_FAILURE; FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("File opening failed"); return is_ok; } int c; // note: int, not char, required to handle EOF while ((c = std::fgetc(fp)) != EOF) { // standard C I/O file reading loop std::putchar(c); } if (std::ferror(fp)) { std::puts("I/O error when reading"); } else if (std::feof(fp)) { std::puts("End of file reached successfully"); is_ok = EXIT_SUCCESS; } std::fclose(fp); return is_ok; } ``` Output: ``` End of file reached successfully ``` ### See also | | | | --- | --- | | [eof](../basic_ios/eof "cpp/io/basic ios/eof") | checks if end-of-file has been reached (public member function of `std::basic_ios<CharT,Traits>`) | | [clearerr](clearerr "cpp/io/c/clearerr") | clears errors (function) | | [perror](perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](std_streams "cpp/io/c/std streams")` (function) | | [ferror](ferror "cpp/io/c/ferror") | checks for a file error (function) | | [C documentation](https://en.cppreference.com/w/c/io/feof "c/io/feof") for `feof` |
programming_docs
cpp std::gets std::gets ========= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` char* gets( char* str ); ``` | | (deprecated in C++11) (removed in C++14) | Reads `[stdin](std_streams "cpp/io/c/std streams")` into given character string until a newline character is found or end-of-file occurs. ### Parameters | | | | | --- | --- | --- | | str | - | character string to be written | ### Return value `str` on success, a null pointer on failure. If the failure has been caused by end of file condition, additionally sets the *eof* indicator (see `[std::feof()](feof "cpp/io/c/feof")`) on `[stdin](std_streams "cpp/io/c/std streams")`. If the failure has been caused by some other error, sets the *error* indicator (see `[std::ferror()](ferror "cpp/io/c/ferror")`) on `[stdin](std_streams "cpp/io/c/std streams")`. ### Notes The function provides no means to prevent buffer overflow of the destination array, given sufficiently long input string. `std::gets` was deprecated in C++11 and removed from C++14. `[std::fgets](fgets "cpp/io/c/fgets")` can be used instead. ### See also | | | | --- | --- | | [scanffscanfsscanf](fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [fgets](fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/gets "c/io/gets") for `gets` | cpp std::fgetwc std::fgetwc =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wint_t fgetwc( std::FILE* stream ); ``` | | | | ``` wint_t getwc( std::FILE* stream ); ``` | | | Reads the next wide character from the given input stream. `getwc()` may be implemented as a macro and may evaluate `stream` more than once. ### Parameters | | | | | --- | --- | --- | | stream | - | to read the wide character from | ### Return value The next wide character from the stream or `WEOF` if an error has occurred or the end of file has been reached. If an encoding error occurred, `[errno](../../error/errno "cpp/error/errno")` is set to `EILSEQ`. ### See also | | | | --- | --- | | [fgetcgetc](fgetc "cpp/io/c/fgetc") | gets a character from a file stream (function) | | [fgetws](fgetws "cpp/io/c/fgetws") | gets a wide string from a file stream (function) | | [fputwcputwc](fputwc "cpp/io/c/fputwc") | writes a wide character to a file stream (function) | | [ungetwc](ungetwc "cpp/io/c/ungetwc") | puts a wide character back into a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fgetwc "c/io/fgetwc") for `fgetwc` | cpp std::fopen std::fopen ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` std::FILE* fopen( const char* filename, const char* mode ); ``` | | | Opens a file indicated by `filename` and returns a file stream associated with that file. `mode` is used to determine the file access mode. ### Parameters | | | | | --- | --- | --- | | filename | - | file name to associate the file stream to | | mode | - | null-terminated character string determining [file access mode](#File_access_flags) | ### File access flags | File access mode string | Meaning | Explanation | Action if file already exists | Action if file does not exist | | --- | --- | --- | --- | --- | | `"r"` | read | Open a file for reading | read from start | return `[NULL](http://en.cppreference.com/w/cpp/types/NULL)` and set error | | `"w"` | write | Create a file for writing | destroy contents | create new | | `"a"` | append | Append to a file | write to end | create new | | `"r+"` | read extended | Open a file for read/write | read from start | return `[NULL](http://en.cppreference.com/w/cpp/types/NULL)` and set error | | `"w+"` | write extended | Create a file for read/write | destroy contents | create new | | `"a+"` | append extended | Open a file for read/write | write to end | create new | | File access mode flag `"b"` can optionally be specified to open a file [in binary mode](file#Binary_and_text_modes "cpp/io/c/FILE"). This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of `'\n'` and `'\x1A'`. On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator. | | File access mode flag `"x"` can optionally be appended to `"w"` or `"w+"` specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C++17) | | The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. [Windows](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen)). | ### Return value If successful, returns a pointer to the object that controls the opened file stream, with both eof and error bits cleared. The stream is fully buffered unless filename refers to an interactive device. On error, returns a null pointer. [POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html) that `[errno](../../error/errno "cpp/error/errno")` is set in this case. ### Notes The format of `filename` is implementation-defined, and does not necessarily refer to a file (e.g. it may be the console or another device accessible through filesystem API). On platforms that support them, `filename` may include absolute or relative filesystem path. For portable directory and file naming, see [C++ filesystem library](../../filesystem "cpp/filesystem") or [boost.filesystem](http://www.boost.org/doc/libs/release/libs/filesystem/doc/index.htm). ### Example ``` #include <cstdio> #include <cstdlib> int main() { int is_ok = EXIT_FAILURE; FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("File opening failed"); return is_ok; } int c; // note: int, not char, required to handle EOF while ((c = std::fgetc(fp)) != EOF) { // standard C I/O file reading loop std::putchar(c); } if (std::ferror(fp)) { std::puts("I/O error when reading"); } else if (std::feof(fp)) { std::puts("End of file reached successfully"); is_ok = EXIT_SUCCESS; } std::fclose(fp); return is_ok; } ``` Output: ``` End of file reached successfully ``` ### See also | | | | --- | --- | | [fclose](fclose "cpp/io/c/fclose") | closes a file (function) | | [fflush](fflush "cpp/io/c/fflush") | synchronizes an output stream with the actual file (function) | | [freopen](freopen "cpp/io/c/freopen") | open an existing stream with a different name (function) | | [C documentation](https://en.cppreference.com/w/c/io/fopen "c/io/fopen") for `fopen` | cpp std::fpos_t std::fpos\_t ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` typedef /* implementation-defined */ fpos_t; ``` | | | `std::fpos_t` is a non-array complete object type, can be used to store (by `[std::fgetpos](fgetpos "cpp/io/c/fgetpos")`) and restore (by `[std::fsetpos](fsetpos "cpp/io/c/fsetpos")`) the position and multibyte parser state (if any) for a C stream. The multibyte parser state of a wide-oriented C stream is represented by a `[std::mbstate\_t](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t")` object, whose value is stored as part of the value of a `std::fpos_t` object by `[std::fgetpos](fgetpos "cpp/io/c/fgetpos")`. ### See also | | | | --- | --- | | [fgetpos](fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [fsetpos](fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [mbstate\_t](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) | | [fpos](../fpos "cpp/io/fpos") | represents absolute position in a stream or a file (class template) | | [C documentation](https://en.cppreference.com/w/c/io/fpos_t "c/io/fpos t") for `fpos_t` | cpp std::puts std::puts ========= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int puts( const char *str ); ``` | | | Writes every character from the null-terminated string `str` and one additional newline character `'\n'` to the output stream `[stdout](std_streams "cpp/io/c/std streams")`, as if by repeatedly executing `[std::fputc](fputc "cpp/io/c/fputc")`. The terminating null character from `str` is not written. ### Parameters | | | | | --- | --- | --- | | str | - | character string to be written | ### Return value On success, returns a non-negative value. On failure, returns `[EOF](../c "cpp/io/c")` and sets the *error* indicator (see `[std::ferror](ferror "cpp/io/c/ferror")`) on `stdout`. ### Notes The `std::puts` function appends the newline character to the output, while `[std::fputs](fputs "cpp/io/c/fputs")` function does not. Different implementations return different non-negative numbers: some return the last character written, some return the number of characters written (or `INT_MAX` if the string was longer than that), some simply return a non-negative constant. A typical cause of failure for `std::puts` is running out of space on the file system, when `stdout` is redirected to a file. ### Example ``` #include <cstdio> int main() { int rc = std::puts("Hello World"); if (rc == EOF) std::perror("puts()"); // POSIX requires that errno is set } ``` Output: ``` Hello World ``` ### See also | | | | --- | --- | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [C documentation](https://en.cppreference.com/w/c/io/puts "c/io/puts") for `puts` | cpp std::fclose std::fclose =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fclose( std::FILE* stream ); ``` | | | Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded. Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by `[std::setbuf](setbuf "cpp/io/c/setbuf")` or `[std::setvbuf](setvbuf "cpp/io/c/setvbuf")`, if any, is also disassociated and deallocated if automatic allocation was used. The behavior is undefined if the value of the pointer `stream` is used after `fclose` returns. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to close | ### Return value `​0​` on success, `[EOF](../c "cpp/io/c")` otherwise. ### Example ``` #include <cstdio> #include <cstdlib> int main() { int is_ok = EXIT_FAILURE; FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("File opening failed"); return is_ok; } int c; // note: int, not char, required to handle EOF while ((c = std::fgetc(fp)) != EOF) { // standard C I/O file reading loop std::putchar(c); } if (std::ferror(fp)) { std::puts("I/O error when reading"); } else if (std::feof(fp)) { std::puts("End of file reached successfully"); is_ok = EXIT_SUCCESS; } std::fclose(fp); return is_ok; } ``` Output: ``` End of file reached successfully ``` ### See also | | | | --- | --- | | [fopen](fopen "cpp/io/c/fopen") | opens a file (function) | | [freopen](freopen "cpp/io/c/freopen") | open an existing stream with a different name (function) | | [close](../basic_filebuf/close "cpp/io/basic filebuf/close") | flushes the put area buffer and closes the associated file (public member function of `std::basic_filebuf<CharT,Traits>`) | | [C documentation](https://en.cppreference.com/w/c/io/fclose "c/io/fclose") for `fclose` | cpp std::wscanf, std::fwscanf, std::swscanf std::wscanf, std::fwscanf, std::swscanf ======================================= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int wscanf( const wchar_t* format, ... ); ``` | (1) | | | ``` int fwscanf( std::FILE* stream, const wchar_t* format, ... ); ``` | (2) | | | ``` int swscanf( const wchar_t* buffer, const wchar_t* format, ... ); ``` | (3) | | Reads data from the a variety of sources, interprets it according to `format` and stores the results into given locations. 1) Reads the data from `[stdin](std_streams "cpp/io/c/std streams")`. 2) Reads the data from file stream `stream`. 3) Reads the data from null-terminated wide string `buffer`. ### Parameters | | | | | --- | --- | --- | | stream | - | input file stream to read from | | buffer | - | pointer to a null-terminated wide string to read from | | format | - | pointer to a null-terminated wide string specifying how to read the input | | ... | - | receiving arguments. | The **format** string consists of. * non-whitespace wide characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. * whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`iswspace`](../../string/wide/iswspace "cpp/string/wide/iswspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string. * conversion specifications. Each conversion specification has the following format: + introductory `%` character + (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument. + (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided. + (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below). + conversion format specifier The following format specifiers are available: | Conversion specifier | Explanation | Argument type | | --- | --- | --- | | **Length modifier →** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* wide characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `s` | matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `[`set`]` | matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `d` | matches a **decimal integer**. The format of the number is the same as expected by [`wcstol`](../../string/wide/wcstol "cpp/string/wide/wcstol") with the value `10` for the `base` argument. | `signed char*` or `unsigned char*` | `signed short*` or `unsigned short*` | `signed int*` or `unsigned int*` | `signed long*` or `unsigned long*` | `signed long long*` or `unsigned long long*` | `intmax_t*` or `uintmax_t*` | `size_t*` | `ptrdiff_t*` | N/A | | `i` | matches an **integer**. The format of the number is the same as expected by [`wcstol`](../../string/wide/wcstol "cpp/string/wide/wcstol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). | | `u` | matches an unsigned **decimal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `10` for the `base` argument. | | `o` | matches an unsigned **octal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `8` for the `base` argument. | | `x`, `X` | matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `16` for the `base` argument. | | `n` | returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. | | `a`, `A`(C++11) `e`, `E` `f`, `F` `g`, `G` | matches a **floating-point number**. The format of the number is the same as expected by [`wcstof`](../../string/wide/wcstof "cpp/string/wide/wcstof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` | | `p` | matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A | For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified field width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The first character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`iswspace`](../../string/wide/iswspace "cpp/string/wide/iswspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width. If the length specifier `l` is not used, the conversion specifiers `c`, `s`, and `[` perform wide-to-multibyte character conversion as if by calling [`wcrtomb`](../../string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") with an [`mbstate_t`](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") object initialized to zero before the first character is converted. The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[std::gets](gets "cpp/io/c/gets")`. The correct conversion specifications for the [fixed-width integer types](../../types/integer "cpp/types/integer") (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although [`SCNdMAX`](../../types/integer "cpp/types/integer"), [`SCNuMAX`](../../types/integer "cpp/types/integer"), etc is synonymous with `%jd`, `%ju`, etc). There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable. When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765). ### Return value Number of arguments successfully read, or `[EOF](../c "cpp/io/c")` if failure occurs before the first receiving argument was assigned. ### Example ### See also | | | | --- | --- | | [vwscanfvfwscanfvswscanf](vfwscanf "cpp/io/c/vfwscanf") (C++11)(C++11)(C++11) | reads formatted wide character input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [C documentation](https://en.cppreference.com/w/c/io/fwscanf "c/io/fwscanf") for `wscanf, fwscanf, swscanf` |
programming_docs
cpp std::rename std::rename =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int rename( const char *old_filename, const char *new_filename ); ``` | | | Changes the filename of a file. The file is identified by character string pointed to by `old_filename`. The new filename is identified by character string pointed to by `new_filename`. If `new_filename` exists, the behavior is implementation-defined. ### Parameters | | | | | --- | --- | --- | | old\_filename | - | pointer to a null-terminated string containing the path identifying the file to rename | | new\_filename | - | pointer to a null-terminated string containing the new path of the file | ### Return value `​0​` upon success or non-zero value on error. ### Notes [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html) specifies many additional details on the semantics of this function, which are reproduced in C++ by `[std::filesystem::rename](../../filesystem/rename "cpp/filesystem/rename")`. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> int main() { bool ok{std::ofstream("from.txt").put('a')}; // create and write to file if (!ok) { std::perror("Error creating from.txt"); return 1; } if (std::rename("from.txt", "to.txt")) { std::perror("Error renaming"); return 1; } std::cout << std::ifstream("to.txt").rdbuf() << '\n'; // print file } ``` Output: ``` a ``` ### See also | | | | --- | --- | | [rename](../../filesystem/rename "cpp/filesystem/rename") (C++17) | moves or renames a file or directory (function) | | [remove](remove "cpp/io/c/remove") | erases a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/rename "c/io/rename") for `rename` | cpp std::fwide std::fwide ========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int fwide( std::FILE* stream, int mode ); ``` | | | If `mode > 0`, attempts to make `stream` wide-oriented. If `mode < 0`, attempts to make `stream` byte-oriented. If `mode==0`, only queries the current orientation of the stream. If the orientation of the stream has already been decided (by executing output or by an earlier call to fwide), this function does nothing. ### Parameters | | | | | --- | --- | --- | | stream | - | pointer to the C I/O stream to modify or query | | mode | - | integer value greater than zero to set the stream wide, less than zero to set the stream narrow, or zero to query only | ### Return value An integer greater than zero if the stream is wide-oriented after this call, less than zero if the stream is byte-oriented after this call, and zero if the stream has no orientation. ### Example The following code sets and resets the stream orientation. ``` #include <cwchar> #include <cstdio> #include <cstdlib> #include <iostream> void show_orientation(int n) { n < 0 ? std::wcout << "\tnarrow orientation\n" : n > 0 ? std::wcout << "\twide orientation\n" : std::wcout << "\tno orientation\n" ; } void try_read(FILE* fp) { if (const int c = std::fgetc(fp); c == EOF) std::wcout << "\tnarrow character read failed\n"; else std::wcout << "\tnarrow character read '" << static_cast<char>(c) << "'\n"; if (const wint_t wc = std::fgetwc(fp); wc == WEOF) std::wcout << "\twide character read failed\n"; else std::wcout << "\twide character read '" << static_cast<wchar_t>(wc) << "'\n"; } int main() { enum fwide_orientation : int { narrow = -1, query, wide }; FILE* fp = std::fopen("main.cpp", "r"); if (!fp) { std::wcerr << "fopen() failed\n"; return EXIT_FAILURE; } std::wcout << "1) A newly opened stream has no orientation.\n"; show_orientation(std::fwide(fp, fwide_orientation::query)); std::wcout << "2) Establish byte orientation.\n"; show_orientation(std::fwide(fp, fwide_orientation::narrow)); try_read(fp); std::wcout << "3) Only freopen() can reset stream orientation.\n"; if (std::freopen("main.cpp", "r", fp) == NULL) { std::wcerr << "freopen() failed\n"; return EXIT_FAILURE; } std::wcout << "4) A reopened stream has no orientation.\n"; show_orientation(std::fwide(fp, fwide_orientation::query)); std::wcout << "5) Establish wide orientation.\n"; show_orientation(std::fwide(fp, fwide_orientation::wide)); try_read(fp); std::fclose(fp); } ``` Possible output: ``` 1) A newly opened stream has no orientation. no orientation 2) Establish byte orientation. narrow orientation narrow character read '#' wide character read failed 3) Only freopen() can reset stream orientation. 4) A reopened stream has no orientation. no orientation 5) Establish wide orientation. wide orientation narrow character read failed wide character read '#' ``` ### See also | | | | --- | --- | | [fopen](fopen "cpp/io/c/fopen") | opens a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fwide "c/io/fwide") for `fwide` | cpp std::fputwc std::fputwc =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wint_t fputwc( wchar_t ch, std::FILE* stream ); ``` | | | | ``` wint_t putwc( wchar_t ch, std::FILE* stream ); ``` | | | Writes a wide character `ch` to the given output stream `stream`. `putwc()` may be implemented as a macro and may evaluate `stream` more than once. ### Parameters | | | | | --- | --- | --- | | ch | - | wide character to be written | | stream | - | the output stream | ### Return value `ch` on success, `WEOF` on failure. If an encoding error occurs, `[errno](../../error/errno "cpp/error/errno")` is set to `EILSEQ`. ### See also | | | | --- | --- | | [fputcputc](fputc "cpp/io/c/fputc") | writes a character to a file stream (function) | | [fputws](fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [fgetwcgetwc](fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fputwc "c/io/fputwc") for `fputwc` | cpp std::setvbuf std::setvbuf ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int setvbuf( std::FILE* stream, char* buffer, int mode, std::size_t size ); ``` | | | Changes the buffering mode of the given file stream `stream` as indicated by the argument `mode`. In addition, * If `buffer` is a null pointer, resizes the internal buffer to `size`. * If `buffer` is not a null pointer, instructs the stream to use the user-provided buffer of size `size` beginning at `buffer`. The stream must be closed (with `[std::fclose](fclose "cpp/io/c/fclose")`) before the [lifetime](../../language/lifetime "cpp/language/lifetime") of the array pointed to by `buffer` ends. The contents of the array after a successful call to `std::setvbuf` are indeterminate and any attempt to use it is undefined behavior. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to set the buffer to | | buffer | - | pointer to a buffer for the stream to use or null pointer to change size and mode only | | mode | - | buffering mode to use. It can be one of the following values: | | | | --- | --- | | `_IOFBF` | full buffering | | `_IOLBF` | line buffering | | `_IONBF` | no buffering | | | size | - | size of the buffer | ### Return value `​0​` on success or nonzero on failure. ### Notes This function may only be used after `stream` has been associated with an open file, but before any other operation (other than a failed call to `[std::setbuf](setbuf "cpp/io/c/setbuf")`/`std::setvbuf`). Not all `size` bytes will necessarily be used for buffering: the actual buffer size is usually rounded down to a multiple of 2, a multiple of page size, etc. On many implementations, line buffering is only available for terminal input streams. A common error is setting the buffer of `stdin` or `stdout` to an array whose lifetime ends before the program terminates: ``` int main() { char buf[BUFSIZ]; std::setbuf(stdin, buf); } // lifetime of buf ends, undefined behavior ``` The default buffer size `[BUFSIZ](../c "cpp/io/c")` is expected to be the most efficient buffer size for file I/O on the implementation, but POSIX [`fstat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fstat.html) often provides a better estimate. ### Example one use case for changing buffer size is when a better size is known. ``` #include <iostream> #include <cstdio> #include <cstdlib> #include <sys/stat.h> int main() { std::FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("fopen"); return EXIT_FAILURE; } struct stat stats; if(fstat(fileno(fp), &stats) == -1) { // POSIX only std::perror("fstat"); return EXIT_FAILURE; } std::cout << "BUFSIZ is " << BUFSIZ << ", but optimal block size is " << stats.st_blksize << '\n'; if(std::setvbuf(fp, nullptr, _IOFBF, stats.st_blksize) != 0) { std::perror("setvbuf failed"); // POSIX version sets errno return EXIT_FAILURE; } // read entire file: use truss/strace // to observe the read(2) syscalls used for (int ch; (ch = std::fgetc(fp)) != EOF; ) {} std::fclose(fp); return EXIT_SUCCESS; } ``` Possible output: ``` BUFSIZ is 8192, but optimal block size is 65536 ``` ### See also | | | | --- | --- | | [setbuf](setbuf "cpp/io/c/setbuf") | sets the buffer for a file stream (function) | | [setbuf](../basic_filebuf/setbuf "cpp/io/basic filebuf/setbuf") [virtual] | provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function of `std::basic_filebuf<CharT,Traits>`) | | [C documentation](https://en.cppreference.com/w/c/io/setvbuf "c/io/setvbuf") for `setvbuf` | cpp stdin, stdout, stderr stdin, stdout, stderr ===================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` #define stdin /* implementation-defined */ ``` | (1) | | | ``` #define stdout /* implementation-defined */ ``` | (2) | | | ``` #define stderr /* implementation-defined */ ``` | (3) | | Three text streams are predefined. These streams are implicitly opened and unoriented at program startup. 1) Associated with the *standard input* stream, used for reading conventional input. At program startup, the stream is fully buffered if and only if the stream can be determined not to refer to an interactive device. 2) Associated with the *standard output* stream, used for writing conventional output. At program startup, the stream is fully buffered if and only if the stream can be determined not to refer to an interactive device. 3) Associated with the *standard error* stream, used for writing diagnostic output. At program startup, the stream is not fully buffered. What consistutes an interactive device is implementation-defined. These macros are expanded to expressions of type `[std::FILE](http://en.cppreference.com/w/cpp/io/c/FILE)\*`. ### Notes Although not mandated by POSIX, the UNIX convention is that `stdin` and `stdout` are line-buffered if associated with a terminal and `stderr` is unbuffered. These macros may be expanded to modifiable lvalues. If any of these `[std::FILE](http://en.cppreference.com/w/cpp/io/c/FILE)\*` lvalue is modified, subsequent operations on the corresponding stream result in unspecified or undefined behavior. ### Example This example shows a function similar to `[std::printf](fprintf "cpp/io/c/fprintf")`. ``` #include <concepts> #include <cstdio> #include <type_traits> template<typename T> concept IsPrintable = std::integral<T> or std::floating_point<T> or std::is_pointer_v<T>; int my_printf(char const* const format, IsPrintable auto const ... arguments) { return std::fprintf(stdout, format, arguments...); } int main(int argv, char*[]) { my_printf("Strings and chars:\t%s %c\n", "hello", 'x'); my_printf("Rounding:\t\t%f %.0f %.32f\n", 1.5, 1.5, 1.3); my_printf("Padding:\t\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5); my_printf("Scientific:\t\t%E %e\n", 1.5, 1.5); my_printf("Hexadecimal:\t\t%a %A 0x%X\n", 1.5, 1.5, &argv); } ``` Possible output: ``` Strings and chars: hello x Rounding: 1.500000 2 1.30000000000000004440892098500626 Padding: 01.50 1.50 1.50 Scientific: 1.500000E+00 1.500000e+00 Hexadecimal: 0x1.8p+0 0X1.8P+0 0x2CFB41BC ``` ### See also | | | | --- | --- | | [cinwcin](../cin "cpp/io/cin") | reads from the standard C input stream `stdin` (global object) | | [coutwcout](../cout "cpp/io/cout") | writes to the standard C output stream `stdout`(global object) | | [cerrwcerr](../cerr "cpp/io/cerr") | writes to the standard C error stream `stderr`, unbuffered(global object) | | [clogwclog](../clog "cpp/io/clog") | writes to the standard C error stream `stderr`(global object) | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `stdout`, a file stream or a buffer (function) | | [FILE](file "cpp/io/c/FILE") | object type, capable of holding all information needed to control a C I/O stream (typedef) | | [C documentation](https://en.cppreference.com/w/c/io/std_streams "c/io/std streams") for `stdin, stdout, stderr` | cpp std::freopen std::freopen ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` std::FILE* freopen( const char* filename, const char* mode, std::FILE* stream ); ``` | | | First, attempts to close the file associated with `stream`, ignoring any errors. Then, if `filename` is not null, attempts to open the file specified by `filename` using `mode` as if by `[std::fopen](fopen "cpp/io/c/fopen")`, and associates that file with the file stream pointed to by `stream`. If `filename` is a null pointer, then the function attempts to reopen the file that is already associated with `stream` (it is implementation defined which mode changes are allowed in this case). ### Parameters | | | | | --- | --- | --- | | filename | - | file name to associate the file stream to | | mode | - | null-terminated character string determining new [file access mode](#File_access_flags) | | stream | - | the file stream to modify | ### File access flags | File access mode string | Meaning | Explanation | Action if file already exists | Action if file does not exist | | --- | --- | --- | --- | --- | | `"r"` | read | Open a file for reading | read from start | return `[NULL](http://en.cppreference.com/w/cpp/types/NULL)` and set error | | `"w"` | write | Create a file for writing | destroy contents | create new | | `"a"` | append | Append to a file | write to end | create new | | `"r+"` | read extended | Open a file for read/write | read from start | return `[NULL](http://en.cppreference.com/w/cpp/types/NULL)` and set error | | `"w+"` | write extended | Create a file for read/write | destroy contents | create new | | `"a+"` | append extended | Open a file for read/write | write to end | create new | | File access mode flag `"b"` can optionally be specified to open a file [in binary mode](file#Binary_and_text_modes "cpp/io/c/FILE"). This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of `'\n'` and `'\x1A'`. On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator. | | File access mode flag `"x"` can optionally be appended to `"w"` or `"w+"` specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C++17) | | The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. [Windows](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen)). | ### Return value `stream` on success, a null pointer on failure. ### Notes `std::freopen` is the only way to change the narrow/wide orientation of a stream once it has been established by an I/O operation or by `std::fwide`. Microsoft CRT version of `std::freopen` does not support any mode changes when `filename` is a null pointer and treats this as an error (see [documentation](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-wfreopen)). A possible workaround is the non-standard function [`_setmode()`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmode). ### Example The following code redirects `stdout` to a file. ``` #include <cstdio> int main() { std::printf("stdout is printed to console\n"); if(std::freopen("redir.txt", "w", stdout)) { std::printf("stdout is redirected to a file\n"); // this is written to redir.txt std::fclose(stdout); } } ``` Output: ``` stdout is printed to console ``` ### See also | | | | --- | --- | | [fopen](fopen "cpp/io/c/fopen") | opens a file (function) | | [fclose](fclose "cpp/io/c/fclose") | closes a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/freopen "c/io/freopen") for `freopen` | cpp std::fwrite std::fwrite =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count, std::FILE* stream ); ``` | | | Writes up to `count` binary objects from the given array `buffer` to the output stream `stream`. The objects are written as if by reinterpreting each object as an array of `unsigned char` and calling `[std::fputc](fputc "cpp/io/c/fputc")` `size` times for each object to write those `unsigned char`s into `stream`, in order. The file position indicator for the stream is advanced by the number of characters written. If the objects are not [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), the behavior is undefined. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. ### Parameters | | | | | --- | --- | --- | | buffer | - | pointer to the first object object in the array to be written | | size | - | size of each object | | count | - | the number of the objects to be written | | stream | - | output file stream to write to | ### Return value Number of objects written successfully, which may be less than `count` if an error occurred. If `size` or `count` is zero, `fwrite` returns zero and performs no other action. ### Example ``` #include <cstdio> #include <vector> #include <array> int main () { // write buffer to file if(std::FILE* f1 = std::fopen("file.bin", "wb")) { std::array<int, 3> v = {42, -1, 7}; // underlying storage of std::array is an array std::fwrite(v.data(), sizeof v[0], v.size(), f1); std::fclose(f1); } // read the same data and print it to the standard output if(std::FILE *f2 = std::fopen("file.bin", "rb")) { std::vector<int> rbuf(10); // underlying storage of std::vector is also an array std::size_t sz = std::fread(rbuf.data(), sizeof rbuf[0], rbuf.size(), f2); std::fclose(f2); for(std::size_t n = 0; n < sz; ++n) { std::printf("%d\n", rbuf[n]); } } } ``` Output: ``` 42 -1 7 ``` ### See also | | | | --- | --- | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [fread](fread "cpp/io/c/fread") | reads from a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fwrite "c/io/fwrite") for `fwrite` |
programming_docs
cpp std::fputc, std::putc std::fputc, std::putc ===================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fputc( int ch, std::FILE* stream ); int putc( int ch, std::FILE* stream ); ``` | | | Writes a character `ch` to the given output stream `stream`. Internally, the character is converted to `unsigned char` just before being written. In C, `putc()` may be implemented as a macro, which is disallowed in C++. Therefore calls to `std::fputc()` and `std::putc()` always have the same effect. ### Parameters | | | | | --- | --- | --- | | ch | - | character to be written | | stream | - | output stream | ### Return value On success, returns the written character. On failure, returns `[EOF](../c "cpp/io/c")` and sets the *error* indicator (see `[std::ferror()](ferror "cpp/io/c/ferror")`) on `stream`. ### Example ``` #include <cstdio> int main() { for (char c = 'a'; c != 'z'; c++) std::putc(c, stdout); std::putc('\n', stdout); // putchar return value is not equal to the argument int r = 0x1070; std::printf("\n0x%x\n", r); r = std::putchar(r); std::printf("\n0x%x\n", r); } ``` Output: ``` abcdefghijklmnopqrstuvwxy 0x1070 p 0x70 ``` ### See also | | | | --- | --- | | [putchar](putchar "cpp/io/c/putchar") | writes a character to `[stdout](std_streams "cpp/io/c/std streams")` (function) | | [C documentation](https://en.cppreference.com/w/c/io/fputc "c/io/fputc") for `fputc, putc` | cpp std::fgetc, std::getc std::fgetc, std::getc ===================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fgetc( std::FILE* stream ); int getc( std::FILE* stream ); ``` | | | Reads the next character from the given input stream. ### Parameters | | | | | --- | --- | --- | | stream | - | to read the character from | ### Return value The obtained character on success or `[EOF](../c "cpp/io/c")` on failure. If the failure has been caused by end of file condition, additionally sets the *eof* indicator (see `[std::feof()](feof "cpp/io/c/feof")`) on `stream`. If the failure has been caused by some other error, sets the *error* indicator (see `[std::ferror()](ferror "cpp/io/c/ferror")`) on `stream`. ### Example ``` #include <cstdio> #include <cstdlib> int main() { int is_ok = EXIT_FAILURE; FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("File opening failed"); return is_ok; } int c; // note: int, not char, required to handle EOF while ((c = std::fgetc(fp)) != EOF) { // standard C I/O file reading loop std::putchar(c); } if (std::ferror(fp)) { std::puts("I/O error when reading"); } else if (std::feof(fp)) { std::puts("End of file reached successfully"); is_ok = EXIT_SUCCESS; } std::fclose(fp); return is_ok; } ``` Output: ``` End of file reached successfully ``` ### See also | | | | --- | --- | | [gets](gets "cpp/io/c/gets") (deprecated in C++11)(removed in C++14) | reads a character string from `[stdin](std_streams "cpp/io/c/std streams")` (function) | | [fputcputc](fputc "cpp/io/c/fputc") | writes a character to a file stream (function) | | [ungetc](ungetc "cpp/io/c/ungetc") | puts a character back into a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fgetc "c/io/fgetc") for `fgetc, getc` | cpp std::ftell std::ftell ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` long ftell( std::FILE* stream ); ``` | | | Returns the current value of the file position indicator for the file stream `stream`. If the stream is open in binary mode, the value obtained by this function is the number of bytes from the beginning of the file. If the stream is open in text mode, the value returned by this function is unspecified and is only meaningful as the input to `[std::fseek](fseek "cpp/io/c/fseek")`. ### Parameters | | | | | --- | --- | --- | | stream | - | file stream to examine | ### Return value File position indicator on success or `-1L` if failure occurs. Also sets `[errno](../../error/errno "cpp/error/errno")` on failure. ### Example Demonstrates `std::ftell()` with error checking. Writes then reads a few floating-point (FP) values to/from a file. ``` #include <cstdio> #include <cstdlib> #include <iostream> // If the condition is not met then exit the program with error message. void check(bool condition, const char* func, int line) { if (condition) return; std::perror(func); std::cerr << func << " failed in file " << __FILE__ << " at line # " << line - 1 << '\n'; std::exit(EXIT_FAILURE); } int main() { // Prepare an array of FP values. constexpr int SIZE {5}; double A[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5}; // Write array to a file. const char* fname = "/tmp/test.bin"; FILE* file = std::fopen(fname, "wb"); check(file != NULL, "fopen()", __LINE__); const int write_count = std::fwrite(A, sizeof(double), SIZE, file); check(write_count == SIZE, "fwrite()", __LINE__); std::fclose(file); // Read the FP values into array B. double B[SIZE]; file = std::fopen(fname, "rb"); check(file != NULL, "fopen()", __LINE__); long pos = std::ftell(file); // position indicator at start of file check(pos != -1L, "ftell()", __LINE__); std::cout << "pos: " << pos << '\n'; const int read_count = std::fread(B, sizeof(double), 1, file); // read one FP value check(read_count == 1, "fread()", __LINE__); pos = std::ftell(file); // position indicator after reading one FP value check(pos != -1L, "ftell()", __LINE__); std::cout << "pos: " << pos << '\n'; std::cout << "B[0]: " << B[0] << '\n'; // print one FP value return EXIT_SUCCESS; } ``` Possible output: ``` pos: 0 pos: 8 B[0]: 1.1 ``` ### See also | | | | --- | --- | | [fgetpos](fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [fseek](fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [fsetpos](fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [tellg](../basic_istream/tellg "cpp/io/basic istream/tellg") | returns the input position indicator (public member function of `std::basic_istream<CharT,Traits>`) | | [tellp](../basic_ostream/tellp "cpp/io/basic ostream/tellp") | returns the output position indicator (public member function of `std::basic_ostream<CharT,Traits>`) | | [C documentation](https://en.cppreference.com/w/c/io/ftell "c/io/ftell") for `ftell` | cpp std::vscanf, std::vfscanf, std::vsscanf std::vscanf, std::vfscanf, std::vsscanf ======================================= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int vscanf( const char* format, va_list vlist ); ``` | (1) | (since C++11) | | ``` int vfscanf( std::FILE* stream, const char* format, va_list vlist ); ``` | (2) | (since C++11) | | ``` int vsscanf( const char* buffer, const char* format, va_list vlist ); ``` | (3) | (since C++11) | Reads data from the a variety of sources, interprets it according to `format` and stores the results into locations defined by `vlist`. 1) Reads the data from `[stdin](std_streams "cpp/io/c/std streams")`. 2) Reads the data from file stream `stream`. 3) Reads the data from null-terminated character string `buffer`. ### Parameters | | | | | --- | --- | --- | | stream | - | input file stream to read from | | buffer | - | pointer to a null-terminated character string to read from | | format | - | pointer to a null-terminated character string specifying how to read the input | | vlist | - | variable argument list containing the receiving arguments. | The **format** string consists of. * non-whitespace multibyte characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. * whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`isspace`](../../string/byte/isspace "cpp/string/byte/isspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string. * conversion specifications. Each conversion specification has the following format: + introductory `%` character + (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument. + (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided. + (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below). + conversion format specifier The following format specifiers are available: | Conversion specifier | Explanation | Argument type | | --- | --- | --- | | **Length modifier →** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `s` | matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `[`set`]` | matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `d` | matches a **decimal integer**. The format of the number is the same as expected by [`strtol`](../../string/byte/strtol "cpp/string/byte/strtol") with the value `10` for the `base` argument. | `signed char*` or `unsigned char*` | `signed short*` or `unsigned short*` | `signed int*` or `unsigned int*` | `signed long*` or `unsigned long*` | `signed long long*` or `unsigned long long*` | `intmax_t*` or `uintmax_t*` | `size_t*` | `ptrdiff_t*` | N/A | | `i` | matches an **integer**. The format of the number is the same as expected by [`strtol`](../../string/byte/strtol "cpp/string/byte/strtol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). | | `u` | matches an unsigned **decimal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `10` for the `base` argument. | | `o` | matches an unsigned **octal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `8` for the `base` argument. | | `x`, `X` | matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `16` for the `base` argument. | | `n` | returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. | | `a`, `A`(C++11) `e`, `E` `f`, `F` `g`, `G` | matches a **floating-point number**. The format of the number is the same as expected by [`strtof`](../../string/byte/strtof "cpp/string/byte/strtof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` | | `p` | matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A | For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified field width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The first character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`isspace`](../../string/byte/isspace "cpp/string/byte/isspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width. The conversion specifiers `lc`, `ls`, and `l[` perform multibyte-to-wide character conversion as if by calling [`mbrtowc`](../../string/multibyte/mbrtowc "cpp/string/multibyte/mbrtowc") with an [`mbstate_t`](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") object initialized to zero before the first character is converted. The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[std::gets](gets "cpp/io/c/gets")`. The correct conversion specifications for the [fixed-width integer types](../../types/integer "cpp/types/integer") (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although [`SCNdMAX`](../../types/integer "cpp/types/integer"), [`SCNuMAX`](../../types/integer "cpp/types/integer"), etc is synonymous with `%jd`, `%ju`, etc). There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable. When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765). ### Return value Number of arguments successfully read, or `[EOF](../c "cpp/io/c")` if failure occurs. ### Notes All these functions invoke `[va\_arg](../../utility/variadic/va_arg "cpp/utility/variadic/va arg")` at least once, the value of `arg` is indeterminate after the return. These functions to not invoke `[va\_end](../../utility/variadic/va_end "cpp/utility/variadic/va end")`, and it must be done by the caller. ### Example ``` #include <iostream> #include <cstdio> #include <cstdarg> #include <stdexcept> void checked_sscanf(int count, const char* buf, const char *fmt, ...) { va_list ap; va_start(ap, fmt); if(std::vsscanf(buf, fmt, ap) != count) throw std::runtime_error("parsing error"); va_end(ap); } int main() { try { int n, m; std::cout << "Parsing '1 2'..."; checked_sscanf(2, "1 2", "%d %d", &n, &m); std::cout << "success\n"; std::cout << "Parsing '1 a'..."; checked_sscanf(2, "1 a", "%d %d", &n, &m); std::cout << "success\n"; } catch(const std::exception& e) { std::cout << e.what() << '\n'; } } ``` Output: ``` Parsing '1 2'...success Parsing '1 a'...parsing error ``` ### See also | | | | --- | --- | | [scanffscanfsscanf](fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vprintfvfprintfvsprintfvsnprintf](vfprintf "cpp/io/c/vfprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [C documentation](https://en.cppreference.com/w/c/io/vfscanf "c/io/vfscanf") for `vscanf, vfscanf, vsscanf` | cpp std::ferror std::ferror =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int ferror( std::FILE* stream ); ``` | | | Checks the given stream for errors. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to check | ### Return value Nonzero value if the file stream has errors occurred, `​0​` otherwise. ### Example ``` #include <cstdio> #include <cstdlib> #include <clocale> #include <cwchar> int main(void) { const char *fname = std::tmpnam(nullptr); std::FILE* f = std::fopen(fname, "wb"); std::fputs("\xff\xff\n", f); // not a valid UTF-8 character sequence std::fclose(f); std::setlocale(LC_ALL, "en_US.utf8"); f = std::fopen(fname, "rb"); std::wint_t ch; while ((ch=std::fgetwc(f)) != WEOF) // attempt to read as UTF-8 std::printf("%#x ", ch); if (std::feof(f)) puts("EOF indicator set"); if (std::ferror(f)) puts("Error indicator set"); } ``` Output: ``` Error indicator set ``` ### See also | | | | --- | --- | | [clearerr](clearerr "cpp/io/c/clearerr") | clears errors (function) | | [feof](feof "cpp/io/c/feof") | checks for the end-of-file (function) | | [fail](../basic_ios/fail "cpp/io/basic ios/fail") | checks if an error has occurred (public member function of `std::basic_ios<CharT,Traits>`) | | [C documentation](https://en.cppreference.com/w/c/io/ferror "c/io/ferror") for `ferror` | cpp std::vwprintf, std::vfwprintf, std::vswprintf std::vwprintf, std::vfwprintf, std::vswprintf ============================================= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int vwprintf( const wchar_t* format, va_list vlist ); ``` | (1) | | | ``` int vfwprintf( std::FILE* stream, const wchar_t* format, va_list vlist ); ``` | (2) | | | ``` int vswprintf( wchar_t* buffer, std::size_t buf_size, const wchar_t* format, va_list vlist ); ``` | (3) | | Loads the data from locations, defined by `vlist`,, converts them to wide string equivalents and writes the results to a variety of sinks. 1) Writes the results to `[stdout](std_streams "cpp/io/c/std streams")`. 2) Writes the results to a file stream `stream`. 3) Writes the results to a wide string `buffer`. At most `size-1` wide characters are written followed by null wide character. ### Parameters | | | | | --- | --- | --- | | stream | - | output wide stream to write to | | buffer | - | pointer to a wide string to write to | | buf\_size | - | maximum number of wide characters to write | | format | - | pointer to a null-terminated wide string specifying how to interpret the data | | vlist | - | [variable argument list](../../language/variadic_arguments "cpp/language/variadic arguments") containing the data to print. | The **format** string consists of ordinary wide characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format: * introductory `%` character * (optional) one or more flags that modify the behavior of the conversion: + `-`: the result of the conversion is left-justified within the field (by default it is right-justified) + `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative) + *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present. + `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined. + `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present. * (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.) + (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*. + (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument) + conversion format specifier The following format specifiers are available: | ConversionSpecifier | Explanation | ExpectedArgument Type | | --- | --- | --- | | **LengthModifier****→** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | writes literal `%`. The full conversion specification must be `%%`. | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | writes a **single character**. The argument is first converted to `wchar_t` as if by calling `btowc`. If the **l** modifier is used, the `wint_t` argument is first converted to `wchar_t`. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A | | `s` | writes a **character string** The argument must be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state, which is converted to wide character array as if by a call to `mbrtowc` with zero-initialized conversion state. *Precision* specifies the maximum number of wide characters to be written. If *Precision* is not specified, writes every wide characters up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `d` `i` | converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `intmax_t` | signed `size_t` | `ptrdiff_t` | N/A | | `o` | converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `uintmax_t` | `size_t` | unsigned version of `ptrdiff_t` | N/A | | `x` `X` | converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A | | `u` | converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A | | `f` `F` | converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | `double` (C++11) | N/A | N/A | N/A | N/A | `long double` | | `e` `E` | converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `a` `A` (C++11). | converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `g` `G` | converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*. * otherwise, the conversion is with style `e` or `E` and precision *P − 1*. Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `n` | returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*. | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `intmax_t*` | signed `size_t*` | `ptrdiff_t*` | N/A | | `p` | writes an implementation defined character sequence defining a **pointer**. | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A | The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined. Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined. The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead. Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called. The correct conversion specifications for the fixed-width character types (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although `[PRIdMAX](../../types/integer "cpp/types/integer")`, `[PRIuMAX](../../types/integer "cpp/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc). The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions. There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call. If a conversion specification is invalid, the behavior is undefined. ### Return value 1,2) Number of wide characters written if successful or negative value if an error occurred. 3) Number of wide characters written (not counting the terminating null wide character) if successful or negative value if an encoding error occurred or if the number of characters to be generated was equal or greater than `size`. ### Notes While narrow strings provide `[std::vsnprintf](vfprintf "cpp/io/c/vfprintf")`, which makes it possible to determine the required output buffer size, there is no equivalent for wide strings, and in order to determine the buffer size, the program may need to call `std::vswprintf`, check the result value, and reallocate a larger buffer, trying again until successful. ### Example ### See also | | | | --- | --- | | [vprintfvfprintfvsprintfvsnprintf](vfprintf "cpp/io/c/vfprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [wprintffwprintfswprintf](fwprintf "cpp/io/c/fwprintf") | prints formatted wide character output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [C documentation](https://en.cppreference.com/w/c/io/vfwprintf "c/io/vfwprintf") for `vwprintf, vfwprintf, vswprintf` |
programming_docs
cpp std::ungetc std::ungetc =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int ungetc( int ch, std::FILE *stream ); ``` | | | If `ch` does not equal `[EOF](../c "cpp/io/c")`, pushes the character `ch` (reinterpreted as `unsigned char`) into the input buffer associated with the stream `stream` in such a manner than subsequent read operation from `stream` will retrieve that character. The external device associated with the stream is not modified. Stream repositioning operations `[std::fseek](fseek "cpp/io/c/fseek")`, `[std::fsetpos](fsetpos "cpp/io/c/fsetpos")`, and `[std::rewind](rewind "cpp/io/c/rewind")` discard the effects of `ungetc`. If `ungetc` is called more than once without an intervening read or repositioning, it may fail (in other words, a pushback buffer of size 1 is guaranteed, but any larger buffer is implementation-defined). If multiple successful `ungetc` were performed, read operations retrieve the pushed-back characters in reverse order of `ungetc`. If `ch` equals `[EOF](../c "cpp/io/c")`, the operation fails and the stream is not affected. A successful call to `ungetc` clears the end of file status flag `[std::feof](feof "cpp/io/c/feof")`. A successful call to `ungetc` on a binary stream decrements the stream position indicator by one (the behavior is indeterminate if the stream position indicator was zero). A successful call to `ungetc` on a text stream modifies the stream position indicator in unspecified manner but guarantees that after all pushed-back characters are retrieved with a read operation, the stream position indicator is equal to its value before `ungetc`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to be pushed into the input stream buffer | | stream | - | file stream to put the character back to | ### Return value On success `ch` is returned. On failure `[EOF](../c "cpp/io/c")` is returned and the given stream remains unchanged. ### Notes The size of the pushback buffer varies in practice from 4k (Linux, MacOS) to as little as 4 (Solaris) or the guaranteed minimum 1 (HPUX, AIX). The apparent size of the pushback buffer may be larger if the character that is pushed back equals the character existing at that location in the external character sequence (the implementation may simply decrement the read file position indicator and avoid maintaining a pushback buffer). ### Example demonstrates the use of `std::ungetc` in its original purpose: implementing `[std::scanf](fscanf "cpp/io/c/fscanf")`. ``` #include <cctype> #include <cstdio> void demo_scanf(const char* fmt, std::FILE* s) { while (*fmt != '\0') { if (*fmt == '%') { switch (*++fmt) { case 'u': { int c{}; while (std::isspace(c=std::getc(s))) {} unsigned int num{}; while (std::isdigit(c)) { num = num*10 + c-'0'; c = std::getc(s); } std::printf("%%u scanned %u\n", num); std::ungetc(c, s); break; } case 'c': { int c = std::getc(s); std::printf("%%c scanned '%c'\n", c); break; } } } else { ++fmt; } } } int main() { if (std::FILE* f = std::fopen("input.txt", "w+")) { std::fputs("123x", f); std::rewind(f); demo_scanf("%u%c", f); std::fclose(f); } } ``` Output: ``` %u scanned 123 %c scanned 'x' ``` ### See also | | | | --- | --- | | [fgetcgetc](fgetc "cpp/io/c/fgetc") | gets a character from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/ungetc "c/io/ungetc") for `ungetc` | cpp std::fgetpos std::fgetpos ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fgetpos( std::FILE* stream, std::fpos_t* pos ); ``` | | | Obtains the file position indicator and the current parse state (if any) for the file stream `stream` and stores them in the object pointed to by `pos`. The value stored is only meaningful as the input to `[std::fsetpos](fsetpos "cpp/io/c/fsetpos")`. ### Parameters | | | | | --- | --- | --- | | stream | - | file stream to examine | | pos | - | pointer to a `fpos_t` object to store the file position indicator to | ### Return value `​0​` upon success, nonzero value otherwise. Also sets `[errno](../../error/errno "cpp/error/errno")` on failure. ### Example ### See also | | | | --- | --- | | [ftell](ftell "cpp/io/c/ftell") | returns the current file position indicator (function) | | [fseek](fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [fsetpos](fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fgetpos "c/io/fgetpos") for `fgetpos` | cpp std::putchar std::putchar ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int putchar( int ch ); ``` | | | Writes a character `ch` to `stdout`. Internally, the character is converted to `unsigned char` just before being written. Equivalent to `putc(ch, stdout)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to be written | ### Return value On success, returns the written character. On failure, returns `[EOF](../c "cpp/io/c")` and sets the *error* indicator (see `ferror()`) on `[stdout](std_streams "cpp/io/c/std streams")`. ### Example ``` #include <cstdio> int main() { for (char c = 'a'; c != 'z'; c++) std::putchar(c); std::putchar('\n'); // putchar return value is not equal to the argument int r = 0x1070; std::printf("\n0x%x\n", r); r = std::putchar(r); std::printf("\n0x%x\n", r); } ``` Output: ``` abcdefghijklmnopqrstuvwxy 0x1070 p 0x70 ``` ### See also | | | | --- | --- | | [fputcputc](fputc "cpp/io/c/fputc") | writes a character to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/putchar "c/io/putchar") for `putchar` | cpp std::scanf, std::fscanf, std::sscanf std::scanf, std::fscanf, std::sscanf ==================================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int scanf( const char* format, ... ); ``` | (1) | | | ``` int fscanf( std::FILE* stream, const char* format, ... ); ``` | (2) | | | ``` int sscanf( const char* buffer, const char* format, ... ); ``` | (3) | | Reads data from a variety of sources, interprets it according to `format` and stores the results into given locations. 1) Reads the data from `[stdin](std_streams "cpp/io/c/std streams")` 2) Reads the data from file stream `stream` 3) Reads the data from null-terminated character string `buffer` ### Parameters | | | | | --- | --- | --- | | stream | - | input file stream to read from | | buffer | - | pointer to a null-terminated character string to read from | | format | - | pointer to a null-terminated character string specifying how to read the input | | ... | - | receiving arguments. | The **format** string consists of. * non-whitespace multibyte characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. * whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`isspace`](../../string/byte/isspace "cpp/string/byte/isspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string. * conversion specifications. Each conversion specification has the following format: + introductory `%` character + (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument. + (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided. + (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below). + conversion format specifier The following format specifiers are available: | Conversion specifier | Explanation | Argument type | | --- | --- | --- | | **Length modifier →** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `s` | matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `[`set`]` | matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `d` | matches a **decimal integer**. The format of the number is the same as expected by [`strtol`](../../string/byte/strtol "cpp/string/byte/strtol") with the value `10` for the `base` argument. | `signed char*` or `unsigned char*` | `signed short*` or `unsigned short*` | `signed int*` or `unsigned int*` | `signed long*` or `unsigned long*` | `signed long long*` or `unsigned long long*` | `intmax_t*` or `uintmax_t*` | `size_t*` | `ptrdiff_t*` | N/A | | `i` | matches an **integer**. The format of the number is the same as expected by [`strtol`](../../string/byte/strtol "cpp/string/byte/strtol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). | | `u` | matches an unsigned **decimal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `10` for the `base` argument. | | `o` | matches an unsigned **octal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `8` for the `base` argument. | | `x`, `X` | matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`strtoul`](../../string/byte/strtoul "cpp/string/byte/strtoul") with the value `16` for the `base` argument. | | `n` | returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. | | `a`, `A`(C++11) `e`, `E` `f`, `F` `g`, `G` | matches a **floating-point number**. The format of the number is the same as expected by [`strtof`](../../string/byte/strtof "cpp/string/byte/strtof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` | | `p` | matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A | For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified field width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The first character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`isspace`](../../string/byte/isspace "cpp/string/byte/isspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width. The conversion specifiers `lc`, `ls`, and `l[` perform multibyte-to-wide character conversion as if by calling [`mbrtowc`](../../string/multibyte/mbrtowc "cpp/string/multibyte/mbrtowc") with an [`mbstate_t`](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") object initialized to zero before the first character is converted. The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[std::gets](gets "cpp/io/c/gets")`. The correct conversion specifications for the [fixed-width integer types](../../types/integer "cpp/types/integer") (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although [`SCNdMAX`](../../types/integer "cpp/types/integer"), [`SCNuMAX`](../../types/integer "cpp/types/integer"), etc is synonymous with `%jd`, `%ju`, etc). There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable. When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765). ### Return value Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or `[EOF](../c "cpp/io/c")` if input failure occurs before the first receiving argument was assigned. ### Complexity Not guaranteed. Notably, some implementations of `std::sscanf` are O(N), where `N = [std::strlen](http://en.cppreference.com/w/cpp/string/byte/strlen)(buffer)` [[1]](https://sourceware.org/bugzilla/show_bug.cgi?id=17577). For performant string parsing, see `[std::from\_chars](../../utility/from_chars "cpp/utility/from chars")`. ### Notes Because most conversion specifiers first consume all consecutive whitespace, code such as. ``` std::scanf("%d", &a); std::scanf("%d", &b); ``` will read two integers that are entered on different lines (second `%d` will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second `%d` will consume the spaces or tabs). The conversion specifiers that do not consume leading whitespace, such as `%c`, can be made to do so by using a whitespace character in the format string: ``` std::scanf("%d", &a); std::scanf(" %c", &c); // ignore the endline after %d, then read a char ``` Note that some implementations of `std::sscanf` involve a call to `[std::strlen](../../string/byte/strlen "cpp/string/byte/strlen")`, which makes their runtime linear on the length of the entire string. This means that if `std::sscanf` is called in a loop to repeatedly parse values from the front of a string, your code might run in quadratic time ([example](https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/#Problem-one-It%E2%80%99s%E2%80%A6-strlen)). ### Example ``` #include <iostream> #include <clocale> #include <cstdio> int main() { int i, j; float x, y; char str1[10], str2[4]; wchar_t warr[2]; std::setlocale(LC_ALL, "en_US.utf8"); char input[] = "25 54.32E-1 Thompson 56789 0123 56ß水"; // parse as follows: // %d: an integer // %f: a floating-point value // %9s: a string of at most 9 non-whitespace characters // %2d: two-digit integer (digits 5 and 6) // %f: a floating-point value (digits 7, 8, 9) // %*d an integer which isn't stored anywhere // ' ': all consecutive whitespace // %3[0-9]: a string of at most 3 digits (digits 5 and 6) // %2lc: two wide characters, using multibyte to wide conversion const int ret = std::sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc", &i, &x, str1, &j, &y, str2, warr); std::cout << "Converted " << ret << " fields:\n" "i = " << i << "\n" "x = " << x << "\n" "str1 = " << str1 << "\n" "j = " << j << "\n" "y = " << y << "\n" "str2 = " << str2 << std::hex << "\n" "warr[0] = U+" << (int)warr[0] << "\n" "warr[1] = U+" << (int)warr[1] << '\n'; } ``` Output: ``` Converted 7 fields: i = 25 x = 5.432 str1 = Thompson j = 56 y = 789 str2 = 56 warr[0] = U+df warr[1] = U+6c34 ``` ### See also | | | | --- | --- | | [vscanfvfscanfvsscanf](vfscanf "cpp/io/c/vfscanf") (C++11)(C++11)(C++11) | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [fgets](fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [C documentation](https://en.cppreference.com/w/c/io/fscanf "c/io/fscanf") for `scanf, fscanf, sscanf` | cpp std::fgetws std::fgetws =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t* fgetws( wchar_t* str, int count, std::FILE* stream ); ``` | | | Reads at most `count - 1` wide characters from the given file stream and stores them in `str`. The produced wide string is always null-terminated. Parsing stops if end-of-file occurs or a newline wide character is found, in which case `str` will contain that wide newline character. ### Parameters | | | | | --- | --- | --- | | str | - | wide string to read the characters to | | count | - | the length of `str` | | stream | - | file stream to read the data from | ### Return value `str` on success, a null pointer on an error. ### See also | | | | --- | --- | | [wscanffwscanfswscanf](fwscanf "cpp/io/c/fwscanf") | reads formatted wide character input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [fgetwcgetwc](fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [fputws](fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fgetws "c/io/fgetws") for `fgetws` |
programming_docs
cpp std::FILE std::FILE ========= | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` typedef /* unspecified */ FILE; ``` | | | Each `std::FILE` object denotes a C stream. C standard (referenced by C++ standard) does not specify whether `std::FILE` is a complete object type. While it may be possible to copy a valid `std::FILE`, using a pointer to such a copy as an argument for an I/O function invokes unspecified behavior. In other words, `std::FILE` may be semantically non-copyable. I/O streams can be used for both unformatted and formatted input and output. Furthermore, the functions that handle input and output can also be locale-sensitive, such that wide/multibyte conversions are performed as necessary. ### Stream state Besides the system-specific information necessary to access the device (*e.g.,* a POSIX file descriptor), each `std::FILE` object directly or indirectly holds the following: 1. Character width: unset, narrow, or wide. 2. Parse state for conversions between multibyte and wide characters (an object of type `[std::mbstate\_t](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t")`) 3. Buffering state: unbuffered, line-buffered, fully buffered. 4. The buffer, which may be replaced by an external, user-provided buffer. 5. I/O mode: input, output, or update (both input and output). 6. Binary/text mode indicator. 7. End-of-file status indicator. 8. Error status indicator. 9. File position indicator, accessible as an object of type `[std::fpos\_t](fpos_t "cpp/io/c/fpos t")`, which, for wide streams, includes parse state. 10. (C++17) Reentrant lock used to prevent data races when multiple threads read, write, position, or query the position of a stream. #### Narrow and wide orientation A newly opened stream has no orientation. The first call to `std::fwide` or to any I/O function establishes the orientation: a wide I/O function makes the stream wide-oriented; a narrow I/O function makes the stream narrow-oriented. Once set, the orientation can be changed with only `[std::freopen](freopen "cpp/io/c/freopen")`. Narrow I/O functions cannot be called on a wide-oriented stream; wide I/O functions cannot be called on a narrow-oriented stream. Wide I/O functions convert between wide and multibyte characters as if by calling `[std::mbrtowc](../../string/multibyte/mbrtowc "cpp/string/multibyte/mbrtowc")` or `[std::wcrtomb](../../string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb")` with the coversion state as described by the stream. Unlike the multibyte character strings that are valid in a program, multibyte character sequences in the file may contain embedded nulls and do not have to begin or end in the initial shift state. The conversion state of a stream with wide orientation is established by the C locale that is installed at the time the stream's orientation is set. #### Binary and text modes A *text stream* is an ordered sequence of characters that can be composed into lines; a line can be decomposed into zero or more characters plus a terminating `'\n'` (“newline”) character. Whether the last line requires a terminating `'\n'` is implementation-defined. Furthermore, characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert `'\n'` to `'\r\n'` on output, and convert `'\r\n'` to `'\n'` on input). Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if each of the following is true: * The data consist of only printing characters and/or the control characters `'\t'` and `'\n'` (in particular, on Windows OS, the character `'\0x1A'` terminates input). * No `'\n'` character is immediately preceded by space characters (such space characters may disappear when such output is later read as input). * The last character is `'\n'`. A *binary stream* is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equal the data that were earlier written out to that stream, except that an implementation is allowed to append an indeterminate number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state. ### Notes POSIX explicitly requires that the `LC_CTYPE` facet of the currently installed C locale be stored within the `FILE` object the moment the stream's orientation becomes wide; POSIX requires that this `LC_CTYPE` facet be used for all future I/O on this stream until the orientation is changed, regardless of any subsequent call to `[std::setlocale](../../locale/setlocale "cpp/locale/setlocale")`. It is intended that each line of text be composed of data that are essentially human-readable. POSIX implementations do not distinguish between text and binary streams (there is no special mapping for `'\n'` or any other characters). ### See also | | | | --- | --- | | [basic\_streambuf](../basic_streambuf "cpp/io/basic streambuf") | abstracts a raw device (class template) | | [basic\_filebuf](../basic_filebuf "cpp/io/basic filebuf") | implements raw file device (class template) | | [stdinstdoutstderr](std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | | [C documentation](https://en.cppreference.com/w/c/io/FILE "c/io/FILE") for `FILE` | cpp std::perror std::perror =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` void perror( const char *s ); ``` | | | Prints a textual description of the error code currently stored in the system variable `[errno](../../error/errno "cpp/error/errno")` to `[stderr](std_streams "cpp/io/c/std streams")`. The description is formed by concatenating the following components: * the contents of the null-terminated byte string pointed to by `s`, followed by `": "` (unless `s` is a null pointer or the character pointed to by `s` is the null character) * implementation-defined error message string describing the error code stored in `errno`, followed by `'\n'`. The error message string is identical to the result of `[std::strerror](http://en.cppreference.com/w/cpp/string/byte/strerror)(errno)`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to a null-terminated string with explanatory message | ### Return value (none). ### Example ``` #include <cmath> #include <cerrno> #include <cstdio> int main() { double not_a_number = std::log(-1.0); if (errno == EDOM) { std::perror("log(-1) failed"); } std::printf("%f\n", not_a_number); } ``` Possible output: ``` log(-1) failed: Numerical argument out of domain nan ``` ### See also | | | | --- | --- | | [errno](../../error/errno "cpp/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) | | [strerror](../../string/byte/strerror "cpp/string/byte/strerror") | returns a text version of a given error code (function) | | [C documentation](https://en.cppreference.com/w/c/io/perror "c/io/perror") for `perror` | cpp std::getwchar std::getwchar ============= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wint_t getwchar(); ``` | | | Reads the next wide character from `[stdin](std_streams "cpp/io/c/std streams")`. ### Parameters (none). ### Return value The obtained wide character or `WEOF` if an error has occurred or the end of file reached. ### See also | | | | --- | --- | | [getchar](getchar "cpp/io/c/getchar") | reads a character from `[stdin](std_streams "cpp/io/c/std streams")` (function) | | [fgetwcgetwc](fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/getwchar "c/io/getwchar") for `getwchar` | cpp std::fgets std::fgets ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` char* fgets( char* str, int count, std::FILE* stream ); ``` | | | Reads at most `count - 1` characters from the given file stream and stores them in the character array pointed to by `str`. Parsing stops if a newline character is found, in which case `str` will contain that newline character, or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position immediately after the last character written to `str`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to an element of a char array | | count | - | maximum number of characters to write (typically the length of `str`) | | stream | - | file stream to read the data from | ### Return value `str` on success, null pointer on failure. If the end-of-file condition is encountered, sets the *eof* indicator on `stream` (see `[std::feof()](feof "cpp/io/c/feof")`). This is only a failure if it causes no bytes to be read, in which case a null pointer is returned and the contents of the array pointed to by `str` are not altered (i.e. the first byte is not overwritten with a null character). If the failure has been caused by some other error, sets the *error* indicator (see `[std::ferror()](ferror "cpp/io/c/ferror")`) on `stream`. The contents of the array pointed to by `str` are indeterminate (it may not even be null-terminated). ### Notes [POSIX additionally requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) that `fgets` sets `[errno](../../error/errno "cpp/error/errno")` if it encounters a failure other than the end-of-file condition. Although the standard specification is [unclear](https://stackoverflow.com/questions/23388620) in the cases where `count<=1`, common implementations do. * if `count < 1`, do nothing, report error * if `count == 1`, + some implementations do nothing, report error, + others read nothing, store zero in `str[0]`, report success ### Example ``` #include <iostream> #include <cstdio> #include <cstdlib> int main() { std::FILE* tmpf = std::tmpfile(); std::fputs("Alan Turing\n", tmpf); std::fputs("John von Neumann\n", tmpf); std::fputs("Alonzo Church\n", tmpf); std::rewind(tmpf); char buf[8]; while (std::fgets(buf, sizeof buf, tmpf) != nullptr) { std::cout << '"' << buf << '"' << '\n'; } } ``` Output: ``` "Alan Tu" "ring " "John vo" "n Neuma" "nn " "Alonzo " "Church " ``` ### See also | | | | --- | --- | | [scanffscanfsscanf](fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [gets](gets "cpp/io/c/gets") (deprecated in C++11)(removed in C++14) | reads a character string from `[stdin](std_streams "cpp/io/c/std streams")` (function) | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fgets "c/io/fgets") for `fgets` | cpp std::rewind std::rewind =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` void rewind( std::FILE* stream ); ``` | | | Moves the file position indicator to the beginning of the given file stream. The function is equivalent to `[std::fseek](http://en.cppreference.com/w/cpp/io/c/fseek)(stream, 0, [SEEK\_SET](http://en.cppreference.com/w/cpp/io/c));`, except that end-of-file and error indicators are cleared. The function drops any effects from previous calls to `ungetc`. ### Parameters | | | | | --- | --- | --- | | stream | - | file stream to modify | ### Return value (none). ### Example ``` #include <cstdio> int main() { std::FILE *f; char ch; char str[20]; f = std::fopen("file.txt", "w"); for (ch = '0'; ch <= '9'; ch++) { std::fputc(ch, f); } std::fclose(f); std::FILE* f2 = std::fopen("file.txt", "r"); unsigned int size = std::fread(str, 1, 10, f2); std::puts(str); std::printf("\n%u\n",size); std::rewind(f2); unsigned int size2 = std::fread(str, 1, 10, f2); std::puts(str); std::printf("\n%u",size2); std::fclose(f2); } ``` ### See also | | | | --- | --- | | [fseek](fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/rewind "c/io/rewind") for `rewind` | cpp std::fputs std::fputs ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fputs( const char* str, std::FILE* stream ); ``` | | | Writes every character from the null-terminated string `str` to the output stream `stream`, as if by repeatedly executing `[std::fputc](fputc "cpp/io/c/fputc")`. The terminating null character from `str` is not written. ### Parameters | | | | | --- | --- | --- | | str | - | null-terminated character string to be written | | stream | - | output stream | ### Return value On success, returns a non-negative value. On failure, returns `[EOF](../c "cpp/io/c")` and sets the *error* indicator (see `[std::ferror](ferror "cpp/io/c/ferror")`) on `stream`. ### Notes The related function `[std::puts](puts "cpp/io/c/puts")` appends a newline character to the output, while `std::fputs` writes the string unmodified. Different implementations return different non-negative numbers: some return the last character written, some return the number of characters written (or INT\_MAX if the string was longer than that), some simply return a non-negative constant such as zero. ### Example ``` #include <cstdio> int main(void) { int rc = std::fputs("Hello World", stdout); if (rc == EOF) std::perror("fputs()"); // POSIX requires that errno is set } ``` Output: ``` Hello World ``` ### See also | | | | --- | --- | | [printffprintfsprintfsnprintf](fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [puts](puts "cpp/io/c/puts") | writes a character string to `[stdout](std_streams "cpp/io/c/std streams")` (function) | | [fputws](fputws "cpp/io/c/fputws") | writes a wide string to a file stream (function) | | [fgets](fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fputs "c/io/fputs") for `fputs` | cpp std::fsetpos std::fsetpos ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fsetpos( std::FILE* stream, const std::fpos_t* pos ); ``` | | | Sets the file position indicator and the multibyte parsing state (if any) for the C file stream `stream` according to the value pointed to by `pos`. Besides establishing new parse state and position, a call to this function undoes the effects of `[std::ungetc](ungetc "cpp/io/c/ungetc")` and clears the end-of-file state, if it is set. If a read or write error occurs, the error indicator (`[std::ferror](ferror "cpp/io/c/ferror")`) for the stream is set. ### Parameters | | | | | --- | --- | --- | | stream | - | file stream to modify | | pos | - | pointer to a `fpos_t` object obtained from `[std::fgetpos](fgetpos "cpp/io/c/fgetpos")` called on a stream associated with the same file | ### Return value `​0​` upon success, nonzero value otherwise. Also, sets `[errno](../../error/errno "cpp/error/errno")` on failure. ### Notes After seeking to a non-end position in a wide stream, the next call to any output function may render the remainder of the file undefined, e.g. by outputting a multibyte sequence of a different length. ### Example ``` #include <cstdio> #include <cstdlib> int main() { // Prepare an array of floating-point values. const int SIZE = 5; double A[SIZE] = {1., 2., 3., 4., 5.}; // Write array to a file. std::FILE * fp = std::fopen("test.bin", "wb"); std::fwrite(A, sizeof(double), SIZE, fp); std::fclose(fp); // Read the values into array B. double B[SIZE]; fp = std::fopen("test.bin", "rb"); std::fpos_t pos; if (std::fgetpos(fp, &pos) != 0) // current position: start of file { std::perror("fgetpos()"); std::fprintf(stderr, "fgetpos() failed in file %s at line # %d\n", __FILE__, __LINE__-3); std::exit(EXIT_FAILURE); } int ret_code = std::fread(B, sizeof(double), 1, fp); // read one value // current position: after reading one value std::printf("%.1f; read count = %d\n", B[0], ret_code); // print one value and ret_code if (std::fsetpos(fp, &pos) != 0) // reset current position to start of file { if (std::ferror(fp)) { std::perror("fsetpos()"); std::fprintf(stderr, "fsetpos() failed in file %s at line # %d\n", __FILE__, __LINE__-5); std::exit(EXIT_FAILURE); } } ret_code = std::fread(B, sizeof(double), 1, fp); // re-read first value std::printf("%.1f; read count = %d\n", B[0], ret_code); // print one value and ret_code std::fclose(fp); return EXIT_SUCCESS; } ``` Output: ``` 1.0; read count = 1 1.0; read count = 1 ``` ### See also | | | | --- | --- | | [fgetpos](fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [ftell](ftell "cpp/io/c/ftell") | returns the current file position indicator (function) | | [fseek](fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fsetpos "c/io/fsetpos") for `fsetpos` | cpp std::vwscanf, std::vfwscanf, std::vswscanf std::vwscanf, std::vfwscanf, std::vswscanf ========================================== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int vwscanf( const wchar_t* format, va_list vlist ); ``` | (1) | (since C++11) | | ``` int vfwscanf( std::FILE* stream, const wchar_t* format, va_list vlist ); ``` | (2) | (since C++11) | | ``` int vswscanf( const wchar_t* buffer, const wchar_t* format, va_list vlist ); ``` | (3) | (since C++11) | Reads data from the a variety of sources, interprets it according to `format` and stores the results into locations defined by `vlist`. 1) Reads the data from `[stdin](std_streams "cpp/io/c/std streams")` 2) Reads the data from file stream `stream` 3) Reads the data from null-terminated wide string `buffer` ### Parameters | | | | | --- | --- | --- | | stream | - | input file stream to read from | | buffer | - | pointer to a null-terminated wide string to read from | | format | - | pointer to a null-terminated wide string specifying how to read the input | | vlist | - | variable argument list containing the receiving arguments. | The **format** string consists of. * non-whitespace wide characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal. * whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`iswspace`](../../string/wide/iswspace "cpp/string/wide/iswspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string. * conversion specifications. Each conversion specification has the following format: + introductory `%` character + (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument. + (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided. + (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below). + conversion format specifier The following format specifiers are available: | Conversion specifier | Explanation | Argument type | | --- | --- | --- | | **Length modifier →** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* wide characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `s` | matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `[`set`]` | matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). | | `d` | matches a **decimal integer**. The format of the number is the same as expected by [`wcstol`](../../string/wide/wcstol "cpp/string/wide/wcstol") with the value `10` for the `base` argument. | `signed char*` or `unsigned char*` | `signed short*` or `unsigned short*` | `signed int*` or `unsigned int*` | `signed long*` or `unsigned long*` | `signed long long*` or `unsigned long long*` | `intmax_t*` or `uintmax_t*` | `size_t*` | `ptrdiff_t*` | N/A | | `i` | matches an **integer**. The format of the number is the same as expected by [`wcstol`](../../string/wide/wcstol "cpp/string/wide/wcstol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). | | `u` | matches an unsigned **decimal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `10` for the `base` argument. | | `o` | matches an unsigned **octal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `8` for the `base` argument. | | `x`, `X` | matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`wcstoul`](../../string/wide/wcstoul "cpp/string/wide/wcstoul") with the value `16` for the `base` argument. | | `n` | returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. | | `a`, `A`(C++11) `e`, `E` `f`, `F` `g`, `G` | matches a **floating-point number**. The format of the number is the same as expected by [`wcstof`](../../string/wide/wcstof "cpp/string/wide/wcstof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` | | `p` | matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A | For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified field width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The first character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`iswspace`](../../string/wide/iswspace "cpp/string/wide/iswspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width. If the length specifier `l` is not used, the conversion specifiers `c`, `s`, and `[` perform wide-to-multibyte character conversion as if by calling [`wcrtomb`](../../string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") with an [`mbstate_t`](../../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") object initialized to zero before the first character is converted. The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[std::gets](gets "cpp/io/c/gets")`. The correct conversion specifications for the [fixed-width integer types](../../types/integer "cpp/types/integer") (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although [`SCNdMAX`](../../types/integer "cpp/types/integer"), [`SCNuMAX`](../../types/integer "cpp/types/integer"), etc is synonymous with `%jd`, `%ju`, etc). There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable. When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765). ### Return value Number of arguments successfully read, or `[EOF](../c "cpp/io/c")` if failure occurs. ### Example ### See also | | | | --- | --- | | [wscanffwscanfswscanf](fwscanf "cpp/io/c/fwscanf") | reads formatted wide character input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [C documentation](https://en.cppreference.com/w/c/io/vfwscanf "c/io/vfwscanf") for `vwscanf, vfwscanf, vswscanf` |
programming_docs
cpp std::tmpfile std::tmpfile ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` std::FILE* tmpfile(); ``` | | | Creates and opens a temporary file with a unique auto-generated filename. The file is opened as a binary file for update (as by `[std::fopen](fopen "cpp/io/c/fopen")` with access mode `"wb+"`). At least `[TMP\_MAX](../c "cpp/io/c")` files may be opened during the lifetime of a program (this limit may be shared with `[std::tmpnam](tmpnam "cpp/io/c/tmpnam")` and may be further limited by `[FOPEN\_MAX](../c "cpp/io/c")`). If the program closes the file, e.g. by executing `[std::fclose](fclose "cpp/io/c/fclose")`, the file is automatically deleted. If the program terminates normally (by calling `[std::exit](../../utility/program/exit "cpp/utility/program/exit")`, returning from `main`, etc), all files that were opened by calling `std::tmpfile` are also automatically deleted. If the program terminates abnormally, it is implementation-defined if these temporary files are deleted. ### Parameters (none). ### Return value The associated file stream or a null pointer if an error has occurred. ### Notes On some implementations (e.g. older Linux), this function actually creates, opens, and immediately deletes the file from the file system: as long as an open file descriptor to a deleted file is held by a program, the file exists, but since it was deleted, its name does not appear in any directory, so that no other process can open it. Once the file descriptor is closed, or once the program terminates (normally or abnormally), the space occupied by the file is reclaimed by the filesystem. Newer Linux (since 3.11 or later, depending on filesystem) creates such invisible temporary files in one step, via special flag in the [`open()`](https://man7.org/linux/man-pages/man2/open.2.html) syscall. On some implementations (e.g. Windows), elevated privileges are required as the function may create the temporary file in a system directory. ### Example ``` #include <iostream> #include <cstdio> #include <cstdlib> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "TMP_MAX = " << TMP_MAX << '\n' << "FOPEN_MAX = " << FOPEN_MAX << '\n'; std::FILE* tmpf = std::tmpfile(); std::fputs("Hello, world", tmpf); std::rewind(tmpf); char buf[6]; std::fgets(buf, sizeof buf, tmpf); std::cout << buf << '\n'; // Linux-specific method to display the tmpfile name std::cout << fs::read_symlink( fs::path("/proc/self/fd") / std::to_string(fileno(tmpf)) ) << '\n'; } ``` Possible output: ``` TMP_MAX = 238328 FOPEN_MAX = 16 Hello "/tmp/tmpfBlY1lI (deleted)" ``` ### See also | | | | --- | --- | | [tmpnam](tmpnam "cpp/io/c/tmpnam") | returns a unique filename (function) | | [temp\_directory\_path](../../filesystem/temp_directory_path "cpp/filesystem/temp directory path") (C++17) | returns a directory suitable for temporary files (function) | | [C documentation](https://en.cppreference.com/w/c/io/tmpfile "c/io/tmpfile") for `tmpfile` | cpp std::setbuf std::setbuf =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` void setbuf( std::FILE* stream, char* buffer ); ``` | | | Sets the internal buffer to use for I/O operations performed on the C stream `stream`. If `buffer` is not null, equivalent to `[std::setvbuf](http://en.cppreference.com/w/cpp/io/c/setvbuf)(stream, buffer, [\_IOFBF](http://en.cppreference.com/w/cpp/io/c), [BUFSIZ](http://en.cppreference.com/w/cpp/io/c))`. If `buffer` is null, equivalent to `[std::setvbuf](http://en.cppreference.com/w/cpp/io/c/setvbuf)(stream, nullptr, [\_IONBF](http://en.cppreference.com/w/cpp/io/c), 0)`, which turns off buffering. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to set the buffer to. | | buffer | - | pointer to a buffer for the stream to use. If a null pointer is supplied, the buffering is turned off. If not null, must be able to hold at least `BUFSIZ` characters | ### Return value (none). ### Notes If `[BUFSIZ](../c "cpp/io/c")` is not the appropriate buffer size, `[std::setvbuf](setvbuf "cpp/io/c/setvbuf")` can be used to change it. `[std::setvbuf](setvbuf "cpp/io/c/setvbuf")` should also be used to detect errors, since `std::setbuf` does not indicate success or failure. This function may only be used after `stream` has been associated with an open file, but before any other operation (other than a failed call to `std::setbuf`/`[std::setvbuf](setvbuf "cpp/io/c/setvbuf")`). A common error is setting the buffer of `stdin` or `stdout` to an array whose lifetime ends before the program terminates: ``` int main() { char buf[BUFSIZ]; std::setbuf(stdin, buf); } // lifetime of buf ends, undefined behavior ``` ### Example `std::setbuf` may be used to disable buffering on streams that require immediate output. ``` #include <cstdio> #include <thread> #include <chrono> int main() { using namespace std::chrono_literals; std::setbuf(stdout, nullptr); // unbuffered stdout std::putchar('a'); // appears immediately on unbuffered stream std::this_thread::sleep_for(1s); std::putchar('b'); } ``` Output: ``` ab ``` ### See also | | | | --- | --- | | [setvbuf](setvbuf "cpp/io/c/setvbuf") | sets the buffer and its size for a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/setbuf "c/io/setbuf") for `setbuf` | cpp std::ungetwc std::ungetwc ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wint_t ungetwc( wint_t ch, std::FILE* stream ); ``` | | | If `ch` does not equal `WEOF`, pushes the wide character `ch` into the input buffer associated with the stream `stream` in such a manner than subsequent read operation from `stream` will retrieve that wide character. The external device associated with the stream is not modified. Stream repositioning operations `[std::fseek](fseek "cpp/io/c/fseek")`, `[std::fsetpos](fsetpos "cpp/io/c/fsetpos")`, and `[std::rewind](rewind "cpp/io/c/rewind")` discard the effects of `ungetwc`. If `ungetwc` is called more than once without an intervening read or repositioning, it may fail (in other words, a pushback buffer of size 1 is guaranteed, but any larger buffer is implementation-defined). If multiple successful `ungetwc` were performed, read operations retrieve the pushed-back wide characters in reverse order of `ungetwc`. If `ch` equals `WEOF`, the operation fails and the stream is not affected. A successful call to `ungetwc` clears the end of file status flag `feof`. A successful call to `ungetwc` on a stream (whether text or binary) modifies the stream position indicator in unspecified manner but guarantees that after all pushed-back wide characters are retrieved with a read operation, the stream position indicator is equal to its value before `ungetwc`. ### Parameters | | | | | --- | --- | --- | | ch | - | wide character to be put back | | stream | - | file stream to put the wide character back to | ### Return value On success `ch` is returned. On failure `WEOF` is returned and the given stream remains unchanged. ### See also | | | | --- | --- | | [ungetc](ungetc "cpp/io/c/ungetc") | puts a character back into a file stream (function) | | [fgetwcgetwc](fgetwc "cpp/io/c/fgetwc") | gets a wide character from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/ungetwc "c/io/ungetwc") for `ungetwc` | cpp std::getchar std::getchar ============ | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int getchar(); ``` | | | Reads the next character from `[stdin](std_streams "cpp/io/c/std streams")`. Equivalent to `[std::getc](http://en.cppreference.com/w/cpp/io/c/fgetc)(stdin)`. ### Parameters (none). ### Return value The obtained character on success or `[EOF](../c "cpp/io/c")` on failure. If the failure has been caused by end of file condition, additionally sets the *eof* indicator (see `[std::feof()](feof "cpp/io/c/feof")`) on `[stdin](std_streams "cpp/io/c/std streams")`. If the failure has been caused by some other error, sets the *error* indicator (see `[std::ferror()](ferror "cpp/io/c/ferror")`) on `[stdin](std_streams "cpp/io/c/std streams")`. ### Example `std::getchar` with error checking. Exit program by entering ESC char. ``` #include <cctype> #include <cstdio> #include <cstdlib> #include <iomanip> #include <iostream> int main() { for (int ch; (ch = std::getchar()) != EOF ; ) { // read/print "abc" from stdin if (std::isprint(ch)) std::cout << static_cast<char>(ch) << '\n'; if (ch == 27) // 'ESC' (escape) in ASCII return EXIT_SUCCESS; } // Test reason for reaching EOF. if (std::feof(stdin)) { // if failure caused by end-of-file condition std::cout << "End of file reached\n"; } else if (std::ferror(stdin)) { // if failure caused by some other error std::perror("getchar()"); std::cerr << "getchar() failed in file " << std::quoted(__FILE__) << " at line # " << __LINE__ - 14 << '\n'; std::exit(EXIT_FAILURE); } return EXIT_SUCCESS; } ``` Possible output: ``` abc a b c ^[ ``` ### See also | | | | --- | --- | | [fgetcgetc](fgetc "cpp/io/c/fgetc") | gets a character from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/getchar "c/io/getchar") for `getchar` | cpp std::printf, std::fprintf, std::sprintf, std::snprintf std::printf, std::fprintf, std::sprintf, std::snprintf ====================================================== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int printf( const char* format, ... ); ``` | (1) | | | ``` int fprintf( std::FILE* stream, const char* format, ... ); ``` | (2) | | | ``` int sprintf( char* buffer, const char* format, ... ); ``` | (3) | | | ``` int snprintf( char* buffer, std::size_t buf_size, const char* format, ... ); ``` | (4) | (since C++11) | Loads the data from the given locations, converts them to character string equivalents and writes the results to a variety of sinks. 1) Writes the results to `[stdout](std_streams "cpp/io/c/std streams")`. 2) Writes the results to a file stream `stream`. 3) Writes the results to a character string `buffer`. 4) Writes the results to a character string `buffer`. At most `buf_size` - 1 characters are written. The resulting character string will be terminated with a null character, unless `buf_size` is zero. If `buf_size` is zero, nothing is written and `buffer` may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned. If a call to `sprintf` or `snprintf` causes copying to take place between objects that overlap, the behavior is undefined (e.g. `sprintf(buf, "%s text", buf);`). ### Parameters | | | | | --- | --- | --- | | stream | - | output file stream to write to | | buffer | - | pointer to a character string to write to | | buf\_size | - | up to buf\_size - 1 characters may be written, plus the null terminator | | format | - | pointer to a null-terminated multibyte string specifying how to interpret the data | | ... | - | arguments specifying data to print. If any argument after [default conversions](../../language/variadic_arguments#Default_conversions "cpp/language/variadic arguments") is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by `format`, the behavior is undefined. If there are more arguments than required by `format`, the extraneous arguments are evaluated and ignored. | The **format** string consists of ordinary multibyte characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format: * introductory `%` character * (optional) one or more flags that modify the behavior of the conversion: + `-`: the result of the conversion is left-justified within the field (by default it is right-justified) + `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative) + *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present. + `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined. + `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present. * (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.) + (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*. + (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument) + conversion format specifier The following format specifiers are available: | ConversionSpecifier | Explanation | ExpectedArgument Type | | --- | --- | --- | | **LengthModifier****→** | `hh` (C++11). | `h` | (none) | `l` | `ll` (C++11). | `j` (C++11). | `z` (C++11). | `t` (C++11). | `L` | | `%` | writes literal `%`. The full conversion specification must be `%%`. | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | | `c` | writes a **single character**. The argument is first converted to `unsigned char`. If the **l** modifier is used, the argument is first converted to a character string as if by **%ls** with a `wchar_t[2]` argument. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A | | `s` | writes a **character string** The argument must be a pointer to the initial element of an array of characters. *Precision* specifies the maximum number of bytes to be written. If *Precision* is not specified, writes every byte up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`, which is converted to char array as if by a call to `wcrtomb` with zero-initialized conversion state. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A | | `d` `i` | converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `intmax_t` | signed `size_t` | `ptrdiff_t` | N/A | | `o` | converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `uintmax_t` | `size_t` | unsigned version of `ptrdiff_t` | N/A | | `x` `X` | converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A | | `u` | converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A | | `f` `F` | converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | `double` (C++11) | N/A | N/A | N/A | N/A | `long double` | | `e` `E` | converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `a` `A` (C++11). | converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `g` `G` | converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*. * otherwise, the conversion is with style `e` or `E` and precision *P − 1*. Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A | | `n` | returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*. | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `intmax_t*` | signed `size_t*` | `ptrdiff_t*` | N/A | | `p` | writes an implementation defined character sequence defining a **pointer**. | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A | The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined. Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined. The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead. Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called. The correct conversion specifications for the fixed-width character types (`int8_t`, etc) are defined in the header [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") (although `[PRIdMAX](../../types/integer "cpp/types/integer")`, `[PRIuMAX](../../types/integer "cpp/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc). The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions. There is a [sequence point](../../language/eval_order "cpp/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call. If a conversion specification is invalid, the behavior is undefined. ### Return value 1-2) Number of characters written if successful or a negative value if an error occurred. 3) Number of characters written if successful (not including the terminating null character) or a negative value if an error occurred. 4) Number of characters that would have been written for a sufficiently large buffer if successful (not including the terminating null character), or a negative value if an error occurred. Thus, the (null-terminated) output has been completely written if and only if the returned value is nonnegative and less than `buf_size`. ### Notes [POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html) that `[errno](../../error/errno "cpp/error/errno")` is set on error. It also specifies additional conversion specifications, most notably support for argument reordering (`n$` immediately after `%` indicates `n`'th argument). Calling `std::snprintf` with zero `buf_size` and null pointer for `buffer` is useful to determine the necessary buffer size to contain the output: ``` const char fmt[] = "sqrt(2) = %f"; int sz = std::snprintf(nullptr, 0, fmt, std::sqrt(2)); std::vector<char> buf(sz + 1); // note +1 for null terminator std::snprintf(&buf[0], buf.size(), fmt, std::sqrt(2)); ``` ### Example ``` #include <cstdio> #include <limits> #include <cstdint> #include <cinttypes> int main() { std::printf("%s", "Strings:\n"); const char s[] = "Hello"; std::printf("\t[%10s]\n\t[%-10s]\n\t[%*s]\n\t[%-10.*s]\n\t[%-*.*s]\n", s, s, 10, s, 4, s, 10, 4, s); std::printf("Characters:\t%c %%\n", 65); std::printf("%s", "Integers\n"); std::printf("Decimal:\t%i %d %.6i %i %.0i %+i %i\n", 1, 2, 3, 0, 0, 4, -4); std::printf("Hexadecimal:\t%x %x %X %#x\n", 5, 10, 10, 6); std::printf("Octal:\t%o %#o %#o\n", 10, 10, 4); std::printf("%s", "Floating point\n"); std::printf("Rounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3); std::printf("Padding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5); std::printf("Scientific:\t%E %e\n", 1.5, 1.5); std::printf("Hexadecimal:\t%a %A\n", 1.5, 1.5); std::printf("Special values:\t0/0=%g 1/0=%g\n", 0.0/0.0, 1.0/0.0); std::printf("%s", "Variable width control:\n"); std::printf("right-justified variable width: '%*c'\n", 5, 'x'); int r = std::printf("left-justified variable width : '%*c'\n", -5, 'x'); std::printf("(the last printf printed %d characters)\n", r); // fixed-width types std::uint32_t val = std::numeric_limits<std::uint32_t>::max(); std::printf("Largest 32-bit value is %" PRIu32 " or %#" PRIx32 "\n", val, val); } ``` Output: ``` Strings: [ Hello] [Hello ] [ Hello] [Hell ] [Hell ] Characters: A % Integers Decimal: 1 2 000003 0 +4 -4 Hexadecimal: 5 a A 0x6 Octal: 12 012 04 Floating point Rounding: 1.500000 2 1.30000000000000004440892098500626 Padding: 01.50 1.50 1.50 Scientific: 1.500000E+00 1.500000e+00 Hexadecimal: 0x1.8p+0 0X1.8P+0 Special values: 0/0=nan 1/0=inf Variable width control: right-justified variable width: ' x' left-justified variable width : 'x ' (the last printf printed 40 characters) Largest 32-bit value is 4294967295 or 0xffffffff ``` ### See also | | | | --- | --- | | [wprintffwprintfswprintf](fwprintf "cpp/io/c/fwprintf") | prints formatted wide character output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vprintfvfprintfvsprintfvsnprintf](vfprintf "cpp/io/c/vfprintf") (C++11) | prints formatted output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [scanffscanfsscanf](fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [to\_chars](../../utility/to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | | [print](../print "cpp/io/print") (C++23) | prints to `[stdout](std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../../utility/format "cpp/utility/format") representation of the arguments (function template) | | [println](../println "cpp/io/println") (C++23) | same as `std::print` except that each print is terminated by additional new line (function template) | | [C documentation](https://en.cppreference.com/w/c/io/fprintf "c/io/fprintf") for `printf, fprintf, sprintf, snprintf` |
programming_docs
cpp std::fflush std::fflush =========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` int fflush( std::FILE* stream ); ``` | | | For output streams (and for update streams on which the last operation was output), writes any unwritten data from the `stream`'s buffer to the associated output device. For input streams (and for update streams on which the last operation was input), the behavior is undefined. If `stream` is a null pointer, all open output streams are flushed, including the ones manipulated within library packages or otherwise not directly accessible to the program. ### Parameters | | | | | --- | --- | --- | | stream | - | the file stream to write out | ### Return value Returns zero on success. Otherwise `[EOF](../c "cpp/io/c")` is returned and the error indicator of the file stream is set. ### Notes POSIX [extends the specification of fflush](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html) by defining its effects on an input stream, as long as that stream represents a file or another seekable device: in that case the POSIX file pointer is repositioned to match the C stream pointer (which effectively undoes any read buffering) and the effects of any `[std::ungetc](ungetc "cpp/io/c/ungetc")` or `[std::ungetwc](ungetwc "cpp/io/c/ungetwc")` that weren't yet read back from the stream are discarded. Microsoft also extends the specification of fflush by defining its effects on an input stream: in Visual Studio 2013 and prior, it [discarded the input buffer](https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/9yky46tz(v=vs.120)), in Visual Studio 2015 and newer, it [has no effect, buffers are retained](https://msdn.microsoft.com/en-us/library/9yky46tz.aspx). ### See also | | | | --- | --- | | [fopen](fopen "cpp/io/c/fopen") | opens a file (function) | | [fclose](fclose "cpp/io/c/fclose") | closes a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fflush "c/io/fflush") for `fflush` | cpp std::fputws std::fputws =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int fputws( const wchar_t* str, std::FILE* stream ); ``` | | | Writes every wide character from the null-terminated wide string `str` to the output stream `stream`, as if by repeatedly executing `[std::fputwc](fputwc "cpp/io/c/fputwc")`. The terminating null wide character from `str` is not written. ### Parameters | | | | | --- | --- | --- | | str | - | null-terminated wide string to be written | | stream | - | output stream | ### Return value On success, returns a non-negative value. On failure, returns `[EOF](../c "cpp/io/c")` and sets the *error* indicator (see `[std::ferror](ferror "cpp/io/c/ferror")`) on `stream`. ### Example ``` #include <clocale> #include <cstdio> #include <cwchar> int main() { std::setlocale(LC_ALL, "en_US.utf8"); int rc = std::fputws(L"御休みなさい", stdout); if (rc == EOF) std::perror("fputws()"); // POSIX requires that errno is set } ``` Output: ``` 御休みなさい ``` ### See also | | | | --- | --- | | [fputs](fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [wprintffwprintfswprintf](fwprintf "cpp/io/c/fwprintf") | prints formatted wide character output to `[stdout](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | **fputws** | writes a wide string to a file stream (function) | | [fgetws](fgetws "cpp/io/c/fgetws") | gets a wide string from a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/fputws "c/io/fputws") for `fputws` | cpp std::fread std::fread ========== | Defined in header `[<cstdio>](../../header/cstdio "cpp/header/cstdio")` | | | | --- | --- | --- | | ``` std::size_t fread( void* buffer, std::size_t size, std::size_t count, std::FILE* stream ); ``` | | | Reads up to `count` objects into the array `buffer` from the given input stream `stream` as if by calling `[std::fgetc](fgetc "cpp/io/c/fgetc")` `size` times for each object, and storing the results, in the order obtained, into the successive positions of `buffer`, which is reinterpreted as an array of `unsigned char`. The file position indicator for the stream is advanced by the number of characters read. If the objects are not [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), the behavior is undefined. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate. ### Parameters | | | | | --- | --- | --- | | buffer | - | pointer to the first object in the array to be read | | size | - | size of each object in bytes | | count | - | the number of the objects to be read | | stream | - | input file stream to read from | ### Return value Number of objects read successfully, which may be less than `count` if an error or end-of-file condition occurs. If `size` or `count` is zero, `fread` returns zero and performs no other action. ### Example ``` #include <iostream> #include <cstdio> #include <fstream> #include <vector> int main() { // prepare file std::ofstream("test.txt") << 1 << ' ' << 2 << '\n'; std::FILE* f = std::fopen("test.txt", "r"); std::vector<char> buf(4); // char is trivally copyable std::fread(&buf[0], sizeof buf[0], buf.size(), f); for(char n : buf) std::cout << n; std::vector<std::string> buf2; // string is not trivially copyable // this would result in undefined behavior // std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f); } ``` Output: ``` 1 2 ``` ### See also | | | | --- | --- | | [scanffscanfsscanf](fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [fgets](fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [fwrite](fwrite "cpp/io/c/fwrite") | writes to a file (function) | | [C documentation](https://en.cppreference.com/w/c/io/fread "c/io/fread") for `fread` | cpp std::putwchar std::putwchar ============= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wint_t putwchar( wchar_t ch ); ``` | | | Writes a wide character `ch` to `stdout`. ### Parameters | | | | | --- | --- | --- | | ch | - | wide character to be written | ### Return value `ch` on success, `WEOF` on failure. ### See also | | | | --- | --- | | [putchar](putchar "cpp/io/c/putchar") | writes a character to `[stdout](std_streams "cpp/io/c/std streams")` (function) | | [fputwcputwc](fputwc "cpp/io/c/fputwc") | writes a wide character to a file stream (function) | | [C documentation](https://en.cppreference.com/w/c/io/putwchar "c/io/putwchar") for `putwchar` | cpp C++ named requirements: CopyConstructible C++ named requirements: CopyConstructible ========================================= Specifies that an instance of the type can be copy-constructed from an [lvalue expression](../language/value_category "cpp/language/value category"). ### Requirements The type `T` satisfies CopyConstructible if. * The type `T` satisfies [MoveConstructible](moveconstructible "cpp/named req/MoveConstructible"), and Given. * `v`, an [lvalue](../language/value_category "cpp/language/value category") expression of type `T` or `const T` or an [rvalue](../language/value_category "cpp/language/value category") expression of type `const T` * `u`, an arbitrary identifier The following expressions must be valid and have their specified effects. | Expression | Post-conditions | | --- | --- | | `T u = v;` | The value of `u` is equivalent to the value of `v`. The value of `v` is unchanged. | | `T(v)` | The value of `T(v)` is equivalent to the value of `v`. The value of `v` is unchanged. | | | | | --- | --- | | The expression `v.~T()` also must be valid, and, for lvalue `v`, the expression `&v` must have the type `T*` or `const T*` and must evaluate to the address of `v`. | (until C++11) | ### Notes Until C++11, classes that overloaded `operator&` were not CopyConstructible and thus weren't usable in the standard library containers. As of C++11, the standard library uses `[std::addressof](../memory/addressof "cpp/memory/addressof")` whenever the address of an object is needed. ### See also | | | | --- | --- | | [is\_copy\_constructibleis\_trivially\_copy\_constructibleis\_nothrow\_copy\_constructible](../types/is_copy_constructible "cpp/types/is copy constructible") (C++11)(C++11)(C++11) | checks if a type has a copy constructor (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 C++ named requirements: Callable C++ named requirements: Callable ================================ A **Callable** type is a type for which the `*INVOKE*` operation (used by, e.g., `[std::function](../utility/functional/function "cpp/utility/functional/function")`, `[std::bind](../utility/functional/bind "cpp/utility/functional/bind")`, and `[std::thread::thread](../thread/thread/thread "cpp/thread/thread/thread")`) is applicable. | | | | --- | --- | | The `*INVOKE*` operation may be performed explicitly using the library function `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`. | (since C++17) | | The `*INVOKE*` operation with explicitly specified return type (`*INVOKE*<R>`) may be performed explicitly using the library function `std::invoke_r`. | (since C++23) | ### Requirements The type `T` satisfies Callable if. Given. * `f`, an object of type `T` * `ArgTypes`, suitable list of argument types * `R`, suitable return type The following expressions must be valid: | Expression | Requirements | | --- | --- | | `INVOKE<R>(f, [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<ArgTypes>()...)` | the expression is well-formed in unevaluated context | where *INVOKE<R>(f, t1, t2, ..., tN)* is defined as `static_cast<void>(INVOKE(f, t1, t2, ..., tN))` if `R` is possibly cv-qualified `void`, otherwise, *INVOKE(f, t1, t2, ..., tN)* is [implicitly converted](../language/implicit_conversion "cpp/language/implicit conversion") to `R`. If `R` is a reference type and the implicit conversion [binds a reference to a temporary object](../language/reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization"), the program is ill-formed, which may result in [substitution failure](../language/sfinae "cpp/language/sfinae"). (since C++23). where *INVOKE(f, t1, t2, ..., tN)* is defined as follows: * if `f` is a [pointer to member function](../language/pointer#Pointers_to_member_functions "cpp/language/pointer") of class `T`: + If `[std::is\_base\_of](http://en.cppreference.com/w/cpp/types/is_base_of)<T, [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<decltype(t1)>>::value` is `true`, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `(t1.*f)(t2, ..., tN)` + otherwise, if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<decltype(t1)>` is a specialization of `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")`, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `(t1.get().*f)(t2, ..., tN)` + otherwise, if `t1` does not satisfy the previous items, then `INVOKE(f, t1, t2, ..., tN)` is equivalent to `((*t1).*f)(t2, ..., tN)`. * otherwise, if N == 1 and `f` is a [pointer to data member](../language/pointer#Pointers_to_data_members "cpp/language/pointer") of class `T`: + If `[std::is\_base\_of](http://en.cppreference.com/w/cpp/types/is_base_of)<T, [std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<decltype(t1)>>::value` is `true`, then `INVOKE(f, t1)` is equivalent to `t1.*f` + otherwise, if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<decltype(t1)>` is a specialization of `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")`, then `INVOKE(f, t1)` is equivalent to `t1.get().*f` + otherwise, if `t1` does not satisfy the previous items, then `INVOKE(f, t1)` is equivalent to `(*t1).*f` * otherwise, `INVOKE(f, t1, t2, ..., tN)` is equivalent to `f(t1, t2, ..., tN)` (that is, `f` is a [FunctionObject](functionobject "cpp/named req/FunctionObject")) ### Notes For pointers to member functions and pointers to data members, `t1` may be a regular pointer or an object of class type that overloads `operator*`, such as `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` or `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")`. [Pointers to data members](../language/pointer#Pointers_to_data_members "cpp/language/pointer") are Callable, even though no function calls take place. ### Standard library In addition, the following standard library facilities accept any Callable type (not just [FunctionObject](functionobject "cpp/named req/FunctionObject")). | | | | --- | --- | | [function](../utility/functional/function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](../utility/functional/move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [bind](../utility/functional/bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [bind\_frontbind\_back](../utility/functional/bind_front "cpp/utility/functional/bind front") (C++20)(C++23) | bind a variable number of arguments, in order, to a function object (function template) | | [reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper") (C++11) | [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") reference wrapper (class template) | | [result\_ofinvoke\_result](../types/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) | | [thread](../thread/thread "cpp/thread/thread") (C++11) | manages a separate thread (class) | | [jthread](../thread/jthread "cpp/thread/jthread") (C++20) | `[std::thread](../thread/thread "cpp/thread/thread")` with support for auto-joining and cancellation (class) | | [call\_once](../thread/call_once "cpp/thread/call once") (C++11) | invokes a function only once even if called from multiple threads (function template) | | [async](../thread/async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `[std::future](../thread/future "cpp/thread/future")` that will hold the result (function template) | | [packaged\_task](../thread/packaged_task "cpp/thread/packaged task") (C++11) | packages a function to store its return value for asynchronous retrieval (class template) | ### 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 2219](https://cplusplus.github.io/LWG/issue2219) | C++11 | it's impossible to `*INVOKE*` a pointer to memberwith a `reference_wrapper` as the object expression | `reference_wrapper` is detected and handled | | [LWG 2420](https://cplusplus.github.io/LWG/issue2420) | C++11 | impossible implicit conversion from the resultto `void` was required when `R` is `void` | the result is discarded when `R` is cv `void` | ### See also | | | | --- | --- | | [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](../types/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) | | [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) | | [invokeinvoke\_r](../utility/functional/invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any **Callable** object with given arguments and possibility to specify return type (since C++23) (function template) | cpp C++ named requirements: Allocator C++ named requirements: Allocator ================================= Encapsulates strategies for access/addressing, allocation/deallocation and construction/destruction of objects. Every standard library component that may need to allocate or release storage, from `[std::string](../string/basic_string "cpp/string/basic string")`, `[std::vector](../container/vector "cpp/container/vector")`, and every container except `[std::array](../container/array "cpp/container/array")`, to `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::function](../utility/functional/function "cpp/utility/functional/function")`, does so through an **Allocator**: an object of a class type that satisfies the following requirements. The implementation of many allocator requirements is optional because all allocator-aware classes, including standard library containers, access allocators indirectly through `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")`, and `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")` supplies the default implementation of those requirements. ### Requirements Given. * `T`, a cv-unqualified object type * `A`, an Allocator type for type `T` * `a`, an object of type `A` * `B`, the corresponding Allocator type for some cv-unqualified object type `U` (as obtained by rebinding `A`) * `b`, an object of type `B` * `p`, a value of type `allocator_traits<A>::pointer`, obtained by calling `allocator_traits<A>::allocate()` * `cp`, a value of type `allocator_traits<A>::const_pointer`, obtained by conversion from `p` * `vp`, a value of type `allocator_traits<A>::void_pointer`, obtained by conversion from `p` * `cvp`, a value of type `allocator_traits<A>::const_void_pointer`, obtained by conversion from `cp` or from `vp` * `xp`, a dereferenceable pointer to some cv-unqualified object type `X` * `r`, an lvalue of type `T` obtained by the expression `*p` * `n`, a value of type `allocator_traits<A>::size_type` Inner types | Type-id | Aliased type | Requirements | | `A::pointer` (optional) | *(unspecified)*[[1]](#cite_note-1) | * Satisfies [NullablePointer](nullablepointer "cpp/named req/NullablePointer"), [LegacyRandomAccessIterator](randomaccessiterator "cpp/named req/RandomAccessIterator"), and [LegacyContiguousIterator](contiguousiterator "cpp/named req/ContiguousIterator"). | | `A::const_pointer` (optional) | *(unspecified)* | * Satisfies [NullablePointer](nullablepointer "cpp/named req/NullablePointer"), [LegacyRandomAccessIterator](randomaccessiterator "cpp/named req/RandomAccessIterator"), and [LegacyContiguousIterator](contiguousiterator "cpp/named req/ContiguousIterator"). * `A::pointer` is convertible to `A::const_pointer`. | | `A::void_pointer` (optional) | *(unspecified)* | * Satisfies [NullablePointer](nullablepointer "cpp/named req/NullablePointer"). * `A::pointer` is convertible to `A::void_pointer`. * `B::void_pointer` and `A::void_pointer` are the same type. | | `A::const_void_pointer` (optional) | *(unspecified)* | * Satisfies [NullablePointer](nullablepointer "cpp/named req/NullablePointer"). * `A::pointer`, `A::const_pointer`, and `A::void_pointer` are convertible to `A::const_void_pointer`. * `B::const_void_pointer` and `A::const_void_pointer` are the same type. | | `A::value_type` | `T` | | | `A::size_type` (optional) | *(unspecified)* | * An unsigned integer type. * Can represent the size of the largest object `A` can allocate. | | `A::difference_type` (optional) | *(unspecified)* | * A signed integer type. * Can represent the difference of any two pointers to the objects allocated by `A`. | | `A::template rebind<U>::other` (optional)[[2]](#cite_note-2) | `B` | * For any `U`, `B::template rebind<T>::other` is `A`. | Operations on pointers | Expression | Return type | Requirements | | `*p` | `T&` | | | `*cp` | `const T&` | `*cp` and `*p` identify the same object. | | `p->m` | *(as is)* | Same as `(*p).m`, if `(*p).m` is well-defined. | | `cp->m` | *(as is)* | Same as `(*cp).m`, if `(*cp).m` is well-defined. | | `static_cast<A::pointer>(vp)` | *(as is)* | `static_cast<A::pointer>(vp) == p` | | `static_cast<A::const_pointer>(cvp)` | *(as is)* | `static_cast<A::const_pointer>(cvp) == cp` | | `[std::pointer\_traits](http://en.cppreference.com/w/cpp/memory/pointer_traits)<A::pointer>::pointer\_to(r)` | *(as is)* | | Storage and lifetime operations | Expression | Return type | Requirements | | `a.allocate(n)` | `A::pointer` | Allocates storage suitable for an array object of type `T[n]` and creates the array, but does not construct array elements. May throw exceptions. | | `a.allocate(n, cvp)` (optional) | Same as `a.allocate(n)`, but may use `cvp` (`nullptr` or a pointer obtained from `a.allocate()`) in unspecified manner to aid locality. | | `a.allocate_at_least(n)` (optional) (since C++23) | `std::allocation_result< A::pointer>` | Allocates storage suitable for an array object of type `T[cnt]` and creates the array, but does not construct array elements, then returns `{p, cnt}`, where `p` points to the storage and `cnt` is not less than `n`. May throw exceptions. | | `a.deallocate(p, n)` | *(not used)* | Deallocates storage pointed to `p`, which must be a value returned by a previous call to `allocate` or `allocate_at_least` (since C++23) that has not been invalidated by an intervening call to `deallocate`. `n` must match the value previously passed to `allocate` or be between the request and returned number of elements via `allocate_at_least` (may be equal to either bound) (since C++23). Does not throw exceptions. | | `a.max_size()` (optional) | `A::size_type` | The largest value that can be passed to `A::allocate()`. | | `a.construct(xp, args)` (optional) | *(not used)* | Constructs an object of type `X` in previously-allocated storage at the address pointed to by `xp`, using `args` as the constructor arguments. | | `a.destroy(xp)` (optional) | *(not used)* | Destructs an object of type `X` pointed to by `xp`, but does not deallocate any storage. | Relationship between instances | Expression | Return type | Requirements | | `a1 == a2` | `bool` | * `true` only if the storage allocated by the allocator `a1` can be deallocated through `a2`. * Establishes reflexive, symmetric, and transitive relationship. * Does not throw exceptions. | | `a1 != a2` | * Same as `!(a1==a2)`. | | Declaration | Effect | Requirements | | `A a1(a)` | Copy-constructs `a1` such that `a1 == a`. (Note: Every Allocator also satisfies [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible").) | * Does not throw exceptions. | | `A a1 = a` | | `A a(b)` | Constructs `a` such that `B(a)==b` and `A(b)==a`. (Note: This implies that all allocators related by `rebind` maintain each other's resources, such as memory pools.) | * Does not throw exceptions. | | `A a1(std::move(a))` | Constructs `a1` such that it equals the prior value of `a`. | * Does not throw exceptions. * The value of `a` is unchanged and `a1 == a`. | | `A a1 = std::move(a)` | | `A a(std::move(b))` | Constructs `a` such that it equals the prior value of `A(b)`. | * Does not throw exceptions. | | Type-id | Aliased type | Requirements | | `A::is_always_equal` (optional) | `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` or derived from such. | * `true` if any two allocators of type `A` always compare equal. * (If not provided, `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")` defaults this to `[std::is\_empty](http://en.cppreference.com/w/cpp/types/is_empty)<A>::type`.) | Influence on container operations | Expression | Return type | Description | | `a.select_on_container_copy_construction()` (optional) | `A` | * Provides an instance of `A` to be used by the container that is copy-constructed from the one that uses `a` currently. * (Usually returns either a copy of `a` or a default-constructed `A`.) | | Type-id | Aliased type | Description | | `A::propagate_on_container_copy_assignment` (optional) | `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` or derived from such. | * `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it if the allocator of type `A` needs to be copied when the container that uses it is copy-assigned. * If this member is `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it, then `A` must satisfy [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") and the copy operation must not throw exceptions. * Note that if the allocators of the source and the target containers do not compare equal, copy assignment has to deallocate the target's memory using the old allocator and then allocate it using the new allocator before copying the elements (and the allocator). | | `A::propagate_on_container_move_assignment` (optional) | * `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it if the allocator of type `A` needs to be moved when the container that uses it is move-assigned. * If this member is `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it, then `A` must satisfy [MoveAssignable](moveassignable "cpp/named req/MoveAssignable") and the move operation must not throw exceptions. * If this member is not provided or derived from `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` and the allocators of the source and the target containers do not compare equal, move assignment cannot take ownership of the source memory and must move-assign or move-construct the elements individually, resizing its own memory as needed. | | `A::propagate_on_container_swap` (optional) | * `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it if the allocators of type `A` need to be swapped when two containers that use them are swapped. * If this member is `[std::true\_type](../types/integral_constant "cpp/types/integral constant")` or derived from it, lvalues of `A` must be [Swappable](swappable "cpp/named req/Swappable") and the swap operation must not throw exceptions. * If this member is not provided or derived from `[std::false\_type](../types/integral_constant "cpp/types/integral constant")` and the allocators of the two containers do not compare equal, the behavior of container swap is undefined. | Notes: 1. See also [fancy pointers](#Fancy_pointers) below. 2. `rebind` is only optional (provided by `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")`) if this allocator is a template of the form `SomeAllocator<T, Args>`, where `Args` is zero or more additional template type parameters. Given. * `x1` and `x2`, objects of (possibly different) types `X::void_pointer`, `X::const_void_pointer`, `X::pointer`, or `X::const_pointer` Then, x1 and x2 are *equivalently-valued* pointer values, if and only if both `x1` and `x2` can be explicitly converted to the two corresponding objects `px1` and `px2` of type `X::const_pointer`, using a sequence of `static_cast`s using only these four types, and the expression `px1 == px2` evaluates to true. Given. * `w1` and `w2`, objects of type `X::void_pointer`. Then for the expression `w1 == w2` and `w1 != w2` either or both objects may be replaced by an *equivalently-valued* object of type `X::const_void_pointer` with no change in semantics. Given. * `p1` and `p2`, objects of type `X::pointer` Then, for the expressions `p1 == p2`, `p1 != p2`, `p1 < p2` `p1 <= p2`, `p1 >= p2`, `p1 > p2`, `p1 - p2` either or both objects may be replaced by an *equivalently-valued* object of type `X::const_pointer` with no change in semantics. The above requirements make it possible to compare [Container](container "cpp/named req/Container")'s `iterator`s and `const_iterator`s. | | | | --- | --- | | Allocator completeness requirements An allocator type `X` for type `T` additionally satisfies the *allocator completeness requirements* if both of the following are true regardless of whether `T` is a complete type:* `X` is a complete type * Except for `value_type`, all the member types of `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<X>` are complete types. | (since C++17) | ### Stateful and stateless allocators Every Allocator type is either *stateful* or *stateless*. Generally, a stateful allocator type can have unequal values which denote distinct memory resources, while a stateless allocator type denotes a single memory resource. | | | | --- | --- | | Although custom allocators are not required to be stateless, whether and how the use of stateful allocators in the standard library is implementation-defined. Use of unequal allocator values may result in implementation-defined runtime errors or undefined behavior if the implementation does not support such usage. | (until C++11) | | Custom allocators may contain state. Each container or another allocator-aware object stores an instance of the supplied allocator and controls allocator replacement through `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")`. | (since C++11) | Instances of a stateless allocator type always compare equal. Stateless allocator types are typically implemented as empty classes and suitable for [empty base class optimization](../language/ebo "cpp/language/ebo"). | | | | --- | --- | | The member type `is_always_equal` of `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")` is intendedly used for determining whether an allocator type is stateless. | (since C++17) | ### Fancy pointers When the member type `pointer` is not a raw pointer type, it is commonly referred to as a ["fancy pointer"](http://wg21.link/p0773r0). Such pointers were introduced to support segmented memory architectures and are used today to access objects allocated in address spaces that differ from the homogeneous virtual address space that is accessed by raw pointers. An example of a fancy pointer is the mapping address-independent pointer [`boost::interprocess::offset_ptr`](http://www.boost.org/doc/libs/release/doc/html/interprocess/offset_ptr.html), which makes it possible to allocate node-based data structures such as `[std::set](../container/set "cpp/container/set")` in shared memory and memory mapped files mapped in different addresses in every process. Fancy pointers can be used independently of the allocator that provided them, through the class template `[std::pointer\_traits](../memory/pointer_traits "cpp/memory/pointer traits")` (since C++11). The function `[std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)` can be used to obtain a raw pointer from a fancy pointer. (since C++20). | | | | --- | --- | | Use of fancy pointers and customized size/different type in the standard libary are conditionally supported. Implementations may require that member type `pointer`, `const_pointer`, `size_type`, and `difference_type` are `value_type*`, `const value_type*`, `[std::size\_t](../types/size_t "cpp/types/size t")`, and `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`, respectively. | (until C++11) | ### Standard library The following standard library components satisfy the Allocator requirements: | | | | --- | --- | | [allocator](../memory/allocator "cpp/memory/allocator") | the default allocator (class template) | | [scoped\_allocator\_adaptor](../memory/scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor") (C++11) | implements multi-level allocator for multi-level containers (class template) | | [polymorphic\_allocator](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator") (C++17) | an allocator that supports run-time polymorphism based on the `[std::pmr::memory\_resource](../memory/memory_resource "cpp/memory/memory resource")` it is constructed with (class template) | ### Examples Demonstrates a C++11 allocator, except for `[[nodiscard]]` added to match C++20 style. ``` #include <cstdlib> #include <new> #include <limits> #include <iostream> #include <vector> template <class T> struct Mallocator { typedef T value_type; Mallocator () = default; template <class U> constexpr Mallocator (const Mallocator <U>&) noexcept {} [[nodiscard]] T* allocate(std::size_t n) { if (n > std::numeric_limits<std::size_t>::max() / sizeof(T)) throw std::bad_array_new_length(); if (auto p = static_cast<T*>(std::malloc(n*sizeof(T)))) { report(p, n); return p; } throw std::bad_alloc(); } void deallocate(T* p, std::size_t n) noexcept { report(p, n, 0); std::free(p); } private: void report(T* p, std::size_t n, bool alloc = true) const { std::cout << (alloc ? "Alloc: " : "Dealloc: ") << sizeof(T)*n << " bytes at " << std::hex << std::showbase << reinterpret_cast<void*>(p) << std::dec << '\n'; } }; template <class T, class U> bool operator==(const Mallocator <T>&, const Mallocator <U>&) { return true; } template <class T, class U> bool operator!=(const Mallocator <T>&, const Mallocator <U>&) { return false; } int main() { std::vector<int, Mallocator<int>> v(8); v.push_back(42); } ``` Possible output: ``` Alloc: 32 bytes at 0x2020c20 Alloc: 64 bytes at 0x2023c60 Dealloc: 32 bytes at 0x2020c20 Dealloc: 64 bytes at 0x2023c60 ``` ### 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 179](https://cplusplus.github.io/LWG/issue179) | C++98 | `pointer` and `const_pointer` were not required to be comparable with each other | required | | [P0593R6](https://wg21.link/P0593R6) | C++98 | `allocate` were not required to create an array object in the storage it allocated | required | | [LWG 2016](https://cplusplus.github.io/LWG/issue2016) | C++11 | the copy, move and swap operations of allocator might be throwing when used | required to be non-throwing | | [LWG 2108](https://cplusplus.github.io/LWG/issue2108) | C++11 | there was no way to show an allocator is stateless | `is_always_equal` provided | | [LWG 2263](https://cplusplus.github.io/LWG/issue2263) | C++11 | resolution of LWG179 was accidently dropped in C++11and not generalized to `void_pointer` and `const_void_pointer` | restored and generalized | | [LWG 2593](https://cplusplus.github.io/LWG/issue2593) | C++11 | moving from an allocator might modify its value | modification forbidden |
programming_docs
cpp C++ named requirements: Compare C++ named requirements: Compare =============================== **Compare** is a set of requirements expected by some of the standard library facilities from the user-provided function object types. The return value of the function call operation applied to an object of a type satisfying Compare, when [contextually converted](../language/implicit_conversion "cpp/language/implicit conversion") to `bool`, yields `true` if the first argument of the call appears before the second in the *strict weak ordering relation* induced by this type, and `false` otherwise. As with any [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate"), evaluation of that expression is not allowed to call non-const functions through the dereferenced iterators and, syntactically, the function call operation must accept `const` object arguments, with the same behavior regardless of whether the arguments are `const` or non-`const` (since C++20). ### Requirements The type `T` satisfies Compare if. * The type `T` satisfies [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate"), and Given. * `comp`, an object of type `T` * `equiv(a, b)`, an expression equivalent to `!comp(a, b) && !comp(b, a)` The following expressions must be valid and have their specified effects. | Expression | Return type | Requirements | | --- | --- | --- | | `comp(a, b)` | [implicitly convertible](../language/implicit_cast "cpp/language/implicit cast") to `bool` | Establishes [strict weak ordering](https://en.wikipedia.org/wiki/Strict_weak_ordering "enwiki:Strict weak ordering") relation with the following properties * For all `a`, `comp(a,a)==false` * If `comp(a,b)==true` then `comp(b,a)==false` * if `comp(a,b)==true` and `comp(b,c)==true` then `comp(a,c)==true` | | `equiv(a, b)` | `bool` | Establishes equivalence relationship with the following properties * For all `a`, `equiv(a,a)==true` * If `equiv(a,b)==true`, then `equiv(b,a)==true` * If `equiv(a,b)==true` and `equiv(b,c)==true`, then `equiv(a,c)==true` | Note: `comp` induces a *strict total ordering* on the equivalence classes determined by `equiv`. ### Standard library The following standard library facilities expect a Compare type. | | | | --- | --- | | [set](../container/set "cpp/container/set") | collection of unique keys, sorted by keys (class template) | | [map](../container/map "cpp/container/map") | collection of key-value pairs, sorted by keys, keys are unique (class template) | | [multiset](../container/multiset "cpp/container/multiset") | collection of keys, sorted by keys (class template) | | [multimap](../container/multimap "cpp/container/multimap") | collection of key-value pairs, sorted by keys (class template) | | [priority\_queue](../container/priority_queue "cpp/container/priority queue") | adapts a container to provide priority queue (class template) | | [sort](../algorithm/sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [sort](../container/forward_list/sort "cpp/container/forward list/sort") (C++11) | sorts the elements (public member function of `std::forward_list<T,Allocator>`) | | [sort](../container/list/sort "cpp/container/list/sort") | sorts the elements (public member function of `std::list<T,Allocator>`) | | [stable\_sort](../algorithm/stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [partial\_sort](../algorithm/partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | | [partial\_sort\_copy](../algorithm/partial_sort_copy "cpp/algorithm/partial sort copy") | copies and partially sorts a range of elements (function template) | | [is\_sorted](../algorithm/is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | | [is\_sorted\_until](../algorithm/is_sorted_until "cpp/algorithm/is sorted until") (C++11) | finds the largest sorted subrange (function template) | | [nth\_element](../algorithm/nth_element "cpp/algorithm/nth element") | partially sorts the given range making sure that it is partitioned by the given element (function template) | | [lower\_bound](../algorithm/lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [upper\_bound](../algorithm/upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | | [binary\_search](../algorithm/binary_search "cpp/algorithm/binary search") | determines if an element exists in a partially-ordered range (function template) | | [equal\_range](../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | [merge](../algorithm/merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [merge](../container/forward_list/merge "cpp/container/forward list/merge") (C++11) | merges two sorted lists (public member function of `std::forward_list<T,Allocator>`) | | [merge](../container/list/merge "cpp/container/list/merge") | merges two sorted lists (public member function of `std::list<T,Allocator>`) | | [inplace\_merge](../algorithm/inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | | [includes](../algorithm/includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [set\_difference](../algorithm/set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | | [set\_intersection](../algorithm/set_intersection "cpp/algorithm/set intersection") | computes the intersection of two sets (function template) | | [set\_symmetric\_difference](../algorithm/set_symmetric_difference "cpp/algorithm/set symmetric difference") | computes the symmetric difference between two sets (function template) | | [set\_union](../algorithm/set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | | [push\_heap](../algorithm/push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [pop\_heap](../algorithm/pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [make\_heap](../algorithm/make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [sort\_heap](../algorithm/sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [is\_heap](../algorithm/is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](../algorithm/is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [max](../algorithm/max "cpp/algorithm/max") | returns the greater of the given values (function template) | | [max\_element](../algorithm/max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | | [min](../algorithm/min "cpp/algorithm/min") | returns the smaller of the given values (function template) | | [min\_element](../algorithm/min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | | [minmax](../algorithm/minmax "cpp/algorithm/minmax") (C++11) | returns the smaller and larger of two elements (function template) | | [minmax\_element](../algorithm/minmax_element "cpp/algorithm/minmax element") (C++11) | returns the smallest and the largest elements in a range (function template) | | [lexicographical\_compare](../algorithm/lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [next\_permutation](../algorithm/next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](../algorithm/prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | ### See also | | | | --- | --- | | [strict\_weak\_order](../concepts/strict_weak_order "cpp/concepts/strict weak order") (C++20) | specifies that a [`relation`](../concepts/relation "cpp/concepts/relation") imposes a strict weak ordering (concept) | | [**Comparison operators**](../language/operator_comparison "cpp/language/operator comparison") | `<`, `<=`, `>`, `>=`, `==`, `!=`, and `<=>` (C++20), compare the arguments | cpp C++ named requirements: RandomNumberDistribution C++ named requirements: RandomNumberDistribution ================================================ A **RandomNumberDistribution** is a function object returning random numbers according to a [probability density function](https://en.wikipedia.org/wiki/Probability_density_function "enwiki:Probability density function") p(x) or a [discrete probability distribution](https://en.wikipedia.org/wiki/Discrete_probability_distribution "enwiki:Discrete probability distribution") P(x i). ### Requirements The type `D` satisfies RandomNumberDistribution if. * `D` satisfies [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * `D` satisfies [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") Given. * `T`, the type named by `D::result_type` * `P`, the type named by `D::param_type`, which + satisfies [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") + satisfies [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") + satisfies [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") + has a constructor taking identical arguments as each of the constructors of `D` that take arguments corresponding to the distribution parameters. + has a member function with the identical name, type, and semantics, as every member function of `D` that returns a parameter of the distribution + declares a member typedef `using distribution_type = D;` * `d`, a value of type `D` * `x` and `y`, (possibly const) values of type `D` * `p`, a (possibly const) value of type `P` * `g`, `g1`, `g2`, lvalues of a type satisfying [UniformRandomBitGenerator](uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") * `os`, lvalue of a specialization of `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` * `is`, lvalue of a specialization of `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` The following expressions must be valid and have their specified effects. | Expression | Type | Notes | Complexity | | --- | --- | --- | --- | | `D::result_type` | `T` | An [arithmetic type](../language/type "cpp/language/type") | compile-time | | `D::param_type` | `P` | | compile-time | | `D()` | | creates a distribution indistinguishable from any other default-constructed `D` | constant | | `D(p)` | | creates a distribution indistinguishable from `D` constructed directly from the values used to construct `p` | Same as `p`'s construction | | `d.reset()` | `void` | Resets the internal state of the distribution. The next call to `operator()` on `d` will not depend on values produced by any engine prior to `reset()`. | constant | | `x.param()` | `P` | Returns `p` such that `D(p).param() == p` | No worse than `D(p)` | | `d.param(p)` | `void` | Postcondition: `d.param() == p` | No worse than `D(p)` | | `d(g)` | `T` | The sequence of numbers returned by successive invocations of this call with the same `g` are randomly distributed according to the distribution parametrized by `d.param()` | Amortized constant number of invocations of `g` | | `d(g,p)` | `T` | The sequence of numbers returned by successive invocations of this call with the same `g` are randomly distributed according to the distribution parametrized by `p` | Amortized constant number of invocations of `g` | | `x.min()` | `T` | the greatest lower bound on the values potentially returned by `x`’s `operator()`, as determined by the current values of `x`’s parameters | constant | | `x.max()` | `T` | the least upper bound on the values potentially returned by `x`’s `operator()`, as determined by the current values of `x`’s parameters | constant | | `x == y` | `bool` | Establishes an equivalence relation. Returns `true` if `x.param() == y.param()` and future infinite sequences of values that would be generated by repeated invocations of `x(g1)` and `y(g2)` would be equal as long as `g1 == g2`. | constant | | `x != y` | `bool` | `!(x == y)` | constant | | `os << x` | Reference to the type of `os` | Writes a textual representation of the distribution parameters and internal state to `os`. The formatting flags and fill character of `os` are unchanged. | | | `is >> d` | Reference to the type of `is` | Restores the distribution parameters and internal state with data read from `is`. The formatting flags of `is` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` stream template parameters, otherwise the behavior is undefined. If bad input is encountered, `is.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. | | ### Notes The parameters of a distribution object may be changed either permanently, by using `d.param(p)` or just for the duration of a single operator() call, by using `d(g,p)`. Calls to const member functions of the distribution and `os << d` do not affect the sequence of numbers produced by repeated `d(g)`. ### Standard library The following standard library components satisfy RandomNumberDistribution. | | | | --- | --- | | [uniform\_int\_distribution](../numeric/random/uniform_int_distribution "cpp/numeric/random/uniform int distribution") (C++11) | produces integer values evenly distributed across a range (class template) | | [uniform\_real\_distribution](../numeric/random/uniform_real_distribution "cpp/numeric/random/uniform real distribution") (C++11) | produces real values evenly distributed across a range (class template) | | [bernoulli\_distribution](../numeric/random/bernoulli_distribution "cpp/numeric/random/bernoulli distribution") (C++11) | produces `bool` values on a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution "enwiki:Bernoulli distribution"). (class) | | [binomial\_distribution](../numeric/random/binomial_distribution "cpp/numeric/random/binomial distribution") (C++11) | produces integer values on a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution "enwiki:Binomial distribution"). (class template) | | [negative\_binomial\_distribution](../numeric/random/negative_binomial_distribution "cpp/numeric/random/negative binomial distribution") (C++11) | produces integer values on a [negative binomial distribution](https://en.wikipedia.org/wiki/Negative_binomial_distribution "enwiki:Negative binomial distribution"). (class template) | | [geometric\_distribution](../numeric/random/geometric_distribution "cpp/numeric/random/geometric distribution") (C++11) | produces integer values on a [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution "enwiki:Geometric distribution"). (class template) | | [poisson\_distribution](../numeric/random/poisson_distribution "cpp/numeric/random/poisson distribution") (C++11) | produces integer values on a [poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution "enwiki:Poisson distribution"). (class template) | | [exponential\_distribution](../numeric/random/exponential_distribution "cpp/numeric/random/exponential distribution") (C++11) | produces real values on an [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution "enwiki:Exponential distribution"). (class template) | | [gamma\_distribution](../numeric/random/gamma_distribution "cpp/numeric/random/gamma distribution") (C++11) | produces real values on an [gamma distribution](https://en.wikipedia.org/wiki/Gamma_distribution "enwiki:Gamma distribution"). (class template) | | [weibull\_distribution](../numeric/random/weibull_distribution "cpp/numeric/random/weibull distribution") (C++11) | produces real values on a [Weibull distribution](https://en.wikipedia.org/wiki/Weibull_distribution "enwiki:Weibull distribution"). (class template) | | [extreme\_value\_distribution](../numeric/random/extreme_value_distribution "cpp/numeric/random/extreme value distribution") (C++11) | produces real values on an [extreme value distribution](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution "enwiki:Generalized extreme value distribution"). (class template) | | [normal\_distribution](../numeric/random/normal_distribution "cpp/numeric/random/normal distribution") (C++11) | produces real values on a [standard normal (Gaussian) distribution](https://en.wikipedia.org/wiki/Normal_distribution "enwiki:Normal distribution"). (class template) | | [lognormal\_distribution](../numeric/random/lognormal_distribution "cpp/numeric/random/lognormal distribution") (C++11) | produces real values on a [lognormal distribution](https://en.wikipedia.org/wiki/Lognormal_distribution "enwiki:Lognormal distribution"). (class template) | | [chi\_squared\_distribution](../numeric/random/chi_squared_distribution "cpp/numeric/random/chi squared distribution") (C++11) | produces real values on a [chi-squared distribution](https://en.wikipedia.org/wiki/Chi-squared_distribution "enwiki:Chi-squared distribution"). (class template) | | [cauchy\_distribution](../numeric/random/cauchy_distribution "cpp/numeric/random/cauchy distribution") (C++11) | produces real values on a [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution "enwiki:Cauchy distribution"). (class template) | | [fisher\_f\_distribution](../numeric/random/fisher_f_distribution "cpp/numeric/random/fisher f distribution") (C++11) | produces real values on a [Fisher's F-distribution](https://en.wikipedia.org/wiki/F-distribution "enwiki:F-distribution"). (class template) | | [student\_t\_distribution](../numeric/random/student_t_distribution "cpp/numeric/random/student t distribution") (C++11) | produces real values on a [Student's t-distribution](https://en.wikipedia.org/wiki/Student%27s_t-distribution "enwiki:Student's t-distribution"). (class template) | | [discrete\_distribution](../numeric/random/discrete_distribution "cpp/numeric/random/discrete distribution") (C++11) | produces random integers on a discrete distribution. (class template) | | [piecewise\_constant\_distribution](../numeric/random/piecewise_constant_distribution "cpp/numeric/random/piecewise constant distribution") (C++11) | produces real values distributed on constant subintervals. (class template) | | [piecewise\_linear\_distribution](../numeric/random/piecewise_linear_distribution "cpp/numeric/random/piecewise linear distribution") (C++11) | produces real values distributed on defined subintervals. (class template) | cpp C++ named requirements: LegacyForwardIterator C++ named requirements: LegacyForwardIterator ============================================= A **LegacyForwardIterator** is a [LegacyIterator](iterator "cpp/named req/Iterator") that can read data from the pointed-to element. Unlike [LegacyInputIterator](inputiterator "cpp/named req/InputIterator") and [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator"), it can be used in multipass algorithms. If a **LegacyForwardIterator** `it` originates from a [Container](container "cpp/named req/Container"), then `it`'s `value_type` is the same as the container's, so dereferencing (`*it`) obtains the container's `value_type`. ### Requirements The type `It` satisfies LegacyForwardIterator if. * The type `It` satisfies [LegacyInputIterator](inputiterator "cpp/named req/InputIterator") * The type `It` satisfies [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") * Objects of the type `It` provide *multipass guarantee* described below * The type `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::reference` must be either * a reference to `T` if `It` satisfies [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") (`It` is mutable), or * a reference to `const T` otherwise (`It` is constant), (where `T` is the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::value\_type`) * Equality and inequality comparison is defined over all iterators for the same underlying sequence and the value initialized-iterators (since C++14). And, given. * `i`, dereferenceable iterator of type `It` * `reference,` the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::reference` The following expressions must be valid and have their specified effects. | Expression | Return type | Equivalent expression | | --- | --- | --- | | `i++` | `It` | `It ip=i; ++i; return ip;` | | `*i++` | `reference` | | A *mutable* LegacyForwardIterator is a LegacyForwardIterator that additionally satisfies the [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") requirements. ### Multipass guarantee Given `a` and `b`, dereferenceable iterators of type `It`. * If `a` and `b` compare equal (`a == b` is contextually convertible to `true`) then either they are both non-dereferenceable or `*a` and `*b` are references bound to the same object. * If `*a` and `*b` refer to the same object, then `a == b`. * Assignment through a mutable `ForwardIterator` iterator cannot invalidate the iterator (implicit due to `reference` defined as a true reference). * Incrementing a copy of `a` does not change the value read from `a` (formally, either `It` is a raw pointer type or the expression `(void)++It(a), *a` is equivalent to the expression `*a`). * `a == b` implies `++a == ++b`. | | | | --- | --- | | Singular iterators A [value-initialized](../language/value_initialization "cpp/language/value initialization") LegacyForwardIterator behaves like the past-the-end iterator of some unspecified empty container: it compares equal to all value-initialized LegacyForwardIterators of the same type. | (since C++14) | | | | | | | | --- | --- | --- | --- | --- | | Concept For the definition of `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")`, the following exposition-only concept is defined. | | | | | --- | --- | --- | | ``` template<class It> concept __LegacyForwardIterator = __LegacyInputIterator<It> && std::constructible_from<It> && std::is_lvalue_reference_v<std::iter_reference_t<It>> && std::same_as< std::remove_cvref_t<std::iter_reference_t<It>>, typename std::indirectly_readable_traits<It>::value_type> && requires(It it) { { it++ } -> std::convertible_to<const It&>; { *it++ } -> std::same_as<std::iter_reference_t<It>>; }; ``` | | | where the exposition-only concept `__LegacyInputIterator<T>` is described in [LegacyInputIterator#Concept](inputiterator#Concept "cpp/named req/InputIterator"). Note that whilst LegacyForwardIterator allows for iterators to have their reference types being rvalue reference types, this concept does not. And so it is important for such iterators (e.g. `[std::move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator")`) to explicitly specify their `It::iterator_category` to be `[std::forward\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` (or stronger iterator category tags), as `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::iterator\_category` would be incorrectly deduced as `[std::input\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` otherwise. | (since C++20) | ### See also | | | | --- | --- | | [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) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions |
programming_docs
cpp C++ named requirements: TransformationTrait C++ named requirements: TransformationTrait =========================================== A **TransformationTrait** is a class template that provides a transformation of its template type parameter. ### Requirements * Takes one template type parameter (additional template parameters are optional and allowed) * The transformed type is a publicly accessible nested type named `type` ### Standard library The [type modifications and transformations](../types#Type_modifications "cpp/types") all satisfy **TransformationTrait**. The following standard library class templates also satisfy **TransformationTrait**. | | | | --- | --- | | [std::tuple\_element<std::tuple>](../utility/tuple/tuple_element "cpp/utility/tuple/tuple element") (C++11) | obtains the type of the specified element (class template specialization) | | [std::tuple\_element<std::pair>](../utility/pair/tuple_element "cpp/utility/pair/tuple element") (C++11) | obtains the type of the elements of `pair` (class template specialization) | | [std::tuple\_element<std::array>](../container/array/tuple_element "cpp/container/array/tuple element") (C++11) | obtains the type of the elements of `array` (class template specialization) | | [variant\_alternativevariant\_alternative\_t](../utility/variant/variant_alternative "cpp/utility/variant/variant alternative") (C++17) | obtains the type of the alternative specified by its index, at compile time (class template) (alias template) | cpp C++ named requirements: LegacyInputIterator C++ named requirements: LegacyInputIterator =========================================== A **LegacyInputIterator** is a [LegacyIterator](iterator "cpp/named req/Iterator") that can read from the pointed-to element. LegacyInputIterators only guarantee validity for single pass algorithms: once a LegacyInputIterator `i` has been incremented, all copies of its previous value may be invalidated. ### Requirements The type `It` satisfies LegacyInputIterator if. * The type `It` satisfies [LegacyIterator](iterator "cpp/named req/Iterator") * The type `It` satisfies [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") And, given. * `i` and `j`, values of type `It` or `const It` * `reference`, the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::reference` * `value_type`, the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::value\_type` The following expressions must be valid and have their specified effects. | Expression | Return type | Equivalent expression | Notes | | --- | --- | --- | --- | | `i != j` | contextually convertible to `bool` | `!(i == j)` | **Precondition**: `(i, j)` is in the domain of `==`. | | `*i` | `reference`, convertible to `value_type` | If `i == j` and `(i, j)` is in the domain of `==` then this is equivalent to `*j`. | **Precondition**: `i` is dereferenceable. The expression `(void)*i, *i` is equivalent to `*i`. | | `i->m` | | `(*i).m` | **Precondition**: `i` is dereferenceable. | | `++i` | `It&` | | **Precondition**: `i` is dereferenceable. **Postcondition**: `i` is dereferenceable or `i` is past-the-end. **Postcondition**: Any copies of the previous value of `i` are no longer required to be either dereferenceable or to be in the domain of `==`. | | `(void)i++` | | `(void)++i` | | | `*i++` | convertible to `value_type` | `value_type x = *i; ++i; return x;` | | ### Notes "in the domain of `==`" means equality comparison is defined between the two iterator values. For input iterators, equality comparison does not need to be defined for all values, and the set of the values in the domain of `==` may change over time. The `reference` type for an input iterator that is not also a [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator") does not have to be a reference type: dereferencing an input iterator may return a proxy object or `value_type` itself by value (as in the case of [`std::istreambuf_iterator`](../iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator")). | | | | | | | --- | --- | --- | --- | --- | | Concept For the definition of `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")`, the following exposition-only concept is defined. | | | | | --- | --- | --- | | ``` template<class I> concept __LegacyInputIterator = __LegacyIterator<I> && std::equality_comparable<I> && requires(I i) { typename std::incrementable_traits<I>::difference_type; typename std::indirectly_readable_traits<I>::value_type; typename std::common_reference_t<std::iter_reference_t<I>&&, typename std::indirectly_readable_traits<I>::value_type&>; *i++; typename std::common_reference_t<decltype(*i++)&&, typename std::indirectly_readable_traits<I>::value_type&>; requires std::signed_integral<typename std::incrementable_traits<I>::difference_type>; }; ``` | | | where the exposition-only concept `__LegacyIterator` is described in [LegacyIterator#Concept](iterator#Concept "cpp/named req/Iterator"). | (since 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 98](https://cplusplus.github.io/LWG/issue98) | C++98 | the return type of `*i++` was `value_type` | it can be any type convertible to `value_type` | ### 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) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions | cpp C++ named requirements: Mutex C++ named requirements: Mutex ============================= The **Mutex** requirements extends the [Lockable](lockable "cpp/named req/Lockable") requirements to include inter-thread synchronization. ### Requirements * [Lockable](lockable "cpp/named req/Lockable") * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") * [Destructible](destructible "cpp/named req/Destructible") * not copyable * not movable For an object `m` of Mutex type: * The expression `m.lock()` has the following properties * Behaves as an atomic operation. * Blocks the calling thread until exclusive ownership of the mutex can be obtained. * Prior `m.unlock()` operations on the same mutex *synchronize-with* this lock operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) * The behavior is undefined if the calling thread already owns the mutex (except if m is `[std::recursive\_mutex](../thread/recursive_mutex "cpp/thread/recursive mutex")` or `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")`) * Exception of type `[std::system\_error](../error/system_error "cpp/error/system error")` may be thrown on errors, with the following error codes: + `[std::errc::operation\_not\_permitted](../error/errc "cpp/error/errc")` if the calling thread does not have required privileges + `[std::errc::resource\_deadlock\_would\_occur](../error/errc "cpp/error/errc")` if the implementation detects that this operation would lead to deadlock | | | | --- | --- | | * `[std::errc::device\_or\_resource\_busy](../error/errc "cpp/error/errc")` if the mutex is already locked | (until C++17) | * The expression `m.try_lock()` has the following properties + Behaves as an atomic operation. + Attempts to obtain exclusive ownership of the mutex for the calling thread without blocking. If ownership is not obtained, returns immediately. The function is allowed to spuriously fail and return even if the mutex is not currently owned by another thread. + If `try_lock()` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). `lock()` does not synchronize with a failed `try_lock()` + Does not throw exceptions. * The expression `m.unlock()` has the following properties + Behaves as an atomic operation. + Releases the calling thread's ownership of the mutex and *synchronizes-with* the subsequent successful lock operations on the same object. + The behavior is undefined if the calling thread does not own the mutex. + Does not throw exceptions. * All lock and unlock operations on a single mutex occur in a single total order that can be viewed as [modification order](../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual mutex. ### Library types The following standard library types satisfy **Mutex**: * `[std::mutex](../thread/mutex "cpp/thread/mutex")` * `[std::recursive\_mutex](../thread/recursive_mutex "cpp/thread/recursive mutex")` * `[std::timed\_mutex](../thread/timed_mutex "cpp/thread/timed mutex")` * `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")` * `[std::shared\_mutex](../thread/shared_mutex "cpp/thread/shared mutex")` ### See also * [Thread support library](../thread "cpp/thread") * [Lockable](lockable "cpp/named req/Lockable") * [TimedMutex](timedmutex "cpp/named req/TimedMutex") cpp C++ named requirements: RandomNumberEngine C++ named requirements: RandomNumberEngine ========================================== A random number engine is a function object returning unsigned integer values such that each value in the range of possible results has (ideally) equal probability. Any random number engine is also a [UniformRandomBitGenerator](uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"), and therefore may be plugged into any [random number distribution](../numeric/random "cpp/numeric/random") in order to obtain a random number (formally, a random variate). ### Requirements A type `E` satisfying [UniformRandomBitGenerator](uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") will additionally satisfy RandomNumberEngine if, given. * `T`, the type named by `E::result_type` * `s`, a value of type `T` * `e`, a non-const value of type `E` * `v`, an lvalue of type `E` * `x` and `y`, possibly const values of type `E` * `q`, a lvalue of some type satisfying [SeedSequence](seedsequence "cpp/named req/SeedSequence") * `z`, a value of type `unsigned long long` * `os`, an output stream * `is`, an input stream the following expressions are valid and have their specified effects: | Expression | Return type | Requirements | | --- | --- | --- | | `E()` | | Creates an engine with the same state as all other default-constructed engines of type `E`. | | `E(x)` | | Creates an engine with the same state as `x`. | | `E(s)` | | Creates an engine whose initial state is determined by the integer `s`. | | `E(q)` | | Creates an engine whose initial state is determined by a single call to `q.generate`. | | `e.seed()` | `void` | Sets `e == E()`. | | `e.seed(s)` | `void` | Sets `e == E(s)`. | | `e.seed(q)` | `void` | Sets `e == E(q)`. | | `e()` | `T` | Returns a value in the closed interval `[E::min(), E::max()]`. Has amortized constant complexity. | | `e.discard(z)` | `void` | Advances `e`'s state as if by `z` consecutive calls to `e()`. | | `x == y` | `bool` | `true` if `x` and `y` are in the same state (such that repeated future calls to `x()` and `y()` will produce identical sequences). Otherwise, `false`. | | `x != y` | `bool` | `!(x == y)` | | `os << x` | `decltype(os)&` | Writes to `os` the textual representation of `x`'s current state. In the output, adjacent numbers are separated by one or more space characters. If `os`'s fmtflags are not set to `ios_base::dec|ios_base::left`, the behavior may be undefined. | | `is >> v` | `decltype(is)&` | Reads from `is` the textual representation of `v`'s current state, such that if that state was previously written via `os << x`, then `x == v`. If `is`'s fmtflags are not set to `ios_base::dec`, the behavior may be undefined. | ### Standard library The following standard library facilities satisfy RandomNumberEngine: | | | | --- | --- | | [linear\_congruential\_engine](../numeric/random/linear_congruential_engine "cpp/numeric/random/linear congruential engine") (C++11) | implements [linear congruential](https://en.wikipedia.org/wiki/Linear_congruential_generator "enwiki:Linear congruential generator") algorithm (class template) | | [mersenne\_twister\_engine](../numeric/random/mersenne_twister_engine "cpp/numeric/random/mersenne twister engine") (C++11) | implements [Mersenne twister](https://en.wikipedia.org/wiki/Mersenne_twister "enwiki:Mersenne twister") algorithm (class template) | | [subtract\_with\_carry\_engine](../numeric/random/subtract_with_carry_engine "cpp/numeric/random/subtract with carry engine") (C++11) | implements a subtract-with-carry ( [lagged Fibonacci](https://en.wikipedia.org/wiki/Lagged_Fibonacci_generator "enwiki:Lagged Fibonacci generator")) algorithm (class template) | | [discard\_block\_engine](../numeric/random/discard_block_engine "cpp/numeric/random/discard block engine") (C++11) | discards some output of a random number engine (class template) | | [independent\_bits\_engine](../numeric/random/independent_bits_engine "cpp/numeric/random/independent bits engine") (C++11) | packs the output of a random number engine into blocks of a specified number of bits (class template) | | [shuffle\_order\_engine](../numeric/random/shuffle_order_engine "cpp/numeric/random/shuffle order engine") (C++11) | delivers the output of a random number engine in a different order (class template) | The following standard library facilities satisfy [UniformRandomBitGenerator](uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") but not RandomNumberEngine: | | | | --- | --- | | [random\_device](../numeric/random/random_device "cpp/numeric/random/random device") (C++11) | non-deterministic random number generator using hardware entropy source (class) | cpp C++ named requirements: LegacyRandomAccessIterator C++ named requirements: LegacyRandomAccessIterator ================================================== A **LegacyRandomAccessIterator** is a [LegacyBidirectionalIterator](bidirectionaliterator "cpp/named req/BidirectionalIterator") that can be moved to point to any element in constant time. If a **LegacyRandomAccessIterator** `it` originates from a [Container](container "cpp/named req/Container"), then `it`'s `value_type` is the same as the container's, so dereferencing (`*it`) obtains the container's `value_type`. A pointer to an element of an array satisfies all requirements of LegacyRandomAccessIterator. ### Requirements The type `It` satisfies LegacyRandomAccessIterator if. * The type `It` satisfies [LegacyBidirectionalIterator](bidirectionaliterator "cpp/named req/BidirectionalIterator") And, given. * `value_type`, the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::value\_type` * `difference_type`, the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::difference\_type` * `reference`, the type denoted by `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::reference` * `i`, `a`, `b`, objects of type `It` or `const It` * `r`, a value of type `It&` * `n`, an integer of type `difference_type` The following expressions must be valid and have their specified effects. | Expression | Return type | Operational semantics | Notes | | --- | --- | --- | --- | | `r += n` | `It&` | `difference_type m = n; if (m >= 0) while (m--) ++r; else while (m++) --r; return r;` | * `n` can be both positive or negative * The complexity is constant (that is, the implementation cannot actually execute the while loop shown in operational semantics) | | `a + n` `n + a`. | `It` | `It temp = a; return temp += n;` | * `n` can be both positive or negative * `a + n == n + a` | | `r -= n` | `It&` | `return r += -n;` | The absolute value of `n` must be within the range of representable values of `difference_type`. | | `i - n` | `It` | `It temp = i; return temp -= n;` | | | `b - a` | `difference_type` | `return n;` | Precondition:* there exists a value `n` of type `difference_type` such that `a+n==b` Postcondition:* `b == a + (b - a)`. | | `i[n]` | convertible to `reference` | `*(i + n)` | | | `a < b` | contextually convertible to `bool` | Equivalent to `return b - a > 0;` | Precondition: * same as of `b - a` Strict total ordering relation:* `!(a < a)` * if `a < b` then `!(b < a)` * if `a < b` and `b < c` then `a < c` * `a < b` or `b < a` or `a == b` (exactly one of the expressions is true) | | `a > b` | contextually convertible to `bool` | `b < a` | Total ordering relation opposite to `a < b` | | `a >= b` | contextually convertible to `bool` | `!(a < b)` | | | `a <= b` | contextually convertible to `bool` | `!(a > b)` | | The above rules imply that LegacyRandomAccessIterator also implements [LessThanComparable](lessthancomparable "cpp/named req/LessThanComparable"). A *mutable* LegacyRandomAccessIterator is a LegacyRandomAccessIterator that additionally satisfies the [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") requirements. | | | | | | | --- | --- | --- | --- | --- | | Concept For the definition of `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")`, the following exposition-only concept is defined. | | | | | --- | --- | --- | | ``` template<class I> concept __LegacyRandomAccessIterator = __LegacyBidirectionalIterator<I> && std::totally_ordered<I> && requires(I i, typename std::incrementable_traits<I>::difference_type n) { { i += n } -> std::same_as<I&>; { i -= n } -> std::same_as<I&>; { i + n } -> std::same_as<I>; { n + i } -> std::same_as<I>; { i - n } -> std::same_as<I>; { i - i } -> std::same_as<decltype(n)>; { i[n] } -> std::convertible_to<std::iter_reference_t<I>>; }; ``` | | | where the exposition-only concept `__LegacyBidirectionalIterator` is described in [LegacyBidirectionalIterator#Concept](bidirectionaliterator#Concept "cpp/named req/BidirectionalIterator"). | (since C++20) | ### See also | | | | --- | --- | | [random\_access\_iterator](../iterator/random_access_iterator "cpp/iterator/random access iterator") (C++20) | specifies that a [`bidirectional_iterator`](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") is a random-access iterator, supporting advancement in constant time and subscripting (concept) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions | cpp C++ named requirements: DefaultInsertable C++ named requirements: DefaultInsertable ========================================= Specifies that an instance of the type can be default-constructed in-place by a given allocator. ### Requirements The type `T` is **DefaultInsertable** into the [Container](container "cpp/named req/Container") `X` whose `value_type` is identical to `T` if, given. | | | | --- | --- | | `A` | an allocator type | | `m` | an lvalue of type `A` | | `p` | the pointer of type `T*` prepared by the container | where `X::allocator_type` is identical to `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<T>`, the following expression is well-formed: ``` std::allocator_traits<A>::construct(m, p); ``` If `X` is not allocator-aware or is a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specialization, the term is defined as if `A` were `std::allocator<T>`, except that no allocator object needs to be created, and user-defined specializations of `[std::allocator](../memory/allocator "cpp/memory/allocator")` are not instantiated. ### Notes By default, this will [value-initialize](../language/value_initialization "cpp/language/value initialization") the object, as by `::new((void*)p) T()` (until C++20)`[std::construct\_at](http://en.cppreference.com/w/cpp/memory/construct_at)(p)` (since C++20). If value-initialization is undesirable, for example, if the object is of non-class type and zeroing out is not needed, it can be avoided by providing a [custom `Allocator::construct`](http://stackoverflow.com/a/21028912/273767). Although it is required that customized `construct` is used when constructing elements of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice. ### See also | | | --- | | [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | | [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") | | [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") | | [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") | | [Erasable](erasable "cpp/named req/Erasable") |
programming_docs
cpp C++ named requirements: SequenceContainer C++ named requirements: SequenceContainer ========================================= A **SequenceContainer** is a [Container](container "cpp/named req/Container") that stores objects of the same type in a linear arrangement. ### Requirements The type `X` satisfies SequenceContainer if. * The type `X` satisfies [Container](container "cpp/named req/Container"), and Given. * `T`, the element type of `X` * `A`, the allocator type of `X`: `X::allocator_type` if it exists, otherwise `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>` * `a`, [rvalue](../language/value_category "cpp/language/value category") expression of type `X` * `p`, a valid const iterator into `a` * `q`, a valid dereferenceable const iterator into `a` * `q1` and `q2`, two const iterators into `a` such that `[q1, q2)` is a valid range * `i` and `j`, [LegacyInputIterators](inputiterator "cpp/named req/InputIterator") such that `[i, j)` is a valid range and that the iterators refer to elements implicitly convertible to `value_type` * `il`, an object of type `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<value_type>` * `n`, a value of type `X::size_type` * `t`, an lvalue or const rvalue of type `X::value_type` * `rv`, a non-const rvalue of type `X::value_type` * `Args`: a template parameter pack * `args`: a function parameter pack with the pattern `Arg&&` The following expressions must be valid and have their specified effects for all sequence containers except `[std::array](../container/array "cpp/container/array")`: | expression | return type | effects | precondition | postcondition | | --- | --- | --- | --- | --- | | `X(n, t)` `X a(n, t)`. | | Constructs the sequence container holding `n` copies of `t` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` | `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(),end()) == n` | | `X(i, j)` `X a(i, j)`. | | Constructs the sequence container equal, element-wise, to the range `[i,j)` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") from `*i` into `X` (only for std::vector) If the iterators are not [LegacyForwardIterators](forwarditerator "cpp/named req/ForwardIterator"), T must be [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable"). | `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(),end()) == [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(i,j)` | | `X(il)` | | `X(il.begin(), il.end())` | | | | `a = il` | `X&` | Assigns the range represented by `il` into `a`[[1]](#cite_note-1) | T is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") and [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") | Existing elements of `a` are destroyed or assigned to | | `a.emplace(p,args)` | `iterator` | Insert an object of type `T`, constructed with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)` before `p` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") (for std::vector and std::deque) `T` is [MoveAssignable](moveassignable "cpp/named req/MoveAssignable") and [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable"). | Returned iterator points at the element constructed from `args` into `a` | | `a.insert(p,t)` | `iterator` | Inserts a copy of `t` before `p` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") (for std::vector and std::deque) `T` is [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") or [MoveAssignable](moveassignable "cpp/named req/MoveAssignable"). | Returned iterator points at the copy of `t` inserted into `a` | | `a.insert(p,rv)` | `iterator` | Inserts a copy of `rv` before `p`, possibly using move semantics | `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") (for std::vector and std::deque) `T` is [MoveAssignable](moveassignable "cpp/named req/MoveAssignable"). | Returned iterator points at the copy of `rv` inserted into `a` | | `a.insert(p,n,t)` | `iterator` | Inserts `n` copies of `t` before `p` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") and [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") | Returned iterator points at the copy of the first element inserted into `a` or is `p` for `n==0` | | `a.insert(p,i,j)` | `iterator` | Inserts copies of elements in `[i, j)` before `p` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") and `i` and `j` are not in `a` (only for std::vector) If the iterators are not [LegacyForwardIterators](forwarditerator "cpp/named req/ForwardIterator"), T must be [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") and [MoveAssignable](moveassignable "cpp/named req/MoveAssignable"). | Each iterator in `[i,j)` is dereferenced once. Returned iterator points at the copy of the first element inserted into `a` or is `p` for `i==j` | | `a.insert(p, il)` | `iterator` | `a.insert(p,il.begin(),il.end())` | | Returned iterator points at the copy of the first element inserted into `a` or is `p` if `il` is empty. | | `a.erase(q)` | `iterator` | Erases the element pointed to by `q` | (std::deque, std::vector) `T` is [MoveAssignable](moveassignable "cpp/named req/MoveAssignable") | Returned iterator points at the element that was immediately following `q` prior to erasure, or `a.end()` if no such element exists. | | `a.erase(q1,q2)` | `iterator` | Erases elements in `[q1,q2)` | (std::deque, std::vector) `T` is [MoveAssignable](moveassignable "cpp/named req/MoveAssignable") | Returned iterator points at the element that was pointed by `q2` prior to any erasure, or `a.end()` if no such element exists. | | `a.clear()` | `void` | Destroys all elements in `a` | | All references, pointers, and iterators are invalidated, including the end iterator. `a.empty() == true`. | | `a.assign(i,j)` | `void` | Replaces elements in a with a copy of `[i, j)` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") and `i`, `j` not in `a` (std::vector) If not [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator"). `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable"). | Each iterator in `[i,j)` is dereferenced once | | `a.assign(il)` | `void` | `a.assign(il.begin(),il.end())` | | | | `a.assign(n,t)` | `void` | Replaces elements in `a` with `n` copies of `t` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") and [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") | | | notes | | 1. `[std::array](../container/array "cpp/container/array")` supports assignment from a braced-init-list, but not from an `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` | The following expressions must be valid and have their specified effects for the sequence containers named: | expression | return type | effects | preconditions | containers | | --- | --- | --- | --- | --- | | `a.front()` | `reference` `const_reference` for const a. | Equivalent to `*a.begin()` | | (all) | | `a.back()` | `reference` `const_reference` for const a. | Equivalent to `{ auto tmp = a.end(); --tmp; return *tmp; }` | | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::array](../container/array "cpp/container/array")` `[std::deque](../container/deque "cpp/container/deque")` `[std::list](../container/list "cpp/container/list")` `[std::vector](../container/vector "cpp/container/vector")` | | `a.emplace_front(args)` | `void` | Prepends a `T` constructed with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") into `X` from `args` | `[std::deque](../container/deque "cpp/container/deque")` `[std::forward\_list](../container/forward_list "cpp/container/forward list")` `[std::list](../container/list "cpp/container/list")` | | `a.emplace_back(args)` | `void` | Appends a `T` constructed with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...` | `T` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") into `X` from `args` (std::vector only) `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X`. | `[std::deque](../container/deque "cpp/container/deque")` `[std::list](../container/list "cpp/container/list")` `[std::vector](../container/vector "cpp/container/vector")` | | `a.push_front(t)` | `void` | Prepends a copy of `t` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` | `[std::deque](../container/deque "cpp/container/deque")` `[std::forward\_list](../container/forward_list "cpp/container/forward list")` `[std::list](../container/list "cpp/container/list")` | | `a.push_front(rv)` | `void` | Prepends a copy of `rv`, possibly using move semantics | `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X` | `[std::deque](../container/deque "cpp/container/deque")` `[std::forward\_list](../container/forward_list "cpp/container/forward list")` `[std::list](../container/list "cpp/container/list")` | | `a.push_back(t)` | `void` | Appends a copy of `t` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::deque](../container/deque "cpp/container/deque")` `[std::list](../container/list "cpp/container/list")` `[std::vector](../container/vector "cpp/container/vector")` | | `a.push_back(rv)` | `void` | Appends a copy of `rv`, possibly using move semantics | `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X` | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::deque](../container/deque "cpp/container/deque")` `[std::list](../container/list "cpp/container/list")` `[std::vector](../container/vector "cpp/container/vector")` | | `a.pop_front()` | `void` | Destroys the first element. | `a.empty() == false` | `[std::deque](../container/deque "cpp/container/deque")` `[std::forward\_list](../container/forward_list "cpp/container/forward list")` `[std::list](../container/list "cpp/container/list")` | | `a.pop_back()` | `void` | Destroys the last element | `a.empty() == false` | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::deque](../container/deque "cpp/container/deque")` `[std::list](../container/list "cpp/container/list")` `[std::vector](../container/vector "cpp/container/vector")` | | `a[n]` | `reference` `const_reference` for const a. | Equivalent to `*(n + a.begin())` | | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::array](../container/array "cpp/container/array")` `[std::deque](../container/deque "cpp/container/deque")` `[std::vector](../container/vector "cpp/container/vector")` | | `a.at(n)` | `reference` `const_reference` for const a. | Equivalent to `*(n + a.begin())`, except that `out_of_range` is thrown if `n>=size()` | | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` `[std::array](../container/array "cpp/container/array")` `[std::deque](../container/deque "cpp/container/deque")` `[std::vector](../container/vector "cpp/container/vector")` | Additionally, for every sequence container, the constructor template that takes two input iterators and the member function template overloads of `insert()`, `append()`, `assign()`, `replace()` that take two input iterators do not participate in overload resolution if the corresponding template argument does not satisfy [LegacyInputIterator](inputiterator "cpp/named req/InputIterator"). ### Sequence containers in the standard library | | | | --- | --- | | [basic\_string](../string/basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) | | [array](../container/array "cpp/container/array") (C++11) | static contiguous array (class template) | | [vector](../container/vector "cpp/container/vector") | dynamic contiguous array (class template) | | [deque](../container/deque "cpp/container/deque") | double-ended queue (class template) | | [forward\_list](../container/forward_list "cpp/container/forward list") (C++11) | singly-linked list (class template) | | [list](../container/list "cpp/container/list") | doubly-linked list (class template) | #### Trade-offs / usage notes | | | | --- | --- | | std::array | Fast access but fixed number of elements | | std::vector | Fast access but mostly inefficient insertions/deletions | | std::liststd::forward\_list | Efficient insertion/deletion in the middle of the sequence | | std::deque | Efficient insertion/deletion at the beginning and at the end of the sequence | cpp C++ named requirements: MoveAssignable (since C++11) C++ named requirements: MoveAssignable (since C++11) ==================================================== Specifies that an instance of the type can be assigned from an [rvalue](../language/value_category "cpp/language/value category") argument. ### Requirements The type `T` satisfies MoveAssignable if. Given. * `t`, a modifiable [lvalue expression](../language/value_category "cpp/language/value category") of type `T` * `rv`, an [rvalue](../language/value_category "cpp/language/value category") expression of type `T` The following expressions must be valid and have their specified effects. | Expression | Return type | Return value | Post-conditions | | --- | --- | --- | --- | | `t = rv` | `T&` | `t` | If `t` and `rv` do not refer to the same object , the value of `t` is equivalent to the value of `rv` before the assignment. The new value of `rv` is unspecified. | ### Notes The type does not have to implement [move assignment operator](../language/move_operator "cpp/language/move operator") in order to satisfy this type requirement: a [copy assignment operator](../language/as_operator "cpp/language/as operator") that takes its parameter by value or as a `const Type&`, will bind to rvalue argument. If a MoveAssignable class implements a move assignment operator, it may also implement [move semantics](../utility/move "cpp/utility/move") to take advantage of the fact that the value of `rv` after assignment is unspecified. ### See also | | | | --- | --- | | [is\_move\_assignableis\_trivially\_move\_assignableis\_nothrow\_move\_assignable](../types/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 C++ named requirements: CopyAssignable C++ named requirements: CopyAssignable ====================================== Specifies that an instance of the type can be copy-assigned from an [lvalue expression](../language/value_category "cpp/language/value category"). ### Requirements The type `T` satisfies CopyAssignable if. * The type `T` satisfies [MoveAssignable](moveassignable "cpp/named req/MoveAssignable"), and Given. * `t`, a modifiable [lvalue expression](../language/value_category "cpp/language/value category") of type `T` * `v`, an [lvalue](../language/value_category "cpp/language/value category") expression of type `T` or `const T` or an [rvalue](../language/value_category "cpp/language/value category") expression of type `const T` The following expressions must be valid and have their specified effects. | Expression | Return type | Return value | Post-conditions | | --- | --- | --- | --- | | `t = v` | `T&` | `t` | The value of `t` is equivalent to the value of `v`. The value of `v` is unchanged. | ### See also | | | | --- | --- | | [is\_copy\_assignableis\_trivially\_copy\_assignableis\_nothrow\_copy\_assignable](../types/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) | | [assignable\_from](../concepts/assignable_from "cpp/concepts/assignable from") (C++20) | specifies that a type is assignable from another type (concept) | cpp C++ named requirements: LegacyContiguousIterator C++ named requirements: LegacyContiguousIterator ================================================ A **LegacyContiguousIterator** is a [LegacyIterator](iterator "cpp/named req/Iterator") whose logically adjacent elements are also physically adjacent in memory. A pointer to an element of an array satisfies all requirements of LegacyContiguousIterator. ### Requirements The type `It` satisfies LegacyContiguousIterator if. * The type `It` satisfies [LegacyIterator](iterator "cpp/named req/Iterator") And, for every. * `a`, a dereferenceable iterator of type `It` * `n`, an integral value such that. * `a + n` is a valid and dereferenceable iterator value then. * `*(a + n)` is equivalent to `\*([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(\*a) + n)`. ### Standard library The following standard library types are **LegacyContiguousIterators**. * [`array::iterator`](../container/array "cpp/container/array"). * [`basic_string_view::iterator`](../string/basic_string_view "cpp/string/basic string view"). * [`basic_string::iterator`](../string/basic_string "cpp/string/basic string"). * [`vector::iterator`](../container/vector "cpp/container/vector") for `value_type` other than `bool`. * The return type of [`begin(valarray)`](../numeric/valarray/begin2 "cpp/numeric/valarray/begin2") and [`end(valarray)`](../numeric/valarray/end2 "cpp/numeric/valarray/end2") ### Notes [Fancy pointer](allocator#Fancy_pointers "cpp/named req/Allocator") to object types are also required to satisfy LegacyContiguousIterator. | | | | --- | --- | | LegacyContiguousIterator is replaced with the [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") concept: iterator types in the standard library that are required to satisfy LegacyContiguousIterator in C++17 are required to model `contiguous_iterator` in C++20. | (since C++20) | ### See also | | | | --- | --- | | [contiguous\_iterator](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") (C++20) | specifies that a [`random_access_iterator`](../iterator/random_access_iterator "cpp/iterator/random access iterator") is a contiguous iterator, referring to elements that are contiguous in memory (concept) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions | cpp C++ named requirements: MoveInsertable (since C++11) C++ named requirements: MoveInsertable (since C++11) ==================================================== Specifies that an object of the type can be constructed into uninitialized storage from an rvalue of that type by a given allocator. ### Requirements The type `T` is **MoveInsertable** into the container `X` whose `value_type` is identical to `T` if, given. | | | | --- | --- | | `A` | an allocator type | | `m` | an lvalue of type `A` | | `p` | the pointer of type `T*` prepared by the container | | `rv` | rvalue expression of type `T` | where `X::allocator_type` is identical to `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<T>`, the following expression is well-formed: ``` std::allocator_traits<A>::construct(m, p, rv); ``` And after evaluation, the value of `*p` is equivalent to the value formerly held by `rv` (`rv` remains valid, but is in an unspecified state.). If `X` is not allocator-aware or is a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specialization, the term is defined as if `A` were `std::allocator<T>`, except that no allocator object needs to be created, and user-defined specializations of `[std::allocator](../memory/allocator "cpp/memory/allocator")` are not instantiated. ### Notes If `A` is `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>`, then this will call placement-new, as by `::new((void*)p) T(rv)` (until C++20)`[std::construct\_at](http://en.cppreference.com/w/cpp/memory/construct_at)(p, rv)` (since C++20). This effectively requires `T` to be move constructible. If `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>` or a similar allocator is used, a class does not have to implement a [move constructor](../language/move_constructor "cpp/language/move constructor") to satisfy this type requirement: a [copy constructor](../language/copy_constructor "cpp/language/copy constructor") that takes a `const T&` argument can bind rvalue expressions. If a MoveInsertable class implements a move constructor, it may also implement [move semantics](../utility/move "cpp/utility/move") to take advantage of the fact that the value of `rv` after construction is unspecified. Although it is required that customized `construct` is used when constructing elements of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice. ### See also | | | --- | | [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") |
programming_docs
cpp C++ named requirements: ContiguousContainer C++ named requirements: ContiguousContainer =========================================== A **ContiguousContainer** is a [Container](container "cpp/named req/Container") that stores objects in contiguous memory locations. ### Requirements The type `X` satisfies ContiguousContainer if. * The type `X` satisfies [Container](container "cpp/named req/Container") * The type `X` supports [LegacyRandomAccessIterators](randomaccessiterator "cpp/named req/RandomAccessIterator") * The member types `X::iterator` and `X::const_iterator` are [LegacyContiguousIterators](contiguousiterator "cpp/named req/ContiguousIterator") (until C++20)[`contiguous_iterator`s](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") (since C++20) ### Contiguous containers in the standard library | | | | --- | --- | | [basic\_string](../string/basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) | | [array](../container/array "cpp/container/array") (C++11) | static contiguous array (class template) | | [vector](../container/vector "cpp/container/vector") | dynamic contiguous array (class template) | cpp C++ named requirements: CopyInsertable C++ named requirements: CopyInsertable ====================================== Specifies that an instance of the type can be copy-constructed in-place by a given allocator. ### Requirements The type `T` is **CopyInsertable** into the container `X` whose `value_type` is identical to `T` if `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X`, and, given. | | | | --- | --- | | `A` | an allocator type | | `m` | an lvalue of type `A` | | `p` | the pointer of type `T*` prepared by the container | | `v` | expression of type (possibly `const`) `T` | where `X::allocator_type` is identical to `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<T>`, the following expression is well-formed: ``` std::allocator_traits<A>::construct(m, p, v); ``` And after evaluation, the value of `*p` is equivalent to the value of `v`. The value of `v` is unchanged. If `X` is not allocator-aware or is a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specialization, the term is defined as if `A` were `std::allocator<T>`, except that no allocator object needs to be created, and user-defined specializations of `[std::allocator](../memory/allocator "cpp/memory/allocator")` are not instantiated. ### Notes If `A` is `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>`, then this will call placement-new, as by `::new((void*)p) T(v)` (until C++20)`[std::construct\_at](http://en.cppreference.com/w/cpp/memory/construct_at)(p, v)` (since C++20). Although it is required that customized `construct` is used when constructing elements of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice. cpp C++ named requirements: SharedTimedLockable C++ named requirements: SharedTimedLockable =========================================== The **SharedTimedLockable** requirements describe the characteristics of types that provide timed shared blocking semantics for execution agents (threads, processes, tasks). ### Requirements * [SharedLockable](sharedlockable "cpp/named req/SharedLockable") For type `L` to be SharedTimedLockable, given. * `rel_time`, a value of a specialization of `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")`, and * `abs_time`, a value of a specialization of `[std::chrono::time\_point](../chrono/time_point "cpp/chrono/time point")`, the following conditions have to be satisfied for an object `m` of type `L`: | Expression | Requires | Return value | | --- | --- | --- | | `m.try_lock_shared_for(rel_time)` | Blocks for the provided duration `rel_time` or until a lock on `m` is acquired. | `true` if the lock was acquired, `false` otherwise. | | `m.try_lock_shared_until(abs_time)` | Blocks until the provided time point `abs_time` is reached or a lock on `m` is acquired. | `true` if the lock was acquired, `false` otherwise. | ### Notes The `try_lock_shared_for` and `try_lock_shared_until` member functions obtain a shared lock on `m` on succcess. ### See also * [Thread support library](../thread "cpp/thread") * [SharedTimedMutex](sharedtimedmutex "cpp/named req/SharedTimedMutex") * [SharedLockable](sharedlockable "cpp/named req/SharedLockable") cpp C++ named requirements: BasicLockable C++ named requirements: BasicLockable ===================================== The **BasicLockable** requirements describe the minimal characteristics of types that provide exclusive blocking semantics for execution agents (i.e. threads). ### Requirements For type `L` to be BasicLockable, the following conditions have to be satisfied for an object `m` of type `L`: | Expression | Preconditions | Effects | | --- | --- | --- | | `m.lock()` | | Blocks until a lock can be acquired for the current execution agent (thread, process, task). If an exception is thrown, no lock is acquired. | | `m.unlock()` | The current execution agent holds a non-shared lock on `m`. | Releases the non-shared lock held by the execution agent. Throws no exceptions. | #### Non-shared locks A lock on an object is said to be *non-shared lock* if it is acquired by a call to `lock`, `try_lock`, `try_lock_for`, or `try_lock_until` member function. ### See also * [Thread support library](../thread "cpp/thread") * [Mutex](mutex "cpp/named req/Mutex") * [Lockable](lockable "cpp/named req/Lockable") * [TimedLockable](timedlockable "cpp/named req/TimedLockable") cpp C++ named requirements: DefaultConstructible C++ named requirements: DefaultConstructible ============================================ Specifies that an instance of the type can be default constructed. ### Requirements The type `T` satisfies DefaultConstructible if. Given. * `u`, an arbitrary identifier The following expressions must be valid and have their specified effects. | Expression | Post-conditions | | --- | --- | | `T u` | The object `u` is [default-initialized](../language/default_initialization "cpp/language/default initialization") | | `T u{}` | The object `u` is [value-initialized](../language/value_initialization "cpp/language/value initialization") or [aggregate-initialized](../language/aggregate_initialization "cpp/language/aggregate initialization"). | | `T()` `T{}` | A temporary object of type `T` is [value-initialized](../language/value_initialization "cpp/language/value initialization") or [aggregate-initialized](../language/aggregate_initialization "cpp/language/aggregate initialization"). | ### Notes For objects of non-aggregate class type, a public [default constructor](../language/default_constructor "cpp/language/default constructor") must be defined (either user-defined or implicitly defined) to satisfy DefaultConstructible. Non-const objects of [non-class object type](../language/type "cpp/language/type") are always DefaultConstructible. Const non-class types are not DefaultConstructible. Const aggregate types are not DefaultConstructible if any of their members is an object of non-class type. Non-object types (function types, reference types, and the (possibly cv-qualified) type `void`) as well as the const non-object types are never DefaultConstructible. ### See also | | | | --- | --- | | [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](../types/is_default_constructible "cpp/types/is default constructible") (C++11)(C++11)(C++11) | checks if a type has a default constructor (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 C++ named requirements: BasicFormatter C++ named requirements: BasicFormatter ====================================== **BasicFormatter** is a type that abstracts formatting operations for a given formatting argument type and character type. Specializations of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` are required to meet the requirements of BasicFormatter. A BasicFormatter is a [Formatter](formatter "cpp/named req/Formatter") if it is able to format both const and non-const arguments. ### Requirements A type satisfies BasicFormatter if it is semiregular, meaning it satisfies: * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") * [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") * [Destructible](destructible "cpp/named req/Destructible") * [Swappable](swappable "cpp/named req/Swappable") And, given. * `Arg`, a formatting argument type * `CharT`, a character type * `BasicFormatter`, a BasicFormatter type for types `Arg` and `CharT` * `OutputIt`, a [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") type * `f`, a value of type `BasicFormatter` * `arg`, an lvalue of type `Arg` * `ParseContext`, an alias of `[std::basic\_format\_parse\_context](http://en.cppreference.com/w/cpp/utility/format/basic_format_parse_context)<CharT>` * `FormatContext`, an alias of `[std::basic\_format\_context](http://en.cppreference.com/w/cpp/utility/format/basic_format_context)<OutputIt, CharT>` * `parse_ctx`, an lvalue of type `ParseContext` * `format_ctx`, an lvalue of type `FormatContext` | Expression | Return type | Semantics | | --- | --- | --- | | `f.parse(parse_ctx)` | `ParseContext::iterator` | * Parses the format-spec `[parse_ctx.begin(), parse_ctx.end())` for type `Arg` until the first unmatched character. * Throws `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")` unless the whole range is parsed or the unmatched character is `}`. [[note 1]](#cite_note-1) * Stores the parsed format specifiers in `f` and returns an end iterator of the parsed range. | | `f.format(arg, format_ctx)` | `FormatContext::​iterator` | * Formats `arg` according to the specifiers stored in `f`, writes the output to `format_ctx.out()` and returns an end iterator of the output range. * The output shall only depend on + `arg`, + `format_ctx.locale()`, + the range `[parse_ctx.begin(), parse_ctx.end())` from the last call to `f.parse(parse_ctx)`, and + `format_ctx.arg(n)` for any value `n` of type `[std::size\_t](../types/size_t "cpp/types/size t")`. | 1. This allows formatters to emit meaningful error messages. cpp C++ named requirements: RegexTraits C++ named requirements: RegexTraits =================================== **RegexTraits** is a traits class that abstracts operations needed for a given character type when as template type parameters for `[std::basic\_regex](http://en.cppreference.com/w/cpp/regex/basic_regex)`. ### Requirements Given. * `CharT`, a character type * `X`, a RegexTraits type for type `CharT` * `u`, an object of type `X` * `v`, an object of type `const X` * `p`, a value of type `const CharT*` * `I1, I2`, input iterators * `F1, F2`, forward iterators * `c`, a value of type `const CharT` * `s`, an object of type `X::string_type` * `cs`, an object of type `const X::string_type` * `b`, a value of type `bool` * `I`, a value of type `int` * `cl`, an object of type `X::char_class_type` * `loc`, an object of type `X::locale_type` | expression | return type | semantics | | --- | --- | --- | | `X::char_type` | `CharT` | Used to refer to the character type. | | `X::string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` | | | `X::locale_type` | | A [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") type that represents the locale used by the traits class. | | `X::char_class_type` | | A [BitmaskType](bitmasktype "cpp/named req/BitmaskType") type that represents a particular character classification. | | `X::length(p)` | `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` | Returns: the smallest `i` such that `p[i] == 0`. Complexity is linear in `i`. | | `v.translate(c)` | `X::char_type` | Returns: a character such that for any character `d` considered to be equivalent to `c`, then `v.translate(c) == v.translate(d)`. | | `v.translate_nocase(c)` | `X::char_type` | Returns: a character such that for any character `C` considered to be equivalent to `c` without regard to case, then `v.translate_nocase(c) == v.translate_nocase(C)`. | | `v.transform(F1, F2)` | `X::string_type` | Returns: a sort key for the character sequence designated by the iterator range `[F1, F2)` such that if the character sequence `[G1, G2)` sorts before the character sequence `[H1, H2)`, then `v.transform(G1, G2) < v.transform(H1, H2)`. | | `v.transform_primary(F1, F2)` | `X::string_type` | Returns: a sort key for the character sequence designated by the iterator range `[F1, F2)` such that if the character sequence `[G1, G2)` sorts before the character sequence `[H1, H2)` without regard to case, then `v.transform_primary(G1, G2) < v.transform_primary(H1, H2)`. | | `v.lookup_collatename(F1, F2)` | `X::string_type` | Returns: * An empty string if the character sequence is not a valid collating element * A sequence of characters that represents the collating element consisting of the character sequence designated by the iterator range `[F1, F2)` otherwise | | `v.lookup_classname(F1, F2, b)` | `X::char_class_type` | * Converts the character sequence designated by the iterator range `[F1, F2)` into a value of a [BitmaskType](bitmasktype "cpp/named req/BitmaskType") that can subsequently be passed to `isctype` * Values returned from `lookup_classname` can be bitwise or'ed together; the resulting value represents membership in either of the corresponding character classes * If `b` is true, the returned bitmask is suitable for matching characters without regard to their case. * Returns `​0​` if the character sequence is not the name of a character class recognized by `X`. * The value returned shall be independent of the case of the characters in the sequence. | | `v.isctype(c, cl)` | `bool` | Returns: whether `c` is a member of one of the character classes designated by `cl` or not. | | `v.value(c, I)` | `int` | Returns: * The value represented by the digit `c` in base `I` if the character `c` is a valid digit in base `I` * `-1` otherwise | | `u.imbue(loc)` | `X::locale_type` | * Imbues `u` with the locale `loc` * Returns: The previous locale used by `u` if any | | `v.getloc()` | `X::locale_type` | Returns: The previous locale used by `v` if any. | ### Standard library RegexTraits is satisfied by the following standard library classes: | | | | | --- | --- | --- | | ``` template<> class regex_traits<char>; template<> class regex_traits<wchar_t>; ``` | | (since C++11)(since C++11) | cpp C++ named requirements: Hash C++ named requirements: Hash ============================ A **Hash** is a function object for which the output depends only on the input and has a very low probability of yielding the same output given different input values. ### Requirements The type `T` satisfies Hash if. * The type `T` satisfies [FunctionObject](functionobject "cpp/named req/FunctionObject"), [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), [Destructible](destructible "cpp/named req/Destructible"), and Given. * `h`, a value of type `T` or `const T`, whose argument type is `Key` * `k`, a value of type convertible to `Key` or `const Key` * `u`, an [lvalue](../language/value_category "cpp/language/value category") expression of type `Key` The following expressions must be valid and have their specified effects. | Expression | Return type | Requirements | | --- | --- | --- | | `h(k)` | `std::size_t` | the returned value depends only on the value of `k` for the duration of the program All evaluations of `h(k)` executed within a given execution of a program yield the same result for the same value of `k`. The probability of `h(a)==h(b)` for `a!=b` should approach `1.0/[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()`. | | `h(u)` | `std::size_t` | `u` is not modified | ### Standard library | | | | --- | --- | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | ### 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 2291](https://cplusplus.github.io/LWG/issue2291) | C++11 | same results for same arguments were required in all cases | only required within a single execution | cpp C++ named requirements: ImplicitLifetimeType C++ named requirements: ImplicitLifetimeType ============================================ Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements The following types are collectively called *implicit-lifetime types*: * [scalar types](scalartype "cpp/named req/ScalarType") * [implicit-lifetime class types](../language/classes#Implicit-lifetime_class "cpp/language/classes") * array types * cv-qualified versions of these types cpp C++ named requirements: TriviallyCopyable C++ named requirements: TriviallyCopyable ========================================= Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements The following types are collectively called *trivially copyable types*: * [scalar types](scalartype "cpp/named req/ScalarType") * [trivially copyable class types](../language/classes#Trivially_copyable_class "cpp/language/classes") * arrays of such types * cv-qualified versions of these types ### Notes In general, for any trivially copyable type `T` and an object `obj1` of `T`, the underlying bytes of `obj1` can be copied into an array of `char`, or `unsigned char`, or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) or into `obj2`, a distinct object of `T`. Neither `obj1` nor `obj2` may be a potentially-overlapping subobject. If the underlying bytes of `obj1` are copied into such an array, and then the resulting content is copied back into `obj1`, `obj1` will hold its original value. If the underlying bytes of `obj1` are copied into `obj2`, `obj2` will hold `obj1`'s value. Underlying bytes can be copied by `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")` or `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`, as long as no living volatile object is 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 | | --- | --- | --- | --- | | [CWG 1734](https://cplusplus.github.io/CWG/issues/1734.html) | C++11 | C++03 POD with deleted non-trivial assignment was not trivial | deleted ctors/operators allowed | | [CWG 2094](https://cplusplus.github.io/CWG/issues/2094.html) | C++11 | Volatile scalar types are not trivially copyable ([CWG 1746](https://cplusplus.github.io/CWG/issues/1746.html)) | made trivially copyable | ### See also | | | | --- | --- | | [is\_trivially\_copyable](../types/is_trivially_copyable "cpp/types/is trivially copyable") (C++11) | checks if a type is trivially copyable (class template) |
programming_docs
cpp C++ named requirements: BitmaskType C++ named requirements: BitmaskType =================================== Defines a type that can be used to represent a set of constant values or any combination of those values. This trait is typically implemented by integer types, `[std::bitset](../utility/bitset "cpp/utility/bitset")`, or enumerations (scoped and unscoped) with additional operator overloads. ### Requirements The bitmask type supports a finite number of bitmask elements, which are distinct non-zero values of the bitmask type, such that, for any pair Ci and Cj, `Ci & Ci` is nonzero and `Ci & Cj` is zero. In addition, the value `0` is used to represent an empty bitmask, with no values set. The bitwise operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=` are defined for values of the bitmask type and have the same semantics as the corresponding built-in operators on unsigned integers would have if the bitmask elements were the distinct integer powers of two. The following expressions are well-formed and have the following meaning for any BitmaskType: | | | | --- | --- | | `X |= Y` | sets the value Y in the object X | | `X &= ~Y` | clears the value Y in the object X | | `X & Y` | nonzero result indicates that the value Y is set in the object X | Each representable bitmask element is defined as a `inline` (since C++17)`constexpr` value of the bitmask type. ### Usage The following standard library types satisfy BitmaskType: * [`std::chars_format`](../utility/chars_format "cpp/utility/chars format") (since C++17) * `[std::ctype\_base::mask](../locale/ctype_base "cpp/locale/ctype base")` * `[std::ios\_base::fmtflags](../io/ios_base/fmtflags "cpp/io/ios base/fmtflags")` * `[std::ios\_base::iostate](../io/ios_base/iostate "cpp/io/ios base/iostate")` * `[std::ios\_base::openmode](../io/ios_base/openmode "cpp/io/ios base/openmode")` * [`std::regex_traits::char_class_type`](../regex/regex_traits#Member_types "cpp/regex/regex traits") (since C++11) * `[std::regex\_constants::syntax\_option\_type](../regex/syntax_option_type "cpp/regex/syntax option type")` (since C++11) * `[std::regex\_constants::match\_flag\_type](../regex/match_flag_type "cpp/regex/match flag type")` (since C++11) * `[std::launch](../thread/launch "cpp/thread/launch")` (since C++11) * `[std::filesystem::perms](../filesystem/perms "cpp/filesystem/perms")` (since C++17) * [`std::filesystem::perm_options`](../filesystem/perm_options "cpp/filesystem/perm options") (since C++17) * `[std::filesystem::copy\_options](../filesystem/copy_options "cpp/filesystem/copy options")` (since C++17) * `[std::filesystem::directory\_options](../filesystem/directory_options "cpp/filesystem/directory options")` (since C++17) Code that relies on some particular implementation option (e.g. `int n = [std::ios\_base::hex](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags)`), is nonportable because `[std::ios\_base::fmtflags](../io/ios_base/fmtflags "cpp/io/ios base/fmtflags")` is not necessarily implicitly convertible to `int`. cpp C++ named requirements: Lockable C++ named requirements: Lockable ================================ The **Lockable** requirements extends the [BasicLockable](basiclockable "cpp/named req/BasicLockable") requirements to include attempted locking. ### Requirements * [BasicLockable](basiclockable "cpp/named req/BasicLockable") For type `L` to be Lockable, it must meet the above condition as well as the following: | Expression | Effects | Return value | | --- | --- | --- | | `m.try_lock()` | Attempts to acquire the lock for the current execution agent (thread, process, task) without blocking. If an exception is thrown, no lock is obtained. | `true` if the lock was acquired, `false` otherwise | ### Notes The `try_lock` member functions obtains a non-shared lock on `m` on succcess. ### See also * [Thread support library](../thread "cpp/thread") * [Mutex](mutex "cpp/named req/Mutex") * [BasicLockable](basiclockable "cpp/named req/BasicLockable") * [TimedLockable](timedlockable "cpp/named req/TimedLockable") cpp C++ named requirements: SeedSequence C++ named requirements: SeedSequence ==================================== A **SeedSequence** is an object that produces unsigned integer values i in the range 0 ≤ i < 232 based on a consumed range of integer data. ### Requirements * `S` is a SeedSequence type. * `q` is an object of `S` and `r` is a potentially constant object of `S`. * `T` is the `result_type`. * `ib`,`ie` are [LegacyInputIterators](inputiterator "cpp/named req/InputIterator") with a `value_type` of unsigned integer values of at least 32 bits. * `il` is an `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<T>`. * `rb`,`re` are [mutable](outputiterator "cpp/named req/OutputIterator") [LegacyRandomAccessIterators](randomaccessiterator "cpp/named req/RandomAccessIterator") with a `value_type` of unsigned integer values of at least 32 bits. * `ob` is an [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator"). | Expression | Type | Notes | Complexity | | --- | --- | --- | --- | | `S::result_type` | `T` | Unsigned integer of at least 32 bits | compile-time | | `S()` | | Creates a seed sequence with the same initial state as other default-constructed seed sequences of type `S` | constant | | `S(ib,ie)` | | Creates a seed sequence with internal state depending on some or all supplied input bits by [`ib`,`ie`) | O(ie-ib) | | `S(il)` | | The same as `S(il.begin(), il.end())` | | | `q.generate(rb,re)` | `void` | Fills [`rb`,`re`) with 32-bit quantities depending on the initial supplied values and potential previous calls to `generate`. If `rb == re`, it does nothing. | O(re-rb) | | `r.size()` | `size_t` | The amount of 32-bit integers copied by `param`. | constant | | `r.param(ob)` | `void` | Copies 32-bit values to `ob` that would reproduce the current state of the object if passed to a constructor of `S`. | O(r.size()) | ### See also * `[std::seed\_seq](../numeric/random/seed_seq "cpp/numeric/random/seed seq")` cpp C++ named requirements: UnorderedAssociativeContainer C++ named requirements: UnorderedAssociativeContainer ===================================================== Unordered associative containers are [Containers](container "cpp/named req/Container") that provide fast lookup of objects based on keys. Worst case complexity is linear but on average much faster for most of the operations. Unordered associative containers are parametrized by `Key`; `Hash`, a [Hash](hash "cpp/named req/Hash") function object which acts as hash function on `Key`; and `Pred`, a [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate") evaluating equivalence between `Key`s. `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` also have a mapped type `T` associated with the `Key`. If two `Key`s are equal according to `Pred`, `Hash` must return the same value for both keys. | | | | --- | --- | | If both `Hash::is_transparent` and `Pred::is_transparent` exist and each names a type, member functions `find`, `contains`, `count`, and `equal_range` accept arguments of types other than `Key` and expect that `Hash` is callable with values of those types, and that `Pred` is a transparent comparison function such as `std::equal_to<>`. | (since C++20) | `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)` can contain at most one element with a given key, `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` instead can have multiple elements with the same key (which must always be adjacent on iterations). For `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)` and `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)` the value type is the same as the key type and both `iterator` and `const_iterator` are constant iterators. For `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` the value type is `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`. Elements in an unordered associative container are organized into buckets, keys with the same hash will end up in the same bucket. The number of buckets is increased when the size of the container increases to keep the average number of elements in each bucket under a certain value. Rehashing invalidates iterator and might cause the elements to be re-arranged in different buckets but it doesn't invalidate references to the elements. Unordered associative containers meet the requirements of [AllocatorAwareContainer](allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"). For `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` the requirements of `value_type` in [AllocatorAwareContainer](allocatorawarecontainer "cpp/named req/AllocatorAwareContainer") apply to `key_type` and `mapped_type` (not to `value_type`). ### Requirements | | | --- | | Legend | | `X` | Container type | | `a` | Object of type `X` | | `b` | `const` Object of type `X` | | `a_uniq` | Object in `X` when `X` supports unique keys | | `a_eq` | Object in `X` when `X` supports multiple equivalent keys | | `i`, `j` | [LegacyInputIterators](inputiterator "cpp/named req/InputIterator") denoting a valid range | | `p`, `q2` | valid const\_iterator to `a` | | `q`, `q1` | dereferenceable const\_iterator to `a` denoting a valid range | | `il` | Object of `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<X::value\_type>` | | `t` | Object of type `X::value_type` | | `k` | Object of type `X::key_type` | | `hf` | `const` Object of type `X::hasher` | | `eq` | `const` Object of type `X::key_equal` | | `n` | Value of type `X::size_type` | | `z` | Value of type `float` | | expression | return type | pre/requirements | post/effects | complexity | | --- | --- | --- | --- | --- | | `X::key_type` | `Key` | | | compile time | | `X::mapped_type` | `T` | `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` only | | compile time | | `X::value_type` | `Key` | `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)` and `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)` only. [Erasable](erasable "cpp/named req/Erasable") in `X` | | compile time | | `X::value_type` | `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)` and `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)` only. [Erasable](erasable "cpp/named req/Erasable") in `X` | | compile time | | `X::hasher` | `Hash` | [Hash](hash "cpp/named req/Hash") | | compile time | | `X::key_equal` | `Pred` | [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate") taking two arguments of type `Key` and expressing an equivalence relation. | | compile time | | `X::local_iterator` | An [LegacyIterator](iterator "cpp/named req/Iterator") whose category and types are the same as `X::iterator` | | Can be used to iterate through a single bucket | compile time | | `X::const_local_iterator` | An [LegacyIterator](iterator "cpp/named req/Iterator") whose category and types are the same as `X::const_iterator` | | Can be used to iterate through a single bucket | compile time | | `X(n,hf,eq)` | `X` | `hasher` and `key_equal` [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") | Constructs an empty container with at least `n` buckets, using the given hash function and equality predicate | linear in `n` | | `X(n,hf)` | `X` | `hasher` [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), `key_equal` [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | Constructs an empty container with at least `n` buckets, using the given hash function and `key_equal()` as equality predicate | linear in `n` | | `X(n)` | `X` | `hasher` and `key_equal` [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | Constructs an empty container with at least `n` buckets, using `hasher()` as hash function and `key_equal()` as equality predicate | linear in `n` | | `X()` | `X` | `hasher` and `key_equal` [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | Constructs an empty container with an unspecified number of buckets, using `hasher()` as hash function and `key_equal()` as equality predicate | constant | | `X(i,j,n,hf,eq)` | `X` | `hasher` and `key_equal` [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), `value_type` [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") into `X` from `*i` | Constructs an empty container with at least `n` buckets, using the given hash function and equality predicate, and inserts elements from [i,j) into it. | average linear, worst quadratin (on the distance between `i` and `j`) | | `X(i,j,n,hf)` | `X` | `key_equal` [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | As above, with `eq=key_equal()` | see above | | `X(i,j,n)` | `X` | `hasher` [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | As above, with `hf=hasher()` | see above | | `X(i,j)` | `X` | | As above, with an unspecified number of buckets | see above | | `X(il)` | `X` | | `X(il.begin(),il.end()` | see above | | `X(il,n)` | `X` | | `X(il.begin(),il.end(),n` | see above | | `X(il,n,hf)` | `X` | | `X(il.begin(),il.end(),n,hf` | see above | | `X(il,n,hf,eq)` | `X` | | `X(il.begin(),il.end(),n,hf,eq` | see above | | `X(b)` | `X` | | Copy constructors, also copies the hash function, predicate and maximum load factor | average linear, worst quadratic (in `b.size()`) | | `a = b` | `X&` | | Copy assignment, also copies the hash function, predicate and maximum load factor | average linear, worst quadratic (in `b.size()`) | | `a = il` | `X&` | `value_type` [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") and [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` | `a = X(il)` | see above | ### Unordered associative containers in the standard library | | | | --- | --- | | [unordered\_set](../container/unordered_set "cpp/container/unordered set") (C++11) | collection of unique keys, hashed by keys (class template) | | [unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset") (C++11) | collection of keys, hashed by keys (class template) | | [unordered\_map](../container/unordered_map "cpp/container/unordered map") (C++11) | collection of key-value pairs, hashed by keys, keys are unique (class template) | | [unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap") (C++11) | collection of key-value pairs, hashed by keys (class template) | cpp C++ named requirements: FormattedInputFunction C++ named requirements: FormattedInputFunction ============================================== ### Requirements A FormattedInputFunction is a stream input function that performs the following: * Constructs an object of type [`basic_istream::sentry`](../io/basic_istream/sentry "cpp/io/basic istream/sentry") with automatic storage duration and with the `noskipws` argument set to `false`, which performs the following * if [`eofbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") or [`badbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") are set on the input stream, sets the `failbit` as well, and if exceptions on failbit are enabled in this input stream's exception mask, throws [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure"). * flushes the tie()'d output stream, if applicable * if `ios_base::skipws` flag is set on this input stream, extracts and discards characters from the input stream until one of the following becomes true: + the next available character on the input stream is not a whitespace character, as tested by the `[std::ctype](../locale/ctype "cpp/locale/ctype")` facet of the locale currently imbued in this input stream. The non-whitespace character is not extracted. + the end of the stream is reached, in which case `failbit` and `eofbit` are set and if the stream is on for exceptions on one of these bits, [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure") is thrown. * Checks the status of the sentry by calling `sentry::operator bool()`, which is equivalent to [`basic_ios::good`](../io/basic_ios/good "cpp/io/basic ios/good"). * If the sentry returned `false` or sentry's constructor threw an exception, no input takes place * If the sentry returned `true`, performs the input as if by calling `rdbuf()->sbumpc()` or `rdbuf()->sgetc()`. + if the end of the stream is reached (the call to `rdbuf()->sbumpc()` or `rdbuf()->sgetc()` returns `Traits::eof()`), sets `eofbit`. If exceptions on eofbit are enabled in this stream's exception mask, throws [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure"). + if an exception is thrown during input, sets `badbit` in the input stream. If exceptions on badbit are enabled in this stream's exception mask, the exception is also rethrown. + If no exception was thrown, returns `*this`. * In any event, whether terminating by exception or returning, the sentry's destructor is called before leaving this function. ### Standard library The following standard library functions are **FormattedInputFunctions**. * [`basic_istream::operator>>(int, long, double, void*, bool)`](../io/basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") * [`operator>>(std::basic_istream, char&)`](../io/basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") * [`operator>>(std::basic_istream, char*)`](../io/basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") * [`operator>>(std::basic_istream, std::bitset)`](../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") * [`operator>>(std::basic_istream, std::string)`](../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") * `operator>>`, when called on the return value of `[std::get\_money](../io/manip/get_money "cpp/io/manip/get money")` cpp C++ named requirements: ConstexprIterator C++ named requirements: ConstexprIterator ========================================= A **ConstexprIterator** is a [LegacyIterator](iterator "cpp/named req/Iterator") that can be used during constant expression evaluation. ### Requirements The type `It` satisfies ConstexprIterator if. * The type `It` satisfies some iterator requirements MeowIterator And, for every. * `purr`, an operation on `It` that is required to be supported by MeowIterator, * `kittens...`, a set of arguments to `purr` that meets the requirements for that operation, Then. * `purr(kittens...)` may be used in a constant expression if `kittens...` can also be used ### Standard library The following standard library types are **ConstexprIterators**. * [`array::iterator`](../container/array "cpp/container/array") and [`array::const_iterator`](../container/array "cpp/container/array"). * [`basic_string_view::iterator`](../string/basic_string_view "cpp/string/basic string view"). * [`span::iterator`](../container/span "cpp/container/span"). * [`vector::iterator`](../container/vector "cpp/container/vector") and [`vector::const_iterator`](../container/vector "cpp/container/vector"). ### See also | | | | --- | --- | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions |
programming_docs
cpp C++ named requirements: PODType C++ named requirements: PODType =============================== Specifies that the type is POD (Plain Old Data) type. This means the type is compatible with the types used in the C programming language, that is, can be exchanged with C libraries directly, in its binary form. Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. | | | | --- | --- | | This type requirement is deprecated in the C++ standard. All of its uses have been replaced by the more refined type requirements, such as [TrivialType](trivialtype "cpp/named req/TrivialType"). | (since C++20) | ### Requirements The following types are collectively called *POD types*: * [scalar types](scalartype "cpp/named req/ScalarType") * [POD classes](../language/classes#POD_class "cpp/language/classes") * arrays of such types * cv-qualified versions of these types ### See also | | | | --- | --- | | [is\_pod](../types/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) | cpp C++ named requirements: NullablePointer (since C++11) C++ named requirements: NullablePointer (since C++11) ===================================================== Specifies that the type is a pointer-like object which can be compared to `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` objects. ### Requirements The type must meet all of the following requirements: * [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") * [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") * [Destructible](destructible "cpp/named req/Destructible") In addition, a value-initialized object of the type must produce a null value of that type. This null value shall only be equivalent to itself. Default initialization of the type may have an indeterminate value. An object of the type must be contextually convertible to bool. The effect of this conversion returns false if the value is equivalent to its null value and true otherwise. None of the operations that this type performs may throw exceptions. The type must satisfy the following additional expressions, given two values `p` and `q` that are of the type, and that `np` is a value of `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` type (possibly `const` qualified): | Expression | Effects | | --- | --- | | `Type p(np);` `Type p = np;` | Afterwards, `p` is equivalent to `nullptr` | | `Type(np)` | a temporary object that is equivalent to `nullptr` | | `p = np` | Must return a `Type&`, and afterwards, `p` is equivalent to `nullptr` | | `p != q` | Must return a value that is contextually convertible to bool. The effect is `!(p == q)`. | | `p == np` `np == p`. | Must return a value that is contextually convertible to bool. The effect is `(p == Type())`. | | `p != np` `np != p`. | Must return a value that is contextually convertible to bool. The effect is `!(p == np)`. | ### Notes Note that dereferencing (`operator*` or `operator->`) is not required of a NullablePointer type. A minimalistic type that satisfies these requirements is. ``` class handle { int id = 0; public: handle() = default; handle(std::nullptr_t) { } explicit operator bool() const { return id != 0; } friend bool operator==(handle l, handle r) { return l.id == r.id; } friend bool operator!=(handle l, handle r) { return !(l == r); } // or only a defaulted operator== (since C++20) }; ``` ### Standard library The following types must satisfy NullablePointer: * The member types `X::pointer`, `X::const_pointer`, `X::void_pointer` and `X::const_void_pointer` of every [Allocator](allocator "cpp/named req/Allocator") type `X` * The member type `X::pointer` of `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` * The type `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` cpp C++ named requirements: Destructible C++ named requirements: Destructible ==================================== Specifies that an instance of the type can be destructed. ### Requirements The type `T` satisfies Destructible if. Given. * `u`, an expression of type `T` The following expressions must be valid and have their specified effects. | Expression | Post-conditions | | --- | --- | | `u.~T()` | All resources owned by `u` are reclaimed, no exceptions are thrown. | ### Notes Destructors are called implicitly at the end of [object lifetime](../language/lifetime "cpp/language/lifetime") such as when leaving [scope](../language/scope "cpp/language/scope") or by the [delete-expression](../language/delete "cpp/language/delete"). Explicit destructor call as shown in the type requirement table is rare. Thanks to [pseudo destructor call](../language/operator_member_access#Built-in_member_access_operators "cpp/language/operator member access"), all scalar types meet the requirement of Destructible, while array types and reference types do not. Note that `[std::is\_destructible](../types/is_destructible "cpp/types/is destructible")` allows arrays and reference types. ### See also | | | | --- | --- | | [is\_destructibleis\_trivially\_destructibleis\_nothrow\_destructible](../types/is_destructible "cpp/types/is destructible") (C++11)(C++11)(C++11) | checks if a type has a non-deleted destructor (class template) | | [destructible](../concepts/destructible "cpp/concepts/destructible") (C++20) | specifies that an object of the type can be destroyed (concept) | cpp C++ named requirements: MoveConstructible (since C++11) C++ named requirements: MoveConstructible (since C++11) ======================================================= Specifies that an instance of the type can be constructed from an [rvalue](../language/value_category "cpp/language/value category") argument. ### Requirements The type `T` satisfies MoveConstructible if. Given. * `rv`, an [rvalue](../language/value_category "cpp/language/value category") expression of type `T` * `u`, an arbitrary identifier The following expressions must be valid and have their specified effects. | Expression | Post-conditions | | --- | --- | | `T u = rv;` | The value of `u` is equivalent to the value of `rv` before the initialization. The new value of `rv` is unspecified. | | `T(rv)` | The value of `T(rv)` is equivalent to the value of `rv` before the initialization. The new value of `rv` is unspecified. | ### Notes A class does not have to implement a [move constructor](../language/move_constructor "cpp/language/move constructor") to satisfy this type requirement: a [copy constructor](../language/copy_constructor "cpp/language/copy constructor") that takes a `const T&` argument can bind rvalue expressions. If a MoveConstructible class implements a move constructor, it may also implement [move semantics](../utility/move "cpp/utility/move") to take advantage of the fact that the value of `rv` after construction is unspecified. ### See also | | | | --- | --- | | [is\_move\_constructibleis\_trivially\_move\_constructibleis\_nothrow\_move\_constructible](../types/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) | | [move\_constructible](../concepts/move_constructible "cpp/concepts/move constructible") (C++20) | specifies that an object of a type can be move constructed (concept) | cpp C++ named requirements: ScalarType C++ named requirements: ScalarType ================================== Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements The following types are collectively called *scalar types*: * [arithmetic types](../language/type "cpp/language/type") * [enumeration types](../language/enum "cpp/language/enum") * [pointer types](../language/pointer "cpp/language/pointer") * [pointer-to-member types](../language/pointer#Pointers_to_members "cpp/language/pointer") | | | | --- | --- | | * `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` | (since C++11) | * cv-qualified versions of these types ### See also | | | | --- | --- | | [is\_scalar](../types/is_scalar "cpp/types/is scalar") (C++11) | checks if a type is a scalar type (class template) | cpp C++ named requirements: AssociativeContainer C++ named requirements: AssociativeContainer ============================================ An **AssociativeContainer** is an ordered [Container](container "cpp/named req/Container") that provides fast lookup of objects based on keys. ### Requirements | | | --- | | Legend | | `X` | Container type | | `a` | Value of type `X` | | `a2` | Value of a type `Y` whose [node handles](../container/node_handle "cpp/container/node handle") are compatible with X | | `b` | Possibly const value of type `X` | | `u` | Arbitrary variable name | | `a_uniq` | Value of type `X` when `X` supports unique keys | | `a_eq` | Value of type `X` when `X` supports multiple keys | | `a_tran` | Possibly const value of type `X` when type `X::key_compare::is_transparent` exists | | `i`, `j` | [LegacyInputIterators](inputiterator "cpp/named req/InputIterator") denoting a valid range and referring to elements implicitly convertible to `X::value_type` | | `p` | A valid const iterator to `a` | | `q` | A valid dereferenceable const iterator to `a` | | `r` | A valid dereferenceable iterator to `a` | | `q1`, `q2` | const iterators denoting a valid range in `a` | | `il` | An object of type `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")`<value\_type> | | `t` | A value of type `X::value_type` | | `k` | A value of type `X::key_type` | | `c` | A possibly const value of type `X::key_compare` | | `kl` | A value such that `a` is partitioned with respect to `c(r,kl)`, with `r` the key value of `e` and `e` in `a` | | `ku` | A value such that `a` is partitioned with respect to `!c(ku, r)` | | `ke` | A value such that `a` is partitioned with respect to `c(r, ke)` and `!c(ke, r)`, with `c(r, ke)` implying `!c(ke, r)` | | `A` | Storage allocator used by `X`, or `std::allocator_type<X::value_type>` | | `m` | Allocator of a type convertible to `A` | | `nh` | A non-const rvalue of type `X::node_type` | | expression | return type | pre/requirements | post/effects | complexity | | --- | --- | --- | --- | --- | | `X::key_type` | `Key` | `Key` is [Destructible](destructible "cpp/named req/Destructible") | | compile time | | `X::key_compare` | `Compare` | | | compile time | | `X::value_compare` | a type satisfying [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate") | `key_compare` for `[std::set](http://en.cppreference.com/w/cpp/container/set)` and `[std::multiset](http://en.cppreference.com/w/cpp/container/multiset)`; an ordering relation over `Key` for `[std::map](http://en.cppreference.com/w/cpp/container/map)` and `[std::multimap](http://en.cppreference.com/w/cpp/container/multimap)` | | compile time | | `X(c)`, `X a(c);` | | `key_compare` is [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") | Construct an empty container using a copy of `c` as `key_comp` | constant | | `X()`, `X a;` | | `key_compare` is [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | Construct an empty container using a `Compare()` as `key_comp` | constant | | `X(i, j, c)`, `X a(i, j, c);` | | `key_compare` is [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") and `value_type` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") into `X` from `*i` | Constructs an empty container using a copy of `c` as `key_comp` and inserts all elements from the range `[i; j)` | generally `N log N`, or `N` if `[i, j)` is sorted (where `N` is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(i, j)`) | | `X(i, j)`, `X a(i, j);` | | `key_compare` is [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") and `value_type` is [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") into `X` from `*i` | Constructs an empty container using a `Compare()` as `key_comp` and inserts all elements from the range `[i; j)` | generally `N log N`, or `N` if `[i, j)` is sorted according to `value_comp()` (where `N` is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(i, j)`) | | `X(il);` | | Equivalent to `X(il.begin(), il.end());` | Equivalent to `X(il.begin(), il.end());` | | `a = il` | `X&` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` and also [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") | Assign the range `[il.begin(), il.end())` into `a`. Elements of `a` that were not assigned to are destroyed | generally `N log N`, or `N` if `[il.begin(), il.end())` is sorted according to `value_comp()` (where `N` is `il.size() + a.size()`) | | `a.key_comp()` | `X::key_compare` | | The comparison object with which `a` was constructed is returned. | constant | | `a.value_comp()` | `X::value_compare` | | An object of type `X::value_compare` constructed out of the comparison object is returned. | constant | An associative container `X` that is either `std::map` and `std::multimap` additionally supports the expression X::mapped\_type, which has a return type of T, with the requirement that `T` be [Destructible](destructible "cpp/named req/Destructible"), and compile time complexity. ### Associative containers in the standard library | | | | --- | --- | | [set](../container/set "cpp/container/set") | collection of unique keys, sorted by keys (class template) | | [multiset](../container/multiset "cpp/container/multiset") | collection of keys, sorted by keys (class template) | | [map](../container/map "cpp/container/map") | collection of key-value pairs, sorted by keys, keys are unique (class template) | | [multimap](../container/multimap "cpp/container/multimap") | collection of key-value pairs, sorted by keys (class template) | cpp C++ named requirements: FormattedOutputFunction C++ named requirements: FormattedOutputFunction =============================================== ### Requirements A FormattedOutputFunction is a stream output function that performs the following: * Constructs an object of type [`basic_ostream::sentry`](../io/basic_ostream/sentry "cpp/io/basic ostream/sentry") with automatic storage duration, which performs the following + if [`eofbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") or [`badbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") are set on the output stream, sets the `failbit` as well, and if exceptions on failbit are enabled in this output stream's exception mask, throws [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure"). + flushes the tie()'d output stream, if applicable. * Checks the status of the sentry by calling `sentry::operator bool()`, which is equivalent to [`basic_ios::good`](../io/basic_ios/good "cpp/io/basic ios/good"). * If the sentry returned `false` or sentry's constructor threw an exception, no output takes place * If the sentry returned `true`, attempts to perform the desired output by inserting the characters into the output stream as if by calling `rdbuf()->sputc()` or `rdbuf()->xsputn()`. Additionally, `rdbuf()->overflow()` and `rdbuf()->sync()` may be called, but no other virtual member function of `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`. + If the output could not be generated, sets `failbit`, If exceptions on failbit are enabled in this stream's exception mask, throws [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure"). + if an exception is thrown during output, sets `badbit` in the output stream. If exceptions on badbit are enabled in this stream's exception mask, the exception is also rethrown. + If no exception was thrown, returns `*this`. * In any event, whether terminating by exception or returning, the sentry's destructor is called before leaving this function. ### Standard library The following standard library functions are **FormattedOutputFunctions**. * [`basic_ostream::operator<<(int, long, double, void*, bool)`](../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") * [`operator<<(std::basic_ostream, char)`](../io/basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") * [`operator<<(std::basic_ostream, char*)`](../io/basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") * [`operator<<(std::basic_ostream, std::bitset)`](../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") * [`operator<<(std::basic_ostream, std::string)`](../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") * `operator<<` , when called on the return value of `[std::put\_money](../io/manip/put_money "cpp/io/manip/put money")` cpp C++ named requirements: Container C++ named requirements: Container ================================= A **Container** is an object used to store other objects and taking care of the management of the memory used by the objects it contains. ### Requirements * `C` container type; * `T` element type; * `a`, `b` objects of type `C`. * `rv` a prvalue expression of type `C`. #### Types | name | type | notes | | --- | --- | --- | | `value_type` | T | [Erasable](erasable "cpp/named req/Erasable") | | `reference` | T& | | | `const_reference` | const T& | | | `iterator` | iterator pointing to T | [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator")convertible to `const_iterator` | | `const_iterator` | constant iterator pointing to T | [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator") | | `difference_type` | signed integer | must be the same as `[iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")::difference_type` for `iterator` and `const_iterator` | | `size_type` | unsigned integer | large enough to represent all positive values of `difference_type` | #### Methods and operators | expression | return type | semantics | conditions | complexity | | --- | --- | --- | --- | --- | | `C()` | C | creates an empty container | Post: C().empty() == true | Constant | | `C(a)` | C | creates a copy of `a` | Pre: T must be [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable")Post: a == C(a) | Linear | | `C(rv)`(since C++11) | C | moves `rv` | Post: equal to the value rv had before this construction | Constant[[1]](#cite_note-array-1) | | `a = b` | C& | destroys or copy-assigns all elements of `a` from elements of `b` | Post: a == b | Linear | | `a = rv` | C& | destroys or move-assigns all elements of `a` from elements of `rv` | Post: if a and rv do not refer the same object, a is equal to the value rv had before this assignment | Linear | | `a.~C()` | void | destroys all elements of `a` and frees all memory | | Linear | | `a.begin()` | (const\_)iterator | Iterator to the first element of `a` | | Constant | | `a.end()` | (const\_)iterator | Iterator to one past the last element of `a` | | Constant | | `a.cbegin()`(since C++11) | const\_iterator | `const_cast<const C&>(a).begin()` | | Constant | | `a.cend()`(since C++11) | const\_iterator | `const_cast<const C&>(a).end()` | | Constant | | `a == b` | convertible to bool | `a.size() == b.size() && [std::equal](http://en.cppreference.com/w/cpp/algorithm/equal)(a.begin(), a.end(), b.begin())` (until C++14)`[std::equal](http://en.cppreference.com/w/cpp/algorithm/equal)(a.begin(), a.end(), b.begin(), b.end())` (since C++14) | Pre: T must be [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") | Constant[[2]](#cite_note-2) if `a.size() != b.size()`, linear otherwise | | `a != b` | convertible to bool | `!(a == b)` | | Linear | | `a.swap(b)` | void | exchanges the values of `a` and `b` | | Constant[[1]](#cite_note-array-1)[[3]](#cite_note-should-3) | | `swap(a, b)` | void | `a.swap(b)` | | Constant[[1]](#cite_note-array-1) | | `a.size()` | size\_type | `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(a.begin(), a.end())` | | Constant[[3]](#cite_note-should-3) | | `a.max_size()` | size\_type | `b.size()` where `b` is the largest possible container | | Constant[[3]](#cite_note-should-3) | | `a.empty()` | convertible to bool | `a.begin() == a.end()` | | Constant | | notes | | 1. Linear for `[std::array](../container/array "cpp/container/array")` 2. always linear for `[std::forward\_list](../container/forward_list "cpp/container/forward list")` 3. (until C++11) Not strictly constant | Given. * `i` and `j`, objects of a container's `iterator` type, in the expressions `i == j`, `i != j`, `i < j`, `i <= j`, `i >= j`, `i > j`, `i - j`, either or both may be replaced by an object of the container's `const_iterator` type referring to the same element with no change in semantics. ### Container data races see [container thread safety](../container#Thread_safety "cpp/container"). ### Other requirements C * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") * [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") * [Swappable](swappable "cpp/named req/Swappable") T * [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") * [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") * [Destructible](destructible "cpp/named req/Destructible") ### 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 179](https://cplusplus.github.io/LWG/issue179) | C++98 | `iterator` and `const_iterator` types might be incomparable | required to be comparable | | [LWG 2263](https://cplusplus.github.io/LWG/issue2263) | C++11 | resolution of LWG179 was accidentally dropped in C++11 | restored | | [LWG 2839](https://cplusplus.github.io/LWG/issue2839) | C++11 | self move assignment of standard containers was not allowed | allowed but the result is unspecifed | ### See also | | | --- | | [C++ documentation](../container "cpp/container") for `Containers library` |
programming_docs
cpp C++ named requirements: CharTraits C++ named requirements: CharTraits ================================== **CharTraits** is a traits class that abstracts basic character and string operations for a given character type. Most standard library string and input/output classes require a CharTraits template type parameter alongside a corresponding character template type parameter. ### Requirements No operation listed below on CharTraits may throw an exception. Given. * `CharT`, a character type * `X`, a CharTraits type for type `CharT` * `c, d`, values of type `CharT` * `p, q`, values of type `const CharT*` * `s`, a value of type `CharT*` * `n, i, j`, values of type `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` * `e, f`, values of type `X::int_type` * `pos`, a value of type `X::pos_type` * `state`, a value of type `X::state_type` * `r`, an lvalue of type `CharT` | expression | return type | semantics | complexity | | --- | --- | --- | --- | | `X::char_type` | `CharT` | Used to refer to the character type | Compile-time | | `X::int_type` | | A type that can hold all valid values of `X::char_type` plus `X::eof()` | Compile-time | | `X::off_type` | | Invokes implementation-defined behaviour if not `[std::streamoff](http://en.cppreference.com/w/cpp/io/streamoff)` when `X` is used as the traits template parameter in input/output classes. | Compile-time | | `X::pos_type` | | * Functions in input/output classes returning this type use `X::pos_type(X::off_type(-1))` as an invalid value to signal an error * Use of this invalid value as an argument to any `[std::istream](http://en.cppreference.com/w/cpp/io/basic_istream)`, `[std::ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)` or `[std::streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)` member taking a value of this type is undefined behaviour * Invokes implementation-defined behaviour if this type is not `[std::streampos](http://en.cppreference.com/w/cpp/io/fpos)` when `X` is used as the traits template parameter in input/output classes | Compile-time | | `X::state_type` | | [Destructible](destructible "cpp/named req/Destructible"), [CopyAssignable](copyassignable "cpp/named req/CopyAssignable"), [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | Compile-time | | `X::eq(c,d)` | `bool` | Returns: whether `c` is to be treated as equal to `d` | Constant | | `X::lt(c,d)` | `bool` | Returns: whether `c` is to be treated as less than `d` | Constant | | `X::compare(p,q,n)` | `int` | Returns: * 0 if for each `i` in `[0,n)`, `X::eq(p[i], q[i])` is true * Else, a negative value if + For some `j` in `[0,n)`, `X::lt(p[j], q[j])` is true and + For each `i` in `[0,j)`, `X::eq(p[i], q[i])` is true * Else a positive value | Linear | | `X::length(p)` | `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` | Returns: the smallest `i` such that `X::eq(p[i], CharT())` is true | Linear | | `X::find(p,n,c)` | `const X::char_type*` | Returns: * The smallest `q` in `[p,p+n)` such that `X::eq(*q, c)` is true * Zero otherwise | Linear | | `X::move(s,p,n)` | `X::char_type*` | * For each `i` in `[0,n)`, performs `X::assign(s[i], p[i])` * Copies correctly even where the ranges `[p,p+n)` and `[s,s+n)` overlap * Returns: `s` | Linear | | `X::copy(s,p,n)` | `X::char_type*` | * Requires: `p` not in `[s,s+n)` * Returns: `s` * For each `i` in `[0,n)`, performs `X::assign(s[i], p[i])` | Linear | | `X::assign(r,d)` | (Not used) | Assigns `r = d` | Constant | | `X::assign(s,n,c)` | `X::char_type*` | * For each `i` in `[0,n)`, performs `X::assign(s[i], c)`. * Returns: `s` | Linear | | `X::not_eof(e)` | `X::int_type` | Returns: * `e` if `X::eq_int_type(e, X::eof())` is false * Otherwise a value `f` such that `X::eq_int_type(f, X::eof())` is false | Constant | | `X::to_char_type(e)` | `X::char_type` | Returns: * If for some `c`, `X::eq_int_type(e, X::to_int_type(c))` is true, `c` * Else some unspecified value | Constant | | `X::to_int_type(c)` | `X::int_type` | Returns: some value `e`, constrained by the definitions of `X::to_char_type` and `X::eq_int_type` | Constant | | `X::eq_int_type(e,f)` | `bool` | * For all `c` and `d`, `X::eq(c,d)` is equal to `X::eq_int_type(X::to_int_type(c), X::to_int_type(d))` * Returns: + Yields `X::eq(c,d)` if for some `c` and `d`, `e == X::to_int_type(c)` and `f == X::to_int_type(d)` + Otherwise, yields true if `e` and `f` are both copies of `X::eof()` + Otherwise, yields false if one of `e` and `f` is a copy of `X::eof()` and the other is not + Otherwise the value is unspecified | Constant | | `X::eof()` | `X::int_type` | Returns: a value `e` such that `X::eq_int_type(e, X::to_int_type(c))` is false for all values `c` | Constant | ### Standard library CharTraits is required by the following standard library class templates as a template type parameter: | | | --- | | Strings | | [basic\_string](../string/basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) | | [basic\_string\_view](../string/basic_string_view "cpp/string/basic string view") (C++17) | read-only string view (class template) | | Streams | | [basic\_ios](../io/basic_ios "cpp/io/basic ios") | manages an arbitrary stream buffer (class template) | | [basic\_istream](../io/basic_istream "cpp/io/basic istream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input interface (class template) | | [basic\_ifstream](../io/basic_ifstream "cpp/io/basic ifstream") | implements high-level file stream input operations (class template) | | [basic\_istringstream](../io/basic_istringstream "cpp/io/basic istringstream") | implements high-level string stream input operations (class template) | | [basic\_ispanstream](../io/basic_ispanstream "cpp/io/basic ispanstream") (C++23) | implements fixed character buffer input operations (class template) | | [basic\_ostream](../io/basic_ostream "cpp/io/basic ostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level output interface (class template) | | [basic\_ofstream](../io/basic_ofstream "cpp/io/basic ofstream") | implements high-level file stream output operations (class template) | | [basic\_ostringstream](../io/basic_ostringstream "cpp/io/basic ostringstream") | implements high-level string stream output operations (class template) | | [basic\_osyncstream](../io/basic_osyncstream "cpp/io/basic osyncstream") (C++20) | synchronized output stream wrapper (class template) | | [basic\_ospanstream](../io/basic_ospanstream "cpp/io/basic ospanstream") (C++23) | implements fixed character buffer output operations (class template) | | [basic\_iostream](../io/basic_iostream "cpp/io/basic iostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input/output interface (class template) | | [basic\_fstream](../io/basic_fstream "cpp/io/basic fstream") | implements high-level file stream input/output operations (class template) | | [basic\_stringstream](../io/basic_stringstream "cpp/io/basic stringstream") | implements high-level string stream input/output operations (class template) | | [basic\_spanstream](../io/basic_spanstream "cpp/io/basic spanstream") (C++23) | implements fixed character buffer input/output operations (class template) | | Stream iterators | | [istream\_iterator](../iterator/istream_iterator "cpp/iterator/istream iterator") | input iterator that reads from `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` (class template) | | [ostream\_iterator](../iterator/ostream_iterator "cpp/iterator/ostream iterator") | output iterator that writes to `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` (class template) | | Stream buffers | | [basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf") | abstracts a raw device (class template) | | [basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf") | implements raw file device (class template) | | [basic\_stringbuf](../io/basic_stringbuf "cpp/io/basic stringbuf") | implements raw string device (class template) | | [basic\_syncbuf](../io/basic_syncbuf "cpp/io/basic syncbuf") (C++20) | synchronized output device wrapper (class template) | | [basic\_spanbuf](../io/basic_spanbuf "cpp/io/basic spanbuf") (C++23) | implements raw fixed character buffer device (class template) | | Stream buffer iterators | | [istreambuf\_iterator](../iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator") | input iterator that reads from `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) | | [ostreambuf\_iterator](../iterator/ostreambuf_iterator "cpp/iterator/ostreambuf iterator") | output iterator that writes to `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) | CharTraits is satisfied by the following standard library classes: | | | | | --- | --- | --- | | ``` template<> class char_traits<char>; template<> class char_traits<wchar_t>; template<> class char_traits<char8_t>; template<> class char_traits<char16_t>; template<> class char_traits<char32_t>; ``` | | (since C++20)(since C++11)(since C++11) | cpp C++ named requirements: Swappable C++ named requirements: Swappable ================================= Any lvalue or rvalue of this type can be swapped with any lvalue or rvalue of some other type, using unqualified function call `swap()` in the context where both `[std::swap](../algorithm/swap "cpp/algorithm/swap")` and the user-defined `swap()`s are visible. ### Requirements Type U is swappable with type T if, for any object u of type U and any object t of type T, | Expression | Requirements | Semantics | | --- | --- | --- | | `#include <utility> using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(u, t);` | After the call, the value of `t` is the value held by `u` before the call, and the value of `u` is the value held by `t` before the call. | Calls the function named `swap()` found by overload resolution among all functions with that name that are found by [argument-dependent lookup](../language/adl "cpp/language/adl") and the two `[std::swap](../algorithm/swap "cpp/algorithm/swap")` templates defined in the header [`<utility>`](../header/utility "cpp/header/utility"). | | `#include <utility> using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(t, u);` | same | same | Many standard library functions (for example, many algorithms) expect their arguments to satisfy Swappable, which means that any time the standard library performs a swap, it uses the equivalent of `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(t, u);`. Typical implementations either. 1) Define a non-member swap in the enclosing namespace, which may forward to a member swap if access to non-public data members is required 2) Define a [friend function](../language/friend "cpp/language/friend") in-class (this approach hides the class-specific swap from name lookup other than ADL) ### Notes It is unspecified whether [`<utility>`](../header/utility "cpp/header/utility") is actually included when the standard library functions perform the swap, so the user-provided `swap()` should not expect it to be included. ### Example ``` #include <iostream> #include <vector> struct IntVector { std::vector<int> v; IntVector& operator=(IntVector) = delete; // not assignable void swap(IntVector& other) { v.swap(other.v); } void operator()(auto rem, char term = ' ') { for(std::cout << rem << " { "; int e: v) { std::cout << e << ' '; } std::cout << "}" << term; } }; void swap(IntVector& v1, IntVector& v2) { v1.swap(v2); } int main() { IntVector v1{ {1,1,1,1,1} }, v2{ {2222,2222} }; auto prn = [&]{ v1("v1"), v2("v2", '\n'); }; // std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable prn(); std::iter_swap(&v1, &v2); // OK: library calls unqualified swap() prn(); std::ranges::swap(v1, v2); // OK: library calls unqualified swap() prn(); } ``` Output: ``` v1 { 1 1 1 1 1 } v2 { 2222 2222 } v1 { 2222 2222 } v2 { 1 1 1 1 1 } v1 { 1 1 1 1 1 } v2 { 2222 2222 } ``` ### See also | | | | --- | --- | | [is\_swappable\_withis\_swappableis\_nothrow\_swappable\_withis\_nothrow\_swappable](../types/is_swappable "cpp/types/is swappable") (C++17)(C++17)(C++17)(C++17) | checks if objects of a type can be swapped with objects of same or different type (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) | cpp C++ named requirements: Erasable C++ named requirements: Erasable ================================ Specifies that an object of the type can be destroyed by a given [Allocator](allocator "cpp/named req/Allocator"). ### Requirements The type `T` is **Erasable** from the [Container](container "cpp/named req/Container") `X` whose `value_type` is identical to `T` if, given. | | | | --- | --- | | `A` | an allocator type | | `m` | an lvalue of type `A` | | `p` | the pointer of type `T*` prepared by the container | where `X::allocator_type` is identical to `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<T>`, the following expression is well-formed: ``` std::allocator_traits<A>::destroy(m, p); ``` If `X` is not allocator-aware or is a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specialization, the term is defined as if `A` were `[std::allocator](http://en.cppreference.com/w/cpp/memory/allocator)<T>`, except that no allocator object needs to be created, and user-defined specializations of `[std::allocator](../memory/allocator "cpp/memory/allocator")` are not instantiated. ### Notes All [standard library containers](../container "cpp/container") require that their element type satisfies Erasable. | | | | --- | --- | | With the default allocator, this requirement is equivalent to the validity of `p->~T()`, which accepts class types with accessible destructors and all scalar types, but rejects array types, function types, reference types, and void. | (until C++20) | | With the default allocator, this requirement is equivalent to the validity of `[std::destroy\_at](http://en.cppreference.com/w/cpp/memory/destroy_at)(p)`, which accepts class types with accessible destructors and all scalar types, as well as arrays thereof. | (since C++20) | Although it is required that customized `destroy` is used when destroying elements of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice. ### See also | | | --- | | [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") | | [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") | | [EmplaceConstructible](emplaceconstructible "cpp/named req/EmplaceConstructible") | | [Destructible](destructible "cpp/named req/Destructible") | cpp C++ named requirements: LegacyOutputIterator C++ named requirements: LegacyOutputIterator ============================================ A **LegacyOutputIterator** is a [LegacyIterator](iterator "cpp/named req/Iterator") that can write to the pointed-to element. An example of a type that implements LegacyOutputIterator is [std::ostream\_iterator](../iterator/ostream_iterator "cpp/iterator/ostream iterator"). When [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator"), [LegacyBidirectionalIterator](bidirectionaliterator "cpp/named req/BidirectionalIterator"), or [LegacyRandomAccessIterator](randomaccessiterator "cpp/named req/RandomAccessIterator") satisfies the LegacyOutputIterator requirements in addition to its own requirements, it is described as **mutable**. ### Requirements The type `X` satisfies LegacyOutputIterator if. * The type `X` satisfies [LegacyIterator](iterator "cpp/named req/Iterator") * `X` is a class type or a pointer type And, given. * `o`, a value of some type that is writable to the output iterator (there may be multiple types that are writable, e.g. if `operator=` may be a template. There is no notion of `value_type` as for the input iterators) * `r`, an lvalue of type `X`, The following expressions must be valid and have their specified effects. | Expression | Return | Equivalent expression | Pre-condition | Post-conditions | Notes | | --- | --- | --- | --- | --- | --- | | `*r = o` | (not used) | | `r` is dereferenceable | `r` is incrementable | After this operation `r` is not required to be dereferenceable and any copies of the previous value of `r` are no longer required to be dereferenceable or incrementable. | | `++r` | `X&` | | `r` is incrementable | `r` and `++r` designate the same iterator object, `r` is dereferenceable or past-the-end | After this operation `r` is not required to be incrementable and any copies of the previous value of `r` are no longer required to be dereferenceable or incrementable. | | `r++` | convertible to `const X&` | `X temp = r; ++r; return temp;` | | | | | `*r++ = o` | (not used) | `*r = o; ++r;` | | | | ### Notes The only valid use of `operator*` with an output iterator is on the left of an assignment: `operator*` may return a proxy object, which defines a member `operator=` (which may be a template). Equality and inequality may not be defined for output iterators. Even if an `operator==` is defined, `x == y` need not imply `++x == ++y`. Assignment through the same value of an output iterator happens only once: algorithms on output iterators must be single-pass algorithms. Assignment through an output iterator is expected to alternate with incrementing. Double-increment is undefined behavior (C++ standard currently claims that double increment is supported, contrary to the STL documentation; this is [LWG #2035](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2035)). Pure output-only iterator is allowed to declare its `iterator_traits<X>::value_type`, `iterator_traits<X>::difference_type`, `iterator_traits<X>::pointer`, and `iterator_traits<X>::reference` to be `void` (and iterators such as `[std::back\_insert\_iterator](../iterator/back_insert_iterator "cpp/iterator/back insert iterator")` do just that except for `difference_type`, which is now defined to satisfy `[std::output\_iterator](../iterator/output_iterator "cpp/iterator/output iterator")` (since C++20)). ### Standard library The following standard library iterators are output iterators that are not forward iterators: * `[std::ostream\_iterator](../iterator/ostream_iterator "cpp/iterator/ostream iterator")` * `[std::ostreambuf\_iterator](../iterator/ostreambuf_iterator "cpp/iterator/ostreambuf iterator")` * `[std::insert\_iterator](../iterator/insert_iterator "cpp/iterator/insert iterator")` * `[std::back\_insert\_iterator](../iterator/back_insert_iterator "cpp/iterator/back insert iterator")` * `[std::front\_insert\_iterator](../iterator/front_insert_iterator "cpp/iterator/front insert iterator")` ### See also | | | | --- | --- | | [output\_iterator](../iterator/output_iterator "cpp/iterator/output iterator") (C++20) | specifies that a type is an output iterator for a given value type, that is, values of that type can be written to it and it can be both pre- and post-incremented (concept) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions |
programming_docs
cpp C++ named requirements: EqualityComparable C++ named requirements: EqualityComparable ========================================== The type must work with == operator and the result should have standard semantics. ### Requirements The type `T` satisfies EqualityComparable if. Given. * `a`, `b`, and `c`, expressions of type `T` or `const T` The following expressions must be valid and have their specified effects. | Expression | Return type | Requirements | | --- | --- | --- | | `a == b` | [implicitly convertible](../language/implicit_cast "cpp/language/implicit cast") to `bool` | Establishes an [equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation), that is, it satisfies the following properties: * For all values of `a`, `a == a` yields `true`. * If `a == b`, then `b == a` * If `a == b` and `b == c`, then `a == c` | ### Notes To satisfy this requirement, types that do not have built-in [comparison operators](../language/operator_comparison "cpp/language/operator comparison") have to provide a [user-defined operator==](../language/operators "cpp/language/operators"). For the types that are both EqualityComparable and [LessThanComparable](lessthancomparable "cpp/named req/LessThanComparable"), the C++ standard library makes a distinction between *equality*, which is the value of the expression `a == b` and *equivalence*, which is the value of the expression `!(a < b) && !(b < a)`. ### See also | | | | --- | --- | | [equality\_comparableequality\_comparable\_with](../concepts/equality_comparable "cpp/concepts/equality comparable") (C++20) | specifies that operator `==` is an equivalence relation (concept) | cpp C++ named requirements: Predicate C++ named requirements: Predicate ================================= The **Predicate** requirements describe a callable that returns a value testable as a `bool`. Predicate is typically used with algorithms that take input data (individual objects/containers) and a predicate, which is then called on input data to decide on further course of action. Some examples of predicate usage in C++ standard library are: * `[std::all\_of](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)`, `[std::any\_of](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)`, `[std::none\_of](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)` Take an array of elements and a predicate as an input. Call predicate on individual input elements, and return true if for all/any/none elements, predicate returns true. * `[std::find\_if](http://en.cppreference.com/w/cpp/algorithm/find)` Take sequence of elements, and a predicate. Return first element in the sequence, for which predicate returns value equal to `true` Description of algorithm facilities, given above, is crude and intended to explain Predicate in simple terms. For detailed info, refer to individual pages. In other words, if an algorithm takes a Predicate `pred` and an iterator `first`, it should be able to test the object of the type pointed to by the iterator `first` using the given predicate via a construct like `if(pred(*first)) {...}`. The function object `pred` shall not apply any non-constant function through the dereferenced iterator and must accept a `const` object argument, with the same behavior regardless of whether its argument is `const` or non-`const` (since C++20). This function object may be a pointer to function or an object of a type with an appropriate function call operator. ### Requirements * [FunctionObject](functionobject "cpp/named req/FunctionObject") ### See also | | | | --- | --- | | [predicate](../concepts/predicate "cpp/concepts/predicate") (C++20) | specifies that a callable type is a Boolean predicate (concept) | cpp C++ named requirements: TimedMutex C++ named requirements: TimedMutex ================================== The **TimedMutex** requirements extend the [TimedLockable](timedlockable "cpp/named req/TimedLockable") requirements to include inter-thread synchronization. ### Requirements * [TimedLockable](timedlockable "cpp/named req/TimedLockable") * [Mutex](mutex "cpp/named req/Mutex") Additionally, for an object `m` of TimedMutex type: * The expression `m.try_lock_for(duration)` has the following properties + Behaves as an atomic operation. + Attempts to obtain exclusive ownership of the mutex within the duration specified by `duration`. If `duration` is less or equal `duration.zero()`, attempts to obtain the ownership without blocking (as if by `try_lock()`). Otherwise, this function blocks until the mutex is acquired or until the time specified by `duration` passes. It returns within `duration` only if it succeeds, but it is allowed to fail to acquire the mutex even if at some point in time during `duration` it was not owned by another thread. In any case, it returns `true` if the mutex was acquired and `false` otherwise. + If `try_lock_for(duration)` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). + The behavior is undefined if the calling thread already owns the mutex (except if m is `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")`). + An exception may be thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). * The expression `m.try_lock_until(time_point)` has the following properties + Behaves as an atomic operation. + Attempts to obtain exclusive ownership of the mutex within the time left until `time_point`. If `time_point` already passed, attempts to obtain the ownership without blocking (as if by `try_lock()`). Otherwise, this function blocks until the mutex is acquired or until the time specified by `time_point` passes. It returns before `time_point` only if it succeeds, but it is allowed to fail to acquire the mutex even if at some point in time before `time_point` it was not owned by another thread. In any case, it returns `true` if the mutex was acquired and `false` otherwise. + If `try_lock_until(time_point)` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). + The behavior is undefined if the calling thread already owns the mutex (except if m is `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")`). + An exception may be thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Library types The following standard library types satisfy **TimedMutex**: * `[std::timed\_mutex](../thread/timed_mutex "cpp/thread/timed mutex")` * `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")` * `[std::shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex")` ### 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 2093](https://cplusplus.github.io/LWG/issue2093) | C++11 | timeout-related exceptions were missing in the specification | mentioned | ### See also * [Thread support library](../thread "cpp/thread") * [TimedLockable](timedlockable "cpp/named req/TimedLockable") * [Mutex](mutex "cpp/named req/Mutex") cpp C++ named requirements: SharedLockable C++ named requirements: SharedLockable ====================================== The **SharedLockable** requirements describe the minimal characteristics of types that provide shared blocking semantics for execution agents (i.e. threads). ### Requirements For type `L` to be SharedLockable, the following conditions have to be satisfied for an object `m` of type `L`: | Expression | Preconditions | Effects | Return value | | --- | --- | --- | --- | | `m.lock_shared()` | | Blocks until a lock can be obtained for the current execution agent (thread, process, task). If an exception is thrown, no lock is obtained. | | | `m.try_lock_shared()` | | Attempts to obtain a lock for the current execution agent (thread, process, task) without blocking. If an exception is thrown, no lock is obtained. | `true` if the lock was obtained, `false` otherwise | | `m.unlock_shared()` | The current execution agent holds a shared lock on `m`. | Releases the shared lock held by the execution agent. Throws no exceptions. | | #### Shared locks A lock on an object is said to be *shared lock* if it is acquired by a call to `lock_shared`, `try_lock_shared`, `try_lock_shared_for`, or `try_lock_shared_until` member function. ### See also * [Thread support library](../thread "cpp/thread") * [SharedTimedLockable](sharedtimedlockable "cpp/named req/SharedTimedLockable") * [SharedMutex](sharedmutex "cpp/named req/SharedMutex") cpp C++ named requirements: LegacyIterator C++ named requirements: LegacyIterator ====================================== The **LegacyIterator** requirements describe types that can be used to identify and traverse the elements of a container. LegacyIterator is the base set of requirements used by other iterator types: [LegacyInputIterator](inputiterator "cpp/named req/InputIterator"), [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator"), [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator"), [LegacyBidirectionalIterator](bidirectionaliterator "cpp/named req/BidirectionalIterator"), and [LegacyRandomAccessIterator](randomaccessiterator "cpp/named req/RandomAccessIterator"). Iterators can be thought of as an abstraction of pointers. ### Requirements The type `It` satisfies LegacyIterator if. * The type `It` satisfies [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), and * The type `It` satisfies [CopyAssignable](copyassignable "cpp/named req/CopyAssignable"), and * The type `It` satisfies [Destructible](destructible "cpp/named req/Destructible"), and * [lvalues](../language/value_category "cpp/language/value category") of type `It` satisfy [Swappable](swappable "cpp/named req/Swappable"), and * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>` has member typedefs `value_type` (until C++20), `difference_type`, `reference`, `pointer`, and `iterator_category` , and * Given `r`, an lvalue of type `It`, the following expressions must be valid and have their specified effects: | Expression | Return Type | Precondition | | --- | --- | --- | | `*r` | unspecified | `r` is *dereferenceable* (see below) | | `++r` | `It&` | `r` is *incrementable* (the behavior of the expression `++r` is defined) | ### Dereferenceable iterators Iterators for which the behavior of the expression `*i` is defined are called *dereferenceable*. Iterators are not dereferenceable if. * they are [past-the-end iterators](../container/vector/end "cpp/container/vector/end") (including pointers past the end of an array) or [before-begin iterators](../container/forward_list/before_begin "cpp/container/forward list/before begin"). Such iterators may be dereferenceable in a particular implementation, but the library never assumes that they are. * they are *singular* iterators, that is, iterators that are not associated with any sequence. A null pointer, as well as a default-constructed pointer (holding an indeterminate value) is singular * they were [invalidated](../container#Iterator_invalidation "cpp/container") by one of the iterator-invalidating operations on the sequence to which they refer. | | | | | | | --- | --- | --- | --- | --- | | Concept For the definition of `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")`, the following exposition-only concept is defined. | | | | | --- | --- | --- | | ``` template<class I> concept __LegacyIterator = requires(I i) { { *i } -> __Referenceable; { ++i } -> std::same_as<I&>; { *i++ } -> __Referenceable; } && std::copyable<I>; ``` | | | where the exposition-only concept `__Referenceable<T>` is satisfied if and only if `T&` is a valid type (in particular, `T` must not be `void`). | (since 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 3420](https://cplusplus.github.io/LWG/issue3420) | C++20 | the exposition-only concept checks `copyable` first | `copyable` is checked only if the requires-expression yields true | ### See also | | | | --- | --- | | [input\_or\_output\_iterator](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator") (C++20) | specifies that objects of a type can be incremented and dereferenced (concept) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions | cpp C++ named requirements: EmplaceConstructible (since C++11) C++ named requirements: EmplaceConstructible (since C++11) ========================================================== Specifies that an object of the type can be constructed from a given set of arguments in uninitialized storage by a given allocator. ### Requirements The type `T` is **EmplaceConstructible** into the [Container](container "cpp/named req/Container") `X` (whose `value_type` is identical to `T`) from the arguments `args` if, given. | | | | --- | --- | | `A` | an allocator type | | `m` | an lvalue of type `A` | | `p` | the pointer of type `T*` prepared by the container | | `args` | zero or more arguments | where `X::allocator_type` is identical to `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::rebind\_alloc<T>`, the following expression is well-formed: ``` std::allocator_traits<A>::construct(m, p, args); ``` If `X` is not allocator-aware or is a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specialization, the term is defined as if `A` were `std::allocator<T>`, except that no allocator object needs to be created, and user-defined specializations of `[std::allocator](../memory/allocator "cpp/memory/allocator")` are not instantiated. ### Notes Although it is required that customized `construct` is used when constructing elements of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice. ### See also | | | --- | | [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") | | [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") | cpp C++ named requirements: SharedTimedMutex C++ named requirements: SharedTimedMutex ======================================== The **SharedTimedMutex** requirements extend the [TimedMutex](timedmutex "cpp/named req/TimedMutex") requirements to include shared lock ownership mode. ### Requirements * [TimedMutex](timedmutex "cpp/named req/TimedMutex") * [SharedMutex](sharedmutex "cpp/named req/SharedMutex") Additionally, an object `m` of SharedTimedMutex type supports timed shared operations: * The expression `m.try_lock_shared_for(duration)` has the following properties + Behaves as an atomic operation. + Attempts to obtain shared ownership of the mutex within the duration specified by `duration`. If `duration` is less or equal `duration.zero()`, attempts to obtain the ownership without waiting (as if by `try_lock()`). Otherwise, this function blocks until the mutex is acquired or until the time specified by `duration` passes. It returns within `duration` only if it succeeds, but it allowed to fail to acquire the mutex even if at some point in time during `duration` it was not owned by another thread. In any case, it returns `true` if the mutex was acquired and `false` otherwise. + If `try_lock_shared_for(duration)` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). + The behavior is undefined if the calling thread already owns the mutex in any mode. + An exception may be thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). + If an exception is thrown, the shared lock is not acquired. * The expression `m.try_lock_shared_until(time_point)` has the following properties + Behaves as an atomic operation. + Attempts to obtain shared ownership of the mutex within the time left until `time_point`. If `time_point` already passed, attempts to obtain the ownership without locking (as if by `try_lock()`). Otherwise, this function blocks until the mutex is acquired or until the time specified by `time_point` passes. It returns before `time_point` only if it succeeds, but it allowed to fail to acquire the mutex even if at some point in time before `time_point` it was not owned by another thread. In any case, it returns `true` if the mutex was acquired and `false` otherwise. + If `try_lock_shared_until(time_point)` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). + The behavior is undefined if the calling thread already owns the mutex in any mode. + An exception may be thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). + If an exception is thrown, the shared lock is not acquired. ### Library types The following standard library types satisfy **SharedTimedMutex**: * `[std::shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex")` ### See also * [Thread support library](../thread "cpp/thread") * [Mutex](mutex "cpp/named req/Mutex") * [TimedMutex](timedmutex "cpp/named req/TimedMutex") * [SharedMutex](sharedmutex "cpp/named req/SharedMutex") cpp C++ named requirements: Formatter C++ named requirements: Formatter ================================= **Formatter** is a type that abstracts formatting operations for a given formatting argument type and character type. Specializations of `[std::formatter](../utility/format/formatter "cpp/utility/format/formatter")` provided by the standard library are required to meet the requirements of Formatter except as noted otherwise. A **Formatter** is able to format both const and non-const arguments, typically by providing a `format` member function that takes a const reference. ### Requirements A type satisfies Formatter if it satisfies [BasicFormatter](basicformatter "cpp/named req/BasicFormatter") and given. * `Arg`, a formatting argument type * `CharT`, a character type * `Formatter`, a Formatter type for types `Arg` and `CharT` * `OutputIt`, a [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") type * `f`, a value of type `Formatter` * `arg`, an lvalue of type `Arg` * `t`, a value of type convertible to (possibly const) `Arg` * `ParseContext`, an alias of `[std::basic\_format\_parse\_context](http://en.cppreference.com/w/cpp/utility/format/basic_format_parse_context)<CharT>` * `FormatContext`, an alias of `[std::basic\_format\_context](http://en.cppreference.com/w/cpp/utility/format/basic_format_context)<OutputIt, CharT>` * `parse_ctx`, an lvalue of type `ParseContext` * `format_ctx`, an lvalue of type `FormatContext` | Expression | Return type | Semantics | | --- | --- | --- | | `f.format(t, format_ctx)` | `FormatContext::iterator` | * Formats `t` according to the specifiers stored in `f`, writes the output to `format_ctx.out()` and returns an end iterator of the output range. * The output shall only depend on + `t`, + `format_ctx.locale()`, + the range `[parse_ctx.begin(), parse_ctx.end())` from the last call to `f.parse(parse_ctx)`, and + `format_ctx.arg(n)` for any value `n` of type `[std::size\_t](../types/size_t "cpp/types/size t")`. | | `f.format(arg, format_ctx)` | `FormatContext::iterator` | As above, but does not modify `arg`. |
programming_docs
cpp C++ named requirements: UnaryTypeTrait C++ named requirements: UnaryTypeTrait ====================================== A **UnaryTypeTrait** is a class template that describes a property of its template type parameter with an `integral_constant` (typically `bool_constant`) specialization. ### Requirements * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") and [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * Takes one template type parameter (additional template parameters are optional and allowed) * Publicly and unambiguously derived from a specialization of `integral_constant`, known as its *base characteristic* * The member names of the *base characteristic* are not hidden and are unambiguously available ### Standard library The following [type properties](../types#Type_properties "cpp/types") all satisfy UnaryTypeTrait. * Primary type categories * Composite type categories * Type properties * Supported operations * Property queries The following standard library class templates also satisfy UnaryTypeTrait. | | | | --- | --- | | [integral\_constant](../types/integral_constant "cpp/types/integral constant") (C++11) | compile-time constant of specified type with specified value (class template) | | [negation](../types/negation "cpp/types/negation") (C++17) | logical NOT metafunction (class template) | | [std::tuple\_size<std::tuple>](../utility/tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | | [std::tuple\_size<std::array>](../container/array/tuple_size "cpp/container/array/tuple size") (C++11) | obtains the size of an `array` (class template specialization) | | [std::tuple\_size<std::pair>](../utility/pair/tuple_size "cpp/utility/pair/tuple size") (C++11) | obtains the size of a `pair` (class template specialization) | | [variant\_sizevariant\_size\_v](../utility/variant/variant_size "cpp/utility/variant/variant size") (C++17) | obtains the size of the variant's list of alternatives at compile time (class template) (variable template) | | [is\_bind\_expression](../utility/functional/is_bind_expression "cpp/utility/functional/is bind expression") (C++11) | indicates that an object is `std::bind` expression or can be used as one (class template) | | [is\_placeholder](../utility/functional/is_placeholder "cpp/utility/functional/is placeholder") (C++11) | indicates that an object is a standard placeholder or can be used as one (class template) | | [is\_execution\_policy](../algorithm/is_execution_policy "cpp/algorithm/is execution policy") (C++17) | test whether a class represents an execution policy (class template) | cpp C++ named requirements: RandomNumberEngineAdaptor C++ named requirements: RandomNumberEngineAdaptor ================================================= A **RandomNumberEngineAdaptor** is a [RandomNumberEngine](randomnumberengine "cpp/named req/RandomNumberEngine") that transforms the output of another [RandomNumberEngine](randomnumberengine "cpp/named req/RandomNumberEngine"), the latter of which is termed a *base engine*. ### Requirements Given. * `B`, a [RandomNumberEngine](randomnumberengine "cpp/named req/RandomNumberEngine") * `b`, an object of type `B` * `A`, a **RandomNumberEngineAdaptor**, adapting `B` as a base engine * `a`, an object of type `A` | function | semantics | | --- | --- | | `A::A();` | The base engine is initialized as if by its default constructor. | | `bool operator==(const A& lhs, const A& rhs);` | Returns whether `lhs`'s base engine is equal to `rhs`'s base engine or not. | | `A::A(result_type s);` | The base engine is initialized with `s`. | | `template<class Sseq> A::A(Sseq& q);` | The base engine is initialized with `q`. | | `void seed();` | Invokes `b.seed()`. | | `void seed(result_type s);` | Invokes `b.seed(s)`. | | `template<class Sseq> void seed(Sseq& q);` | Invokes `b.seed(q)`. | Furthermore. * The complexity of each function of `A` does not exceed the complexity of the function of `B` * The state of `A` includes the state of `B` * The size of `A`'s state is no less than the size of `b` * Copying `A`'s state includes copying `B`'s state * The textual representation of `A` includes the textual representation of `B` ### Standard library The following standard library facilities satisfy **RandomNumberEngineAdaptor**: | | | | --- | --- | | [discard\_block\_engine](../numeric/random/discard_block_engine "cpp/numeric/random/discard block engine") (C++11) | discards some output of a random number engine (class template) | | [independent\_bits\_engine](../numeric/random/independent_bits_engine "cpp/numeric/random/independent bits engine") (C++11) | packs the output of a random number engine into blocks of a specified number of bits (class template) | | [shuffle\_order\_engine](../numeric/random/shuffle_order_engine "cpp/numeric/random/shuffle order engine") (C++11) | delivers the output of a random number engine in a different order (class template) | cpp C++ named requirements: BinaryTypeTrait C++ named requirements: BinaryTypeTrait ======================================= A **BinaryTypeTrait** is a class template that describes a relationship between its two template type parameters with a `intergral_constant` (typically `bool_constant`) specialization. ### Requirements * [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") and [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") * Takes two template type parameters (additional template parameters are optional and allowed) * Publicly and unambiguously derived from a specialization of `intergral_constant`, known as its *base characteristic* * The member names of the *base characteristic* are not hidden and are unambiguously available ### Standard library The following standard library class templates satisfy **BinaryTypeTrait**. | | | | --- | --- | | [is\_same](../types/is_same "cpp/types/is same") (C++11) | checks if two types are the same (class template) | | [is\_base\_of](../types/is_base_of "cpp/types/is base of") (C++11) | checks if a type is derived from the other type (class template) | | [is\_convertibleis\_nothrow\_convertible](../types/is_convertible "cpp/types/is convertible") (C++11)(C++20) | checks if a type can be converted to the other type (class template) | | [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](../types/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) | | [uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator") (C++11) | checks if the specified type supports uses-allocator construction (class template) | cpp C++ named requirements: TrivialClock C++ named requirements: TrivialClock ==================================== The **TrivialClock** requirements describe the requirements satisfied by several clocks in the [chrono library](../chrono "cpp/chrono"). ### Requirements For a type `TC`: * The type must meet [Clock](clock "cpp/named req/Clock") requirements. * The types `TC::rep`, `TC::duration`, and `TC::time_point` satisfy the requirements of [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable"), [LessThanComparable](lessthancomparable "cpp/named req/LessThanComparable"), [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](copyassignable "cpp/named req/CopyAssignable"), [Destructible](destructible "cpp/named req/Destructible"), and [NumericType](numerictype "cpp/named req/NumericType"). * [lvalues](../language/value_category "cpp/language/value category") of the types `TC::rep`, `TC::duration`, and `TC::time_point` are [Swappable](swappable "cpp/named req/Swappable"). * The function `TC::now()` does not throw exceptions. * The type `TC::time_point::clock` meets the TrivialClock requirements, recursively. ### Usage The following types in the standard library satisfy these requirements: * `[std::chrono::system\_clock](../chrono/system_clock "cpp/chrono/system clock")` * `[std::chrono::steady\_clock](../chrono/steady_clock "cpp/chrono/steady clock")` * `[std::chrono::high\_resolution\_clock](../chrono/high_resolution_clock "cpp/chrono/high resolution clock")` * [`std::filesystem::file_time_type::clock`](../filesystem/file_time_type "cpp/filesystem/file time type") * [`std::chrono::file_clock`](../chrono/file_clock "cpp/chrono/file clock") cpp C++ named requirements: StandardLayoutType C++ named requirements: StandardLayoutType ========================================== Specifies that a type is a standard layout type. Standard layout types are useful for communicating with code written in other programming languages. Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements The following types are collectively called *standard-layout types*: * [scalar types](scalartype "cpp/named req/ScalarType") * [standard-layout class types](../language/classes#Standard-layout_class "cpp/language/classes") * arrays of such types * cv-qualified versions of these types ### Properties See [Standard layout](../language/data_members#Standard_layout "cpp/language/data 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 | | --- | --- | --- | --- | | [CWG 1672](https://cplusplus.github.io/CWG/issues/1672.html) | C++11 | first non-static data member rule ignoredexistence of empty base classes | first non-static data member rulemade recursive | | [CWG 1813](https://cplusplus.github.io/CWG/issues/1813.html) | C++11 | class with a member defined in an indirect basewasn't technically standard-layout | all member declarations must bein the same class | | [CWG 2120](https://cplusplus.github.io/CWG/issues/2120.html) | C++11 | array as first member wasn't considered whencomparing the first element type with type of a base | array members are considered | ### See also | | | | --- | --- | | [is\_standard\_layout](../types/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 C++ named requirements: LiteralType C++ named requirements: LiteralType =================================== Specifies that a type is a *literal type*. Literal types are the types of [`constexpr` variables](../language/constexpr "cpp/language/constexpr") and they can be constructed, manipulated, and returned from [`constexpr` functions](../language/constexpr "cpp/language/constexpr"). Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements A literal type is any of the following: | | | | --- | --- | | * possibly cv-qualified `void` (so that `constexpr` functions can return void); | (since C++14) | * [scalar type](scalartype "cpp/named req/ScalarType"); * [reference type](../language/reference "cpp/language/reference"); * an [array](../language/array "cpp/language/array") of literal type; * possibly cv-qualified class type that has all of the following properties: * has a trivial (until C++20)`constexpr` (since C++20) [destructor](../language/destructor "cpp/language/destructor"), * is one of + an [aggregate type](../language/aggregate_initialization#Definitions "cpp/language/aggregate initialization"), + a type with at least one `constexpr` (possibly template) constructor that is not a copy or move constructor, | | | | --- | --- | | * a [closure type](../language/lambda "cpp/language/lambda") | (since C++17) | * for [unions](../language/union "cpp/language/union"), at least one non-static data member is of non-volatile literal type, * for non-unions, all non-static data members and base classes are of non-volatile literal types. ### Notes A type can be literal even if all of its constexpr constructors are deleted, inaccessible, or cannot participate in overload resolution. ``` struct A { constexpr A(int) = delete; char c; }; // A is a literal type constexpr A v = std::bit_cast<A>('0'); // OK in C++20 // v has literal type and thus can be constexpr ``` ### Example Literal type that extends string literals: ``` #include <iostream> #include <stdexcept> class conststr { const char* p; std::size_t sz; public: template<std::size_t N> constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {} constexpr char operator[](std::size_t n) const { return n < sz ? p[n] : throw std::out_of_range(""); } constexpr std::size_t size() const { return sz; } }; constexpr std::size_t countlower(conststr s, std::size_t n = 0, std::size_t c = 0) { return n == s.size() ? c : s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) : countlower(s, n + 1, c); } // output function that requires a compile-time constant, for testing template<int n> struct constN { constN() { std::cout << n << '\n'; } }; int main() { std::cout << "the number of lowercase letters in \"Hello, world!\" is "; constN<countlower("Hello, world!")>(); // implicitly converted to conststr } ``` Output: ``` the number of lowercase letters in "Hello, world!" is 9 ``` ### 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 1453](https://cplusplus.github.io/CWG/issues/1453.html) | C++11 | a literal class could have volatile data members | not allowed | | [CWG 1951](https://cplusplus.github.io/CWG/issues/1951.html) | C++11 (class type) C++14 (void) | it was unclear whether cv-qualified`void` and class types are literal types | they are | | [CWG 2096](https://cplusplus.github.io/CWG/issues/2096.html) | C++11 | for a union type to be literal, all its non-static data members must be literal | only one non-static datamember needs to be | ### See also | | | | --- | --- | | [is\_literal\_type](../types/is_literal_type "cpp/types/is literal type") (C++11)(deprecated in C++17)(removed in C++20) | checks if a type is a literal type (class template) | cpp C++ named requirements: TimedLockable C++ named requirements: TimedLockable ===================================== The **TimedLockable** requirements describe the characteristics of types that provide timed exclusive blocking semantics for execution agents (threads, processes, tasks). ### Requirements * [Lockable](lockable "cpp/named req/Lockable") For type `L` to be TimedLockable, given. * `rel_time`, a value of a specialization of `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")`, and * `abs_time`, a value of a specialization of `[std::chrono::time\_point](../chrono/time_point "cpp/chrono/time point")`, the following conditions have to be satisfied for an object `m` of type `L`: | Expression | Effects | Return value | | --- | --- | --- | | `m.try_lock_for(rel_time)` | Blocks for the provided duration `rel_time` or until a lock on `m` is acquired. | `true` if the lock was acquired, `false` otherwise. | | `m.try_lock_until(abs_time)` | Blocks until the provided time point `abs_time` is reached or a lock on `m` is acquired. | `true` if the lock was acquired, `false` otherwise. | ### Notes The `try_lock_for` and `try_lock_until` member functions obtain a non-shared lock on `m` on succcess. ### See also * [Thread support library](../thread "cpp/thread") * [TimedMutex](timedmutex "cpp/named req/TimedMutex") * [Lockable](lockable "cpp/named req/Lockable") * [BasicLockable](basiclockable "cpp/named req/BasicLockable") cpp C++ named requirements: UniformRandomBitGenerator C++ named requirements: UniformRandomBitGenerator ================================================= A uniform random bit generator is a function object returning unsigned integer values such that each value in the range of possible results has (ideally) equal probability. Uniform random bit generators are not intended to be used as random number generators: they are used as the source of random bits (generated in bulk, for efficiency). Any uniform random bit generator may be plugged into any [random number distribution](../numeric/random "cpp/numeric/random") in order to obtain a random number (formally, a random variate). ### Requirements The type `G` satisfies UniformRandomBitGenerator if. Given. * `T`, the type named by `G::result_type` * `g`, a value of type `G` The following expressions must be valid and have their specified effects. | Expression | Return type | Requirements | | --- | --- | --- | | `G::result_type` | `T` | `T` is an unsigned integer type | | `G::min()` | `T` | Returns the smallest value that G's operator() may return. The value is strictly less than `G::max()`. The function must be constexpr. | | `G::max()` | `T` | Returns the largest value that G's operator() may return. The value is strictly greater than `G::min()`. The function must be constexpr. | | `g()` | `T` | Returns a value in the closed interval `[G::min(), G::max()]`. Has amortized constant complexity. | ### Notes All [RandomNumberEngines](randomnumberengine "cpp/named req/RandomNumberEngine") satisfy this requirement. ### Standard library The following standard library facilities expect a UniformRandomBitGenerator type. | | | | --- | --- | | [random\_shuffleshuffle](../algorithm/random_shuffle "cpp/algorithm/random shuffle") (until C++17)(C++11) | randomly re-orders elements in a range (function template) | | [generate\_canonical](../numeric/random/generate_canonical "cpp/numeric/random/generate canonical") (C++11) | evenly distributes real values of given precision across [0, 1) (function template) | | [uniform\_int\_distribution](../numeric/random/uniform_int_distribution "cpp/numeric/random/uniform int distribution") (C++11) | produces integer values evenly distributed across a range (class template) | | [uniform\_real\_distribution](../numeric/random/uniform_real_distribution "cpp/numeric/random/uniform real distribution") (C++11) | produces real values evenly distributed across a range (class template) | | all other random number distributions | The following standard library facilities satisfy UniformRandomBitGenerator without additionally satisfying [RandomNumberEngine](randomnumberengine "cpp/named req/RandomNumberEngine"): | | | | --- | --- | | [random\_device](../numeric/random/random_device "cpp/numeric/random/random device") (C++11) | non-deterministic random number generator using hardware entropy source (class) | ### See also | | | | --- | --- | | [uniform\_random\_bit\_generator](../numeric/random/uniform_random_bit_generator "cpp/numeric/random/uniform random bit generator") (C++20) | specifies that a type qualifies as a uniform random bit generator (concept) | cpp C++ named requirements: BinaryPredicate C++ named requirements: BinaryPredicate ======================================= **BinaryPredicate** is a set of requirements expected by some of the standard library facilities from the user-provided arguments. Given a BinaryPredicate `bin_pred` and a pair of iterators `iter1` and `iter2` or an iterator `iter` and a (possibly `const`) (since C++20) value `value`, the expression `bin_pred(*iter1, *iter2)` or, respectively, `bin_pred(*iter, value)`, must be [contextually convertible](../language/implicit_cast "cpp/language/implicit cast") to `bool`. In addition, evaluation of that expression is not allowed to call non-const member functions of the dereferenced iterators ; syntactically, the predicate must accept `const` object arguments, with the same behavior regardless of whether its arguments are `const` or non-`const` (since C++20). ### Requirements * [Predicate](predicate "cpp/named req/Predicate") * [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible") (unless otherwise specified) ### Standard library The following standard library facilities expect a BinaryPredicate which isn't a [Compare](compare "cpp/named req/Compare") type. | | | | --- | --- | | [unique](../container/forward_list/unique "cpp/container/forward list/unique") (C++11) | removes consecutive duplicate elements (public member function of `std::forward_list<T,Allocator>`) | | [unique](../container/list/unique "cpp/container/list/unique") | removes consecutive duplicate elements (public member function of `std::list<T,Allocator>`) | | [find\_end](../algorithm/find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | | [find\_first\_of](../algorithm/find_first_of "cpp/algorithm/find first of") | searches for any one of a set of elements (function template) | | [adjacent\_find](../algorithm/adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [mismatch](../algorithm/mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | | [equal](../algorithm/equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [is\_permutation](../algorithm/is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | | [search](../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) | | [search\_n](../algorithm/search_n "cpp/algorithm/search n") | searches a range for a number of consecutive copies of an element (function template) | | [unique](../algorithm/unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [unique\_copy](../algorithm/unique_copy "cpp/algorithm/unique copy") | creates a copy of some range of elements that contains no consecutive duplicates (function template) | | [not2](../utility/functional/not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `[std::binary\_negate](../utility/functional/binary_negate "cpp/utility/functional/binary negate")` object (function template) | | [unordered\_set](../container/unordered_set "cpp/container/unordered set") (C++11) | collection of unique keys, hashed by keys (class template) | | [unordered\_map](../container/unordered_map "cpp/container/unordered map") (C++11) | collection of key-value pairs, hashed by keys, keys are unique (class template) | | [unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset") (C++11) | collection of keys, hashed by keys (class template) | | [unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap") (C++11) | collection of key-value pairs, hashed by keys (class template) |
programming_docs
cpp C++ named requirements: AllocatorAwareContainer C++ named requirements: AllocatorAwareContainer =============================================== An **AllocatorAwareContainer** is a [Container](container "cpp/named req/Container") that holds an instance of an [Allocator](allocator "cpp/named req/Allocator") and uses that instance in all its member functions to allocate and deallocate memory and to construct and destroy objects in that memory (such objects may be container elements, nodes, or, for unordered containers, bucket arrays), except that `[std::basic\_string](../string/basic_string "cpp/string/basic string")` specializations do not use the allocators for construction/destruction of their elements (since C++23). The following rules apply to container construction. * Copy constructors of AllocatorAwareContainers obtain their instances of the allocator by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction` on the allocator of the container being copied. * Move constructors obtain their instances of allocators by move-constructing from the allocator belonging to the old container. * All other constructors take a `const allocator_type&` parameter. The only way to replace an allocator is copy-assignment, move-assignment, and swap: * Copy-assignment will replace the allocator only if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true` * Move-assignment will replace the allocator only if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true` * Swap will replace the allocator only if `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is `true`. Specifically, it will exchange the allocator instances through an unqualified call to the non-member function swap, see [Swappable](swappable "cpp/named req/Swappable"). Note: swapping two containers with unequal allocators if `propagate_on_container_swap` is `false` is undefined behavior. * The accessor `get_allocator()` obtains a copy of the allocator that was used to construct the container or installed by the most recent allocator replacement operation. ### Requirements #### Legend | | | | --- | --- | | `X` | Container type | | `T` | Element type | | `A` | Allocator for `T` | | `a`, `b` | Objects of type `X` (non-const lvalue) | | `t` | Object of type `X` (lvalue or const rvalue) | | `rv` | Object of type `X` (non-const rvalue) | | `m` | Object of type `A` | | expression | return type | pre/requirements | post/effects | complexity | | --- | --- | --- | --- | --- | | `allocator_type` | `A` | `allocator_type::value_type` must be the same as `X::value_type` | | compile-time | | `get_allocator()` | `A` | | | constant | | `X u;` | | `A` is [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible") | `u.empty() == true && u.get_allocator() == A()` | constant | | `X u(m);` | | | `u.empty() == true && u.get_allocator() == m` | constant | | `X u(t,m);` | | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` | `u == t && u.get_allocator() == m` | linear | | `X u(rv);` | | Move constructor of `A` must not throw exceptions | `u` has the same elements and an equal allocator as `rv` had before the construction | constant | | `X u(rv,m);` | | `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X` | The elements of `u` are the same or copies of those of `rv` and `u.get_allocator() == m` | constant if `m == rv.get_allocator()`, otherwise linear | | `a = t` | `X&` | `T` is [CopyInsertable](copyinsertable "cpp/named req/CopyInsertable") into `X` and [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") | `a == t` | linear | | `a = rv` | `X&` | If the allocator will *not* be replaced by move-assignment (see above), then `T` is [MoveInsertable](moveinsertable "cpp/named req/MoveInsertable") into `X` and [MoveAssignable](moveassignable "cpp/named req/MoveAssignable") | All existing elements of `a` are either move assigned to or destroyed; if `a` and `rv` do not refer the same object, `a` is equal to the value that `rv` had before the assignment | linear | | `a.swap(b)` | void | | Exchanges the contents of `a` and `b` | constant | ### Notes Allocator-aware containers always call `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<A>::construct(m, p, args)` to construct an object of type `T` at `p` using `args`, with `m == get_allocator()`. The default `construct` in `[std::allocator](../memory/allocator "cpp/memory/allocator")` calls `::new((void*)p) T(args)` (until C++20)`[std::allocator](../memory/allocator "cpp/memory/allocator")` has no `construct` member and `[std::construct\_at](http://en.cppreference.com/w/cpp/memory/construct_at)(p, args)` is called when constructing elements (since C++20), but specialized allocators may choose a different definition. ### Standard library All standard library containers except `[std::array](../container/array "cpp/container/array")` are AllocatorAwareContainers: * `[std::basic\_string](../string/basic_string "cpp/string/basic string")` * `[std::deque](../container/deque "cpp/container/deque")` * `[std::forward\_list](../container/forward_list "cpp/container/forward list")` * `[std::list](../container/list "cpp/container/list")` * `[std::vector](../container/vector "cpp/container/vector")` * `[std::map](../container/map "cpp/container/map")` * `[std::multimap](../container/multimap "cpp/container/multimap")` * `[std::set](../container/set "cpp/container/set")` * `[std::multiset](../container/multiset "cpp/container/multiset")` * `[std::unordered\_map](../container/unordered_map "cpp/container/unordered map")` * `[std::unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap")` * `[std::unordered\_set](../container/unordered_set "cpp/container/unordered set")` * `[std::unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset")` ### 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 2839](https://cplusplus.github.io/LWG/issue2839) | C++11 | self move assignment of standard containers was not allowed | allowed but the result is unspecifed | cpp C++ named requirements: LessThanComparable C++ named requirements: LessThanComparable ========================================== The type must work with < operator and the result should have standard semantics. ### Requirements The type `T` satisfies LessThanComparable if. Given. * `a`, `b`, and `c`, expressions of type `T` or `const T` The following expressions must be valid and have their specified effects. | Expression | Return type | Requirements | | --- | --- | --- | | `a < b` | [implicitly convertible](../language/implicit_cast "cpp/language/implicit cast") to `bool` | Establishes [strict weak ordering](https://en.wikipedia.org/wiki/Strict_weak_ordering "enwiki:Strict weak ordering") relation with the following properties * For all `a`, `!(a < a)` * If `a < b` then `!(b < a)` * If `a < b` and `b < c` then `a < c` * Defining `equiv(a, b)` as `!(a < b) && !(b < a)`, if `equiv(a, b)` and `equiv(b, c)`, then `equiv(a, c)` | ### Notes To satisfy this requirement, types that do not have built-in [comparison operators](../language/operator_comparison "cpp/language/operator comparison") have to provide a [user-defined operator<](../language/operators#Comparison_operators "cpp/language/operators"). For the types that are both [EqualityComparable](equalitycomparable "cpp/named req/EqualityComparable") and LessThanComparable, the C++ standard library makes a distinction between *equality*, which is the value of the expression `a == b` and *equivalence*, which is the value of the expression `!(a < b) && !(b < a)`. ### See also | | | | --- | --- | | [Compare](compare "cpp/named req/Compare") | a [BinaryPredicate](binarypredicate "cpp/named req/BinaryPredicate") that establishes an ordering relation (named requirement) | cpp C++ named requirements: ValueSwappable C++ named requirements: ValueSwappable ====================================== Two objects of this type can be dereferenced and the resulting values can be swapped using unqualified function call `swap()` in the context where both `[std::swap](../algorithm/swap "cpp/algorithm/swap")` and the user-defined `swap()`s are visible. ### Requirements A type T is ValueSwappable if. 1. `T` satisfies the [LegacyIterator](iterator "cpp/named req/Iterator") requirements 2. For any dereferenceable object `x` of type `T` (that is, any value other than the end iterator), `*x` satisfies the [Swappable](swappable "cpp/named req/Swappable") requirements. Many standard library functions expect their arguments to satisfy ValueSwappable, which means that any time the standard library performs a swap, it uses the equivalent of `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(\*iter1, \*iter2);`. ### Example ``` #include <iostream> #include <vector> class IntVector { std::vector<int> v; // IntVector& operator=(IntVector); // not assignable (C++98 way) public: IntVector& operator=(IntVector) = delete; // not assignable void swap(IntVector& other) { v.swap(other.v); } }; void swap(IntVector& v1, IntVector& v2) { v1.swap(v2); } int main() { IntVector v1, v2; // IntVector is Swappable, but not MoveAssignable IntVector* p1 = &v1; IntVector* p2 = &v2; // IntVector* is ValueSwappable std::iter_swap(p1, p2); // OK: iter_swap requires ValueSwappable // std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable } ``` ### See also | | | | --- | --- | | [indirectly\_swappable](../iterator/indirectly_swappable "cpp/iterator/indirectly swappable") (C++20) | specifies that the values referenced by two [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types can be swapped (concept) | cpp C++ named requirements: LegacyBidirectionalIterator C++ named requirements: LegacyBidirectionalIterator =================================================== A **LegacyBidirectionalIterator** is a [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator") that can be moved in both directions (i.e. incremented and decremented). If a **LegacyBidirectionalIterator** `it` originates from a [Container](container "cpp/named req/Container"), then `it`'s `value_type` is the same as the container's, so dereferencing (`*it`) obtains the container's `value_type`. ### Requirements The type `It` satisfies LegacyBidirectionalIterator if. * The type `It` satisfies [LegacyForwardIterator](forwarditerator "cpp/named req/ForwardIterator") And, given. * `a` and `b`, iterators of type `It` * `reference,` the type denoted by `std::iterator_traits<It>::reference` The following expressions must be valid and have their specified effects. | Expression | Return | Equivalent expression | Notes | | --- | --- | --- | --- | | `--a` | `It&` | | Preconditions: * `a` is decrementable (there exists such `b` that `a == ++b`) Postconditions:* a is dereferenceable * `--(++a) == a` * If `--a == --b` then `a == b` * `a` and `--a` designate the same iterator object | | `a--` | convertible to `const It&` | `It temp = a; --a; return temp;` | | | `*a--` | `reference` | | | A *mutable* LegacyBidirectionalIterator is a LegacyBidirectionalIterator that additionally satisfies the [LegacyOutputIterator](outputiterator "cpp/named req/OutputIterator") requirements. ### Notes The begin iterator is not decrementable and the behavior is undefined if `--container.begin()` is evaluated. A bidirectional iterator does not have to be dereferenceable to be decrementable (in particular, the end iterator is not dereferenceable but is decrementable). | | | | | | | --- | --- | --- | --- | --- | | Concept For the definition of `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")`, the following exposition-only concept is defined. | | | | | --- | --- | --- | | ``` template<class I> concept __LegacyBidirectionalIterator = __LegacyForwardIterator<I> && requires(I i) { { --i } -> std::same_as<I&>; { i-- } -> std::convertible_to<const I&>; { *i-- } -> std::same_as<std::iter_reference_t<I>>; }; ``` | | | where the exposition-only concept `__LegacyForwardIterator` is described in [LegacyForwardIterator#Concept](forwarditerator#Concept "cpp/named req/ForwardIterator"). | (since C++20) | ### See also | | | | --- | --- | | [bidirectional\_iterator](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") (C++20) | specifies that a [`forward_iterator`](../iterator/forward_iterator "cpp/iterator/forward iterator") is a bidirectional iterator, supporting movement backwards (concept) | | [**Iterator library**](../iterator "cpp/iterator") | provides definitions for iterators, iterator traits, adaptors, and utility functions | cpp C++ named requirements: NumericType C++ named requirements: NumericType =================================== Specifies that the type can be used as the template argument of `[std::valarray](../numeric/valarray "cpp/numeric/valarray")`. ### Requirements for a type `T` to be a NumericType, it must be a cv-unqualified object type that: * meets the [DefaultConstructible](defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](copyassignable "cpp/named req/CopyAssignable") and [Destructible](destructible "cpp/named req/Destructible") requirements. * No operation on `T` may throw exceptions cpp C++ named requirements: TrivialType C++ named requirements: TrivialType =================================== Specifies that a type is a trivial type. Note: the standard doesn't define a named requirement with this name. This is a type category defined by the core language. It is included here as a named requirement only for consistency. ### Requirements The following types are collectively called *trivial types*: * [scalar types](scalartype "cpp/named req/ScalarType") * [trivial class types](../language/classes#Trivial_class "cpp/language/classes") * arrays of such types * cv-qualified versions of these types ### See also | | | | --- | --- | | [is\_trivial](../types/is_trivial "cpp/types/is trivial") (C++11) | checks if a type is trivial (class template) | cpp C++ named requirements: FunctionObject C++ named requirements: FunctionObject ====================================== A **FunctionObject** type is the type of an object that can be used on the left of the function call operator. ### Requirements The type `T` satisfies FunctionObject if. * The type `T` satisfies `[std::is\_object](../types/is_object "cpp/types/is object")`, and Given. * `f`, a value of type `T` or `const T` * `args`, suitable argument list, which may be empty The following expressions must be valid: | Expression | Requirements | | --- | --- | | `f(args)` | performs a function call | ### Notes Functions and references to functions are not function object types, but can be used where function object types are expected due to function-to-pointer [implicit conversion](../language/implicit_cast "cpp/language/implicit cast"). ### Standard library * All [pointers to functions](../language/pointer#Pointers_to_functions "cpp/language/pointer") satisfy this requirement. * All function objects defined in [`<functional>`](../header/functional "cpp/header/functional") * Some return types of functions of [`<functional>`](../header/functional "cpp/header/functional") ### Example demonstrates different types of function objects. ``` #include <iostream> void foo(int x) { std::cout << "foo(" << x << ")\n"; } int main() { void(*fp)(int) = foo; fp(1); // calls foo using the pointer to function struct S { void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; } } s; s(2); // calls s.operator() s.operator()(3); // the same auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; }; lam(4); // calls the lambda lam.operator()(5); // the same } ``` Output: ``` foo(1) S::operator(2) S::operator(3) lambda(4) lambda(5) ``` ### See also | | | | --- | --- | | [Callable](callable "cpp/named req/Callable") | a type for which the invoke operation is defined (named requirement) | cpp C++ named requirements: Clock C++ named requirements: Clock ============================= The **Clock** requirements describe a bundle consisting of a `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")`, a `[std::chrono::time\_point](../chrono/time_point "cpp/chrono/time point")`, and a function `now()` to get the current `time_point`. The origin of the clock's `time_point` is referred to as the clock's epoch. ### Requirements `C1` and `C2` denote clock types. `t1` and `t2` are values returned by `C1::now()` where the call returning `t1` happens before the call returning `t2` and both of these calls occur before `C1::time_point::max()`. | Expression | Return type | Operational semantics | | --- | --- | --- | | `C1::rep` | An arithmetic type or a class emulating an arithmetic type | The representation type of `C1::duration`. | | `C1::period` | A specialization of `[std::ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio")` | The tick period of the clock in seconds. | | `C1::duration` | `[std::chrono::duration](http://en.cppreference.com/w/cpp/chrono/duration)<C1::rep, C1::period>` | The duration type of the clock. | | `C1::time_point` | `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<C1>` or `[std::chrono::time\_point](http://en.cppreference.com/w/cpp/chrono/time_point)<C2, C1::duration>` | The `[std::chrono::time\_point](../chrono/time_point "cpp/chrono/time point")` type of the clock. C1 and C2 shall refer to the same epoch. | | `C1::is_steady` | `const bool` | `true` if `t1 <= t2` is always `true` and the clock advances at a steady rate relative to real time (so the difference between two distinct reported times is approximately the elapsed real time between the clock updates), otherwise `false` | | `C1::now()` | `C1::time_point` | Returns a `time_point` object representing the current point in time. | ### See also | | | | --- | --- | | [is\_clockis\_clock\_v](../chrono/is_clock "cpp/chrono/is clock") (C++20) | determines if a type is a **Clock** (class template) (variable template) | cpp C++ named requirements: UnformattedOutputFunction C++ named requirements: UnformattedOutputFunction ================================================= ### Requirements A UnformattedOutputFunction is a stream output function that performs the following: 1) Constructs an object of type [`basic_ostream::sentry`](../io/basic_ostream/sentry "cpp/io/basic ostream/sentry") with automatic storage duration, which performs the following: * If [`eofbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") or [`badbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") are set on the output stream, sets the [`failbit`](../io/ios_base/iostate "cpp/io/ios base/iostate") as well, and if exceptions on `failbit` are enabled in this output stream's exception mask, throws [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure"). * Flushes the tie()'d output stream, if applicable. 2) Checks the status of the sentry by calling `sentry::operator bool()`, which is equivalent to [`basic_ios::good`](../io/basic_ios/good "cpp/io/basic ios/good"). * If the operator returns `false` or sentry's constructor throws an exception, no output takes place. * If the operator returns `true`, attempts to perform the desired output by inserting the characters into the output stream as if by calling `rdbuf()->sputc()` or `rdbuf()->xsputn()`. Additionally, `rdbuf()->overflow()` and `rdbuf()->sync()` may be called, but no other virtual member function of `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`. + If an exception is thrown during output, sets `badbit` in the output stream. If exceptions on `badbit` are enabled in this stream's exception mask, the exception is also rethrown. + If no exception was thrown, returns the value specified by the function. 3) In any event, whether terminating by exception or returning, the sentry's destructor is called before leaving this function. ### Standard library The following standard library functions are **UnformattedOutputFunctions**. * [`basic_ostream::operator<<(basic_streambuf*)`](../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") * [`basic_ostream::put`](../io/basic_ostream/put "cpp/io/basic ostream/put") * [`basic_ostream::write`](../io/basic_ostream/write "cpp/io/basic ostream/write") * [`basic_ostream::flush`](../io/basic_ostream/flush "cpp/io/basic ostream/flush") | | | | --- | --- | | * [`basic_ostream::tellp`](../io/basic_ostream/tellp "cpp/io/basic ostream/tellp") (except calls pubseekoff instead of output) * [`basic_ostream::seekp`](../io/basic_ostream/seekp "cpp/io/basic ostream/seekp") (except calls pubseekoff or pubseekpos instead of output) | (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 | | --- | --- | --- | --- | | [LWG 63](https://cplusplus.github.io/LWG/issue63) | C++98 | the exception-handling policy was missing | added |
programming_docs
cpp C++ named requirements: ReversibleContainer C++ named requirements: ReversibleContainer =========================================== A **ReversibleContainer** is a [Container](container "cpp/named req/Container") that has iterators that meet the requirements of either [LegacyBidirectionalIterator](bidirectionaliterator "cpp/named req/BidirectionalIterator") or [LegacyRandomAccessIterator](randomaccessiterator "cpp/named req/RandomAccessIterator"). Such iterators allow a ReversibleContainer to be iterated over in reverse. ### Requirements | | | | --- | --- | | `X` | Container type | | `T` | Element type | | `a` | Objects of type `X` | #### Types | expression | return type | conditions | complexity | | --- | --- | --- | --- | | `X::reverse_iterator` | iterator type whose value type is `T` | `reverse_iterator<iterator>` | compile time | | `X::const_reverse_iterator` | constant iterator type whose value type is `T` | `reverse_iterator<const_iterator>` | compile time | #### Methods | expression | return type | conditions | complexity | | --- | --- | --- | --- | | `a.rbegin()` | `reverse_iterator`; `const_reverse_iterator` for constant `a` | `reverse_iterator(end())` | constant | | `a.rend()` | `reverse_iterator`; `const_reverse_iterator` for constant `a` | `reverse_iterator(begin())` | constant | | `a.crbegin()` | `const_reverse_iterator` | `const_cast<X const&>(a).rbegin()` | constant | | `a.crend()` | `const_reverse_iterator` | `const_cast<X const&>(a).rend()` | constant | ### Standard library * `[std::array](../container/array "cpp/container/array")` * `[std::deque](../container/deque "cpp/container/deque")` * `[std::list](../container/list "cpp/container/list")` * `[std::vector](../container/vector "cpp/container/vector")` * `[std::map](../container/map "cpp/container/map")` * `[std::multimap](../container/multimap "cpp/container/multimap")` * `[std::set](../container/set "cpp/container/set")` * `[std::multiset](../container/multiset "cpp/container/multiset")` ### Example The following example iterates over a `[vector](../container/vector "cpp/container/vector")` (which has [random-access iterators](../container/vector#Member_types "cpp/container/vector")) in reverse. ``` #include <vector> #include <iostream> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9}; for(std::vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i) { std::cout << *i << ' '; } } ``` Output: ``` 9 5 1 4 1 3 ``` cpp C++ named requirements: SharedMutex C++ named requirements: SharedMutex =================================== The **SharedMutex** requirements extend the [Mutex](mutex "cpp/named req/Mutex") requirements to include shared lock ownership mode. ### Requirements * [Mutex](mutex "cpp/named req/Mutex") Additionally, an object `m` of SharedMutex type supports another mode of ownership: shared. Multiple threads (or, more generally, execution agents) can simultaneously own this mutex in shared mode, but no thread may obtain shared ownership if there is a thread that owns it in exclusive mode and no thread may obtain exclusive ownership if there is a thread that owns it in shared mode. If more than implementation-defined number of threads (no less than 10000) hold a shared lock, another attempt to acquire the mutex in shared mode blocks until the number of shared owners drops down below that threshold. * The expression `m.lock_shared()` has the following properties + Behaves as an atomic operation. + Blocks the calling thread until shared ownership of the mutex can be obtained. + Prior `m.unlock()` operations on the same mutex *synchronize-with* this lock operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) + The behavior is undefined if the calling thread already owns the mutex in any mode. + If an exception is thrown, the shared lock is not acquired. * The expression `m.try_lock_shared()` has the following properties + Behaves as an atomic operation. + Attempts to obtain shared ownership of the mutex for the calling thread without blocking. If ownership is not obtained, returns immediately. The function is allowed to spuriously fail and return even if the mutex is not currently owned by any threads in any mode. + If `try_lock_shared()` succeeds, prior `unlock()` operations on the same object *synchronize-with* this operation (equivalent to release-acquire `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). + The behavior is undefined if the calling thread already owns the mutex in any mode * The expression `m.unlock_shared()` has the following properties + Behaves as an atomic operation. + Releases the calling thread's ownership of the mutex and *synchronizes-with* the subsequent successful lock operations on the same object. + The behavior is undefined if the calling thread does not own the mutex. * All lock and unlock operations on a single mutex occur in a single total order ### Library types The following standard library types satisfy **SharedMutex**: * `[std::shared\_mutex](../thread/shared_mutex "cpp/thread/shared mutex")`(since C++17) * `[std::shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex")`(since C++14) ### See also * [Thread support library](../thread "cpp/thread") * [Mutex](mutex "cpp/named req/Mutex") * [TimedMutex](timedmutex "cpp/named req/TimedMutex") * [SharedTimedMutex](sharedtimedmutex "cpp/named req/SharedTimedMutex") cpp Parameter pack(since C++11) Parameter pack(since C++11) =========================== A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A function parameter pack is a function parameter that accepts zero or more function arguments. A template with at least one parameter pack is called a *variadic template*. ### Syntax Template parameter pack (appears in [alias template](type_alias "cpp/language/type alias"), [class template](class_template "cpp/language/class template"), [variable template](variable_template "cpp/language/variable template") (since C++14) and [function template](function_template "cpp/language/function template") parameter lists). | | | | | --- | --- | --- | | type `...` pack-name(optional) | (1) | | | `typename``|``class` `...` pack-name(optional) | (2) | | | type-constraint `...` pack-name(optional) | (3) | (since C++20) | | `template` `<` parameter-list `>` `class` `...` pack-name(optional) | (4) | (until C++17) | | `template` `<` parameter-list `>` `typename``|``class` `...` pack-name(optional) | (4) | (since C++17) | Function parameter pack (a form of [declarator](declarations "cpp/language/declarations"), appears in a function parameter list of a variadic function template). | | | | | --- | --- | --- | | pack-name `...` pack-param-name(optional) | (5) | | Parameter pack expansion (appears in a body of a variadic template). | | | | | --- | --- | --- | | pattern `...` | (6) | | 1) A non-type template parameter pack with an optional name 2) A type template parameter pack with an optional name | | | | --- | --- | | 3) A [constrained](constraints "cpp/language/constraints") type template parameter pack with an optional name | (since C++20) | 4) A template template parameter pack with an optional name 5) A function parameter pack with an optional name 6) Parameter pack expansion: expands to comma-separated list of zero or more `pattern`s. Pattern must include at least one parameter pack. ### Explanation A variadic class template can be instantiated with any number of template arguments: ``` template<class... Types> struct Tuple {}; Tuple<> t0; // Types contains no arguments Tuple<int> t1; // Types contains one argument: int Tuple<int, float> t2; // Types contains two arguments: int and float Tuple<0> t3; // error: 0 is not a type ``` A variadic function template can be called with any number of function arguments (the template arguments are deduced through [template argument deduction](template_argument_deduction "cpp/language/template argument deduction")): ``` template<class... Types> void f(Types... args); f(); // OK: args contains no arguments f(1); // OK: args contains one argument: int f(2, 1.0); // OK: args contains two arguments: int and double ``` In a primary class template, the template parameter pack must be the final parameter in the template parameter list. In a function template, the template parameter pack may appear earlier in the list provided that all following parameters can be deduced from the function arguments, or have default arguments: ``` template<typename U, typename... Ts> // OK: can deduce U struct valid; // template<typename... Ts, typename U> // Error: Ts... not at the end // struct Invalid; template<typename... Ts, typename U, typename=void> void valid(U, Ts...); // OK: can deduce U // void valid(Ts..., U); // Can't be used: Ts... is a non-deduced context in this position valid(1.0, 1, 2, 3); // OK: deduces U as double, Ts as {int, int, int} ``` If every valid specialization of a variadic template requires an empty template parameter pack, the program is ill-formed, no diagnostic required. ### Pack expansion A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is *expanded* into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order. ``` template<class... Us> void f(Us... pargs) {} template<class... Ts> void g(Ts... args) { f(&args...); // “&args...” is a pack expansion // “&args” is its pattern } g(1, 0.2, "a"); // Ts... args expand to int E1, double E2, const char* E3 // &args... expands to &E1, &E2, &E3 // Us... pargs expand to int* E1, double* E2, const char** E3 ``` If the names of two parameter packs appear in the same pattern, they are expanded simultaneously, and they must have the same length: ``` template<typename...> struct Tuple {}; template<typename T1, typename T2> struct Pair {}; template<class... Args1> struct zip { template<class... Args2> struct with { typedef Tuple<Pair<Args1, Args2>...> type; // Pair<Args1, Args2>... is the pack expansion // Pair<Args1, Args2> is the pattern }; }; typedef zip<short, int>::with<unsigned short, unsigned>::type T1; // Pair<Args1, Args2>... expands to // Pair<short, unsigned short>, Pair<int, unsigned int> // T1 is Tuple<Pair<short, unsigned short>, Pair<int, unsigned>> // typedef zip<short>::with<unsigned short, unsigned>::type T2; // error: pack expansion contains parameter packs of different lengths ``` If a pack expansion is nested within another pack expansion, the parameter packs that appear inside the innermost pack expansion are expanded by it, and there must be another pack mentioned in the enclosing pack expansion, but not in the innermost one: ``` template<class... Args> void g(Args... args) { f(const_cast<const Args*>(&args)...); // const_cast<const Args*>(&args) is the pattern, it expands two packs // (Args and args) simultaneously f(h(args...) + args...); // Nested pack expansion: // inner pack expansion is "args...", it is expanded first // outer pack expansion is h(E1, E2, E3) + args..., it is expanded // second (as h(E1, E2, E3) + E1, h(E1, E2, E3) + E2, h(E1, E2, E3) + E3) } ``` ### Expansion loci Depending on where the expansion takes place, the resulting comma-separated list is a different kind of list: function parameter list, member initializer list, attribute list, etc. The following is the list of all allowed contexts: #### Function argument lists A pack expansion may appear inside the parentheses of a function call operator, in which case the largest expression or braced-init-list to the left of the ellipsis is the pattern that is expanded: ``` f(&args...); // expands to f(&E1, &E2, &E3) f(n, ++args...); // expands to f(n, ++E1, ++E2, ++E3); f(++args..., n); // expands to f(++E1, ++E2, ++E3, n); f(const_cast<const Args*>(&args)...); // f(const_cast<const E1*>(&X1), const_cast<const E2*>(&X2), const_cast<const E3*>(&X3)) f(h(args...) + args...); // expands to // f(h(E1, E2, E3) + E1, h(E1, E2, E3) + E2, h(E1, E2, E3) + E3) ``` Formally, the *expression-list* in a function call expression is classified as *initializer-list*, and the pattern is the *initializer-clause*, which is either an *assignment-expression* or a *braced-init-list*. #### Parenthesized initializers A pack expansion may appear inside the parentheses of a [direct initializer](direct_initialization "cpp/language/direct initialization"), a [function-style cast](explicit_cast "cpp/language/explicit cast"), and other contexts ([member initializer](initializer_list "cpp/language/initializer list"), [new-expression](new "cpp/language/new"), etc.) in which case the rules are identical to the rules for a function call expression above: ``` Class c1(&args...); // calls Class::Class(&E1, &E2, &E3) Class c2 = Class(n, ++args...); // calls Class::Class(n, ++E1, ++E2, ++E3); ::new((void *)p) U(std::forward<Args>(args)...) // std::allocator::allocate ``` #### Brace-enclosed initializers In a *braced-init-list* (brace-enclosed list of initializers and other *braced-init-list*s, used in [list-initialization](list_initialization "cpp/language/list initialization") and some other contexts), a pack expansion may appear as well: ``` template<typename... Ts> void func(Ts... args) { const int size = sizeof...(args) + 2; int res[size] = {1, args..., 2}; // since initializer lists guarantee sequencing, this can be used to // call a function on each element of a pack, in order: int dummy[sizeof...(Ts)] = {(std::cout << args, 0)...}; } ``` #### Template argument lists Pack expansions can be used anywhere in a template argument list, provided the template has the parameters to match the expansion: ``` template<class A, class B, class... C> void func(A arg1, B arg2, C... arg3) { container<A, B, C...> t1; // expands to container<A, B, E1, E2, E3> container<C..., A, B> t2; // expands to container<E1, E2, E3, A, B> container<A, C..., B> t3; // expands to container<A, E1, E2, E3, B> } ``` #### Function parameter list In a function parameter list, if an ellipsis appears in a parameter declaration (whether it names a function parameter pack (as in, Args`...` args) or not) the parameter declaration is the pattern: ``` template<typename... Ts> void f(Ts...) {} f('a', 1); // Ts... expands to void f(char, int) f(0.1); // Ts... expands to void f(double) template<typename... Ts, int... N> void g(Ts (&...arr)[N]) {} int n[1]; g<const char, int>("a", n); // Ts (&...arr)[N] expands to // const char (&)[2], int(&)[1] ``` Note: In the pattern `Ts (&...arr)[N]`, the ellipsis is the innermost element, not the last element as in all other pack expansions. Note: `Ts (&...)[N]` is not allowed because the C++11 grammar requires the parenthesized ellipsis to have a name: [CWG issue 1488](https://cplusplus.github.io/CWG/issues/1488.html). #### Template parameter list Pack expansion may appear in a template parameter list: ``` template<typename... T> struct value_holder { template<T... Values> // expands to a non-type template parameter struct apply {}; // list, such as <int, char, int(&)[5]> }; ``` #### Base specifiers and member initializer lists A pack expansion may designate the list of base classes in a [class declaration](class "cpp/language/class"). Typically, this also means that the constructor needs to use a pack expansion in the [member initializer list](initializer_list "cpp/language/initializer list") to call the constructors of these bases: ``` template<class... Mixins> class X : public Mixins... { public: X(const Mixins&... mixins) : Mixins(mixins)... {} }; ``` #### Lambda captures Pack expansion may appear in the capture clause of a [lambda](lambda "cpp/language/lambda") expression: ``` template<class... Args> void f(Args... args) { auto lm = [&, args...] { return g(args...); }; lm(); } ``` #### The sizeof... operator The [`sizeof...`](sizeof... "cpp/language/sizeof...") operator is classified as a pack expansion as well: ``` template<class... Types> struct count { static const std::size_t value = sizeof...(Types); }; ``` | | | | --- | --- | | Dynamic exception specifications The list of exceptions in a [dynamic exception specification](except_spec "cpp/language/except spec") may also be a pack expansion: ``` template<class... X> void func(int arg) throw(X...) { // ... throw different Xs in different situations } ``` | (until C++17) | #### Alignment specifier Pack expansions are allowed in both the lists of types and the lists of expressions used by the keyword [`alignas`](alignas "cpp/language/alignas"). #### Attribute list Pack expansions are allowed in the lists of [attributes](attributes "cpp/language/attributes"), as in `[[attributes...]]`. For example: `void [[attributes...]] function()`. | | | | --- | --- | | Fold-expressions In [fold-expressions](fold "cpp/language/fold"), the pattern is the entire subexpression that does not contain an unexpanded parameter pack. Using-declarations In [using declaration](using_declaration "cpp/language/using declaration"), ellipsis may appear in the list of declarators, this is useful when deriving from a parameter pack: ``` template<typename... bases> struct X : bases... { using bases::g...; }; X<B, D> x; // OK: B::g and D::g introduced ``` | (since C++17) | ### Notes ### Example The below example defines a function similar to `[std::printf](../io/c/fprintf "cpp/io/c/fprintf")`, that replace each occurrence of the character `%` in the format string with a value. The first overload is called when only the format string is passed and there is no parameter expansion. The second overload contains a separate template parameter for the head of the arguments and a parameter pack, this allows the recursive call to pass only the tail of the parameters until it becomes empty. `Targs` is the template parameter pack and `Fargs` is the function parameter pack. ``` #include <iostream> void tprintf(const char* format) // base function { std::cout << format; } template<typename T, typename... Targs> void tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function { for (; *format != '\0'; format++) { if (*format == '%') { std::cout << value; tprintf(format + 1, Fargs...); // recursive call return; } std::cout << *format; } } int main() { tprintf("% world% %\n", "Hello", '!', 123); } ``` Output: ``` Hello world! 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 | | --- | --- | --- | --- | | [CWG 1533](https://cplusplus.github.io/CWG/issues/1533.html) | C++11 | a pack expansion could occur in a member initializer for a member | not allowed | ### See also | | | --- | | [function template](function_template "cpp/language/function template") | | [class template](class_template "cpp/language/class template") | | [`sizeof...`](sizeof... "cpp/language/sizeof...") | Queries the number of elements in a parameter pack. | | [C-style variadic functions](../utility/variadic "cpp/utility/variadic") | | [Preprocessor macros](../preprocessor/replace "cpp/preprocessor/replace") | Can be variadic as well | | [Fold expressions](fold "cpp/language/fold") |
programming_docs
cpp Template argument deduction Template argument deduction =========================== In order to instantiate a [function template](function_template "cpp/language/function template"), every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted, when an address of a function template is taken, and in some [other contexts](#Other_contexts): ``` template<typename To, typename From> To convert(From f); void g(double d) { int i = convert<int>(d); // calls convert<int, double>(double) char c = convert<char>(d); // calls convert<char, double>(double) int(*ptr)(float) = convert; // instantiates convert<int, float>(float) // and stores its address in ptr } ``` This mechanism makes it possible to use template operators, since there is no syntax to specify template arguments for an operator other than by re-writing it as a function call expression: ``` #include <iostream> int main() { std::cout << "Hello, world" << std::endl; // operator<< is looked up via ADL as std::operator<<, // then deduced to operator<<<char, std::char_traits<char>> both times // std::endl is deduced to &std::endl<char, std::char_traits<char>> } ``` Template argument deduction takes place after the function template [name lookup](lookup "cpp/language/lookup") (which may involve [argument-dependent lookup](adl "cpp/language/adl")) and before [template argument substitution](function_template#Template_argument_substitution "cpp/language/function template") (which may involve [SFINAE](sfinae "cpp/language/sfinae")) and [overload resolution](overload_resolution "cpp/language/overload resolution"). | | | | --- | --- | | Template argument deduction is also performed when the name of a class template is used as the type of an object being constructed: ``` std::pair p(2, 4.5); std::tuple t(4, 3, 2.5); std::copy_n(vi1, 3, std::back_insert_iterator(vi2)); std::for_each(vi.begin(), vi.end(), Foo([&](int i) {...})); auto lck = std::lock_guard(foo.mtx); std::lock_guard lck2(foo.mtx, ul); ``` Template argument deduction for class templates takes place in declarations and in explicit cast expressions; see [class template argument deduction](class_template_argument_deduction "cpp/language/class template argument deduction") for details. | (since C++17) | ### Deduction from a function call Template argument deduction attempts to determine template arguments (types for type template parameters `T`i, templates for template template parameters `TT`i, and values for non-type template parameters `I`i), which can be substituted into each parameter `P` to produce the type *deduced* `A`, which is the same as the type of the argument `A`, after adjustments listed below. If there are multiple parameters, each `P`/`A` pair is deduced separately and the deduced template arguments are then combined. If deduction fails or is ambiguous for any `P`/`A` pair or if different pairs yield different deduced template arguments, or if any template argument remains neither deduced nor explicitly specified, compilation fails. | | | | --- | --- | | If removing references and cv-qualifiers from `P` gives `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<P'>` and `A` is a [braced-init-list](list_initialization "cpp/language/list initialization"), then deduction is performed for every element of the initializer list, taking `P'` as the parameter and the list element `A'` as the argument: ``` template<class T> void f(std::initializer_list<T>); f({1, 2, 3}); // P = std::initializer_list<T>, A = {1, 2, 3} // P'1 = T, A'1 = 1: deduced T = int // P'2 = T, A'2 = 2: deduced T = int // P'3 = T, A'3 = 3: deduced T = int // OK: deduced T = int f({1, "abc"}); // P = std::initializer_list<T>, A = {1, "abc"} // P'1 = T, A'1 = 1: deduced T = int // P'2 = T, A'2 = "abc": deduced T = const char* // error: deduction fails, T is ambiguous ``` If removing references and cv-qualifiers from `P` gives `P'`[`N`], and `A` is a non-empty braced-init-list, then deduction is performed as above, except if `N` is a non-type template parameter, it is deduced from the length of the initializer list: ``` template<class T, int N> void h(T const(&)[N]); h({1, 2, 3}); // deduced T = int, deduced N = 3 template<class T> void j(T const(&)[3]); j({42}); // deduced T = int, array bound is not a parameter, not considered struct Aggr { int i; int j; }; template<int N> void k(Aggr const(&)[N]); k({1, 2, 3}); // error: deduction fails, no conversion from int to Aggr k({{1}, {2}, {3}}); // OK: deduced N = 3 template<int M, int N> void m(int const(&)[M][N]); m({{1, 2}, {3, 4}}); // deduced M = 2, deduced N = 2 template<class T, int N> void n(T const(&)[N], T); n({{1}, {2}, {3}}, Aggr()); // deduced T = Aggr, deduced N = 3 ``` If a [parameter pack](parameter_pack "cpp/language/parameter pack") appears as the last `P`, then the type `P` is matched against the type `A` of each remaining argument of the call. Each match deduces the template arguments for the next position in the pack expansion: ``` template<class... Types> void f(Types&...); void h(int x, float& y) { const int z = x; f(x, y, z); // P = Types&..., A1 = x: deduced first member of Types... = int // P = Types&..., A2 = y: deduced second member of Types... = float // P = Types&..., A3 = z: deduced third member of Types... = const int // calls f<int, float, const int> } ``` | (since C++11) | If `P` is a function type, pointer to function type, or pointer to member function type and if `A` is a [set of overloaded functions](overloaded_address "cpp/language/overloaded address") not containing function templates, template argument deduction is attempted with each overload. If only one succeeds, that successful deduction is used. If none or more than one succeeds, the template parameter is non-deduced context (see below): ``` template<class T> int f(T(*p)(T)); int g(int); int g(char); f(g); // P = T(*)(T), A = overload set // P = T(*)(T), A1 = int(int): deduced T = int // P = T(*)(T), A2 = int(char): fails to deduce T // only one overload works, deduction succeeds ``` Before deduction begins, the following adjustments to `P` and `A` are made: 1) If `P` is not a reference type, a) if `A` is an array type, `A` is replaced by the pointer type obtained from array-to-pointer conversion; b) otherwise, if `A` is a function type, `A` is replaced by the pointer type obtained from function-to-pointer conversion; c) otherwise, if `A` is a cv-qualified type, the top-level cv-qualifiers are ignored for deduction: ``` template<class T> void f(T); int a[3]; f(a); // P = T, A = int[3], adjusted to int*: deduced T = int* void b(int); f(b); // P = T, A = void(int), adjusted to void(*)(int): deduced T = void(*)(int) const int c = 13; f(c); // P = T, A = const int, adjusted to int: deduced T = int ``` 2) If `P` is a cv-qualified type, the top-level cv-qualifiers are ignored for deduction. 3) If `P` is a reference type, the referenced type is used for deduction. 4) If `P` is an rvalue reference to a cv-unqualified template parameter (so-called [forwarding reference](reference#Forwarding_references "cpp/language/reference")), and the corresponding function call argument is an lvalue, the type lvalue reference to `A` is used in place of `A` for deduction (Note: this is the basis for the action of `[std::forward](../utility/forward "cpp/utility/forward")` Note: in [class template argument deduction](class_template_argument_deduction "cpp/language/class template argument deduction"), template parameter of a class template is never a forwarding reference (since C++17)): ``` template<class T> int f(T&&); // P is an rvalue reference to cv-unqualified T (forwarding reference) template<class T> int g(const T&&); // P is an rvalue reference to cv-qualified T (not special) int main() { int i; int n1 = f(i); // argument is lvalue: calls f<int&>(int&) (special case) int n2 = f(0); // argument is not lvalue: calls f<int>(int&&) // int n3 = g(i); // error: deduces to g<int>(const int&&), which // cannot bind an rvalue reference to an lvalue } ``` After these transformations, the deduction processes as described below (cf. section [Deduction from a type](#Deduction_from_a_type)) and attempts to find such template arguments that would make the deduced `A` (that is, `P` after adjustments listed above and the substitution of the deduced template parameters) identical to the *transformed* `A`, that is `A` after the adjustments listed above. If the usual deduction from `P` and `A` fails, the following alternatives are additionally considered: 1) If `P` is a reference type, the deduced `A` (i.e., the type referred to by the reference) can be more cv-qualified than the transformed `A`: ``` template<typename T> void f(const T& t); bool a = false; f(a); // P = const T&, adjusted to const T, A = bool: // deduced T = bool, deduced A = const bool // deduced A is more cv-qualified than A ``` 2) The transformed `A` can be another pointer or pointer to member type that can be converted to the deduced `A` via a [qualification conversions](implicit_cast#Qualification_conversions "cpp/language/implicit cast") or a function pointer conversion (since C++17): ``` template<typename T> void f(const T*); int* p; f(p); // P = const T*, A = int*: // deduced T = int, deduced A = const int* // qualification conversion applies (from int* to const int*) ``` 3) If `P` is a class and `P` has the form [simple-template-id](templates#template-id "cpp/language/templates"), then the transformed `A` can be a derived class of the deduced `A`. Likewise, if `P` is a pointer to a class of the form *simple-template-id*, the transformed `A` can be a pointer to a derived class pointed to by the deduced `A`: ``` template<class T> struct B {}; template<class T> struct D : public B<T> {}; template<class T> void f(B<T>&) {} void f() { D<int> d; f(d); // P = B<T>&, adjusted to P = B<T> (a simple-template-id), A = D<int>: // deduced T = int, deduced A = B<int> // A is derived from deduced A } ``` #### Non-deduced contexts In the following cases, the types, templates, and non-type values that are used to compose `P` do not participate in template argument deduction, but instead *use* the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails. 1) The nested-name-specifier (everything to the left of the scope resolution operator `::`) of a type that was specified using a [qualified-id](identifiers#Qualified_identifiers "cpp/language/identifiers"): ``` // the identity template, often used to exclude specific arguments from deduction // (available as std::type_identity as of C++20) template<typename T> struct identity { typedef T type; }; template<typename T> void bad(std::vector<T> x, T value = 1); template<typename T> void good(std::vector<T> x, typename identity<T>::type value = 1); std::vector<std::complex<double>> x; bad(x, 1.2); // P1 = std::vector<T>, A1 = std::vector<std::complex<double>> // P1/A1: deduced T = std::complex<double> // P2 = T, A2 = double // P2/A2: deduced T = double // error: deduction fails, T is ambiguous good(x, 1.2); // P1 = std::vector<T>, A1 = std::vector<std::complex<double>> // P1/A1: deduced T = std::complex<double> // P2 = identity<T>::type, A2 = double // P2/A2: uses T deduced by P1/A1 because T is to the left of :: in P2 // OK: T = std::complex<double> ``` | | | | --- | --- | | 2) The expression of a [decltype](decltype "cpp/language/decltype")-specifier: ``` template<typename T> void f(decltype(*std::declval<T>()) arg); int n; f<int*>(n); // P = decltype(*declval<T>()), A = int: T is in non-deduced context ``` | (since C++11) | 3) A non-type template argument or an array bound in which a subexpression references a template parameter: ``` template<std::size_t N> void f(std::array<int, 2 * N> a); std::array<int, 10> a; f(a); // P = std::array<int, 2 * N>, A = std::array<int, 10>: // 2 * N is non-deduced context, N cannot be deduced // note: f(std::array<int, N> a) would be able to deduce N ``` 4) A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done: ``` template<typename T, typename F> void f(const std::vector<T>& v, const F& comp = std::less<T>()); std::vector<std::string> v(3); f(v); // P1 = const std::vector<T>&, A1 = std::vector<std::string> lvalue // P1/A1 deduced T = std::string // P2 = const F&, A2 = std::less<std::string> rvalue // P2 is non-deduced context for F (template parameter) used in the // parameter type (const F&) of the function parameter comp, // that has a default argument that is being used in the call f(v) ``` 5) The parameter `P`, whose `A` is a function or a set of overloads such that more than one function matches `P` or no function matches `P` or the set of overloads includes one or more function templates: ``` template<typename T> void out(const T& value) { std::cout << value; } out("123"); // P = const T&, A = const char[4] lvalue: deduced T = char[4] out(std::endl); // P = const T&, A = function template: T is in non-deduced context ``` 6) The parameter `P`, whose `A` is a braced-init-list, but `P` is not `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")`, a reference to one (possibly cv-qualified), or (since C++17) a reference to an array: ``` template<class T> void g1(std::vector<T>); template<class T> void g2(std::vector<T>, T x); g1({1, 2, 3}); // P = std::vector<T>, A = {1, 2, 3}: T is in non-deduced context // error: T is not explicitly specified or deduced from another P/A g2({1, 2, 3}, 10); // P1 = std::vector<T>, A1 = {1, 2, 3}: T is in non-deduced context // P2 = T, A2 = int: deduced T = int ``` | | | | --- | --- | | 7) The parameter `P` which is a parameter pack and does not occur at the end of the parameter list: ``` template<class... Ts, class T> void f1(T n, Ts... args); template<class... Ts, class T> void f2(Ts... args, T n); f1(1, 2, 3, 4); // P1 = T, A1 = 1: deduced T = int // P2 = Ts..., A2 = 2, A3 = 3, A4 = 4: deduced Ts = [int, int, int] f2(1, 2, 3, 4); // P1 = Ts...: Ts is non-deduced context ``` 8) The template parameter list that appears within the parameter `P`, and which includes a pack expansion that is not at the very end of the template parameter list: ``` template<int...> struct T {}; template<int... Ts1, int N, int... Ts2> void good(const T<N, Ts1...>& arg1, const T<N, Ts2...>&); template<int... Ts1, int N, int... Ts2> void bad(const T<Ts1..., N>& arg1, const T<Ts2..., N>&); T<1, 2> t1; T<1, -1, 0> t2; good(t1, t2); // P1 = const T<N, Ts1...>&, A1 = T<1, 2>: // deduced N = 1, deduced Ts1 = [2] // P2 = const T<N, Ts2...>&, A2 = T<1, -1, 0>: // deduced N = 1, deduced Ts2 = [-1, 0] bad(t1, t2); // P1 = const T<Ts1..., N>&, A1 = T<1, 2>: // <Ts1..., N> is non-deduced context // P2 = const T<Ts2..., N>&, A2 = T<1, -1, 0>: // <Ts2..., N> is non-deduced context ``` | (since C++11) | 9) For `P` of array type (but not reference to array or pointer to array), the major array bound: ``` template<int i> void f1(int a[10][i]); template<int i> void f2(int a[i][20]); // P = int[i][20], array type template<int i> void f3(int (&a)[i][20]); // P = int(&)[i][20], reference to array void g() { int a[10][20]; f1(a); // OK: deduced i = 20 f1<20>(a); // OK f2(a); // error: i is non-deduced context f2<10>(a); // OK f3(a); // OK: deduced i = 10 f3<10>(a); // OK } ``` In any case, if any part of a type name is non-deduced, the entire type name is non-deduced context. However, compound types can include both deduced and non-deduced type names. For example, in `A<T>::B<T2>`, `T` is non-deduced because of rule #1 (nested name specifier), and `T2` is non-deduced because it is part of the same type name, but in `void(*f)(typename A<T>::B, A<T>)`, the `T` in `A<T>::B` is non-deduced (because of the same rule), while the `T` in `A<T>` is deduced. #### Deduction from a type Given a function parameter `P` that depends on one or more type template parameters `T`i, template template parameters `TT`i, or non-type template parameters `I`i, and the corresponding argument `A`, deduction takes place if `P` has one of the following forms: * `*cv*`(optional) `T`; * `T*`; * `T&`; | | | | --- | --- | | * `T&&`; | (since C++11) | * `T`(optional) `[``I`(optional)`]`; | | | | --- | --- | | * `T`(optional) `(``U`(optional)`)`; | (until C++17) | | * `T`(optional) `(``U`(optional)`)` `noexcept(``I`(optional)`)`; | (since C++17) | * `T`(optional) `U`(optional)`::*`; * `TT`(optional)`<T>`; * `TT`(optional)`<I>`; * `TT`(optional)`<TU>`; * `TT`(optional)`<>`. In the above forms, * `T`(optional) or `U`(optional) represents a type or parameter-type-list that either satisfies these rules recursively, is a non-deduced context in `P` or `A`, or is the same non-dependent type in `P` and `A`. * `TT`(optional) or `TU`(optional) represents either a class template or a template template parameter. * `I`(optional) represents an expression that either is an `I`, is value-dependent in `P` or `A`, or has the same constant value in `P` and `A`. | | | | --- | --- | | * `noexcept(``I`(optional)`)` represents an [exception specification](noexcept_spec "cpp/language/noexcept spec") in which the possibly-implicit `noexcept` specifier's operand satisfies the rules for an `I`(optional) above. | (since C++17) | If `P` has one of the forms that include a template parameter list `<T>` or `<I>`, then each element `P`i of that template argument list is matched against the corresponding template argument `A`i of its `A`. If the last `P`i is a pack expansion, then its pattern is compared against each remaining argument in the template argument list of `A`. A trailing parameter pack that is not otherwise deduced, is deduced to an empty parameter pack. If `P` has one of the forms that include a function parameter list `(T)`, then each parameter `P`i from that list is compared with the corresponding argument `A`i from `A`'s function parameter list. If the last `P`i is a pack expansion, then its declarator is compared with each remaining `A`i in the parameter type list of `A`. Forms can be nested and processed recursively: * `X<int>(*)(char[6])` is an example of `T*`, where `T` is `X<int>(char[6])`; | | | | --- | --- | | * `X<int>(char[6])` is an example of `T`(optional) `(``U`(optional)`)`, where `T` is `X<int>` and `U` is `char[6]`; | (until C++17) | | * `X<int>(char[6])` is an example of `T`(optional) `(``U`(optional)`)` `noexcept(``I`(optional)`)`, where `T` is `X<int>`, `U` is `char[6]`, and `I` in the implicit `noexcept` specifier is `false`; | (since C++17) | * `X<int>` is an example of `TT`(optional)`<T>`, where `TT` is `X` and `T` is `int`, and * `char[6]` is an example of `T`(optional) `[``I`(optional)`]`, where `T` is `char` and `I` is `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)(6)`. | | | | --- | --- | | Type template argument cannot be deduced from the type of a non-type template argument: ``` template<typename T, T i> void f(double a[10][i]); double v[10][20]; f(v); // P = double[10][i], A = double[10][20]: // i can be deduced to equal 20 // but T cannot be deduced from the type of i ``` | (until C++17) | | When the value of the argument corresponding to a non-type template parameter P that is declared with a dependent type is deduced from an expression, the template parameters in the type of P are deduced from the type of the value. ``` template<long n> struct A {}; template<class T> struct C; template<class T, T n> struct C<A<n>> { using Q = T; }; typedef long R; typedef C<A<2>>::Q R; // OK: T was deduced to long // from the template argument value in the type A<2> template<auto X> class bar{}; template<class T, T n> void f(bar<n> x); f(bar<3>{}); // OK: T was deduced to int (and n to 3) // from the template argument value in the type bar<3> ``` The type of `N` in the type `T[N]` is `[std::size\_t](../types/size_t "cpp/types/size t")`. ``` template<class T, T i> void f(int (&a)[i]); int v[10]; f(v); // OK: T is std::size_t ``` The type of `B` in `noexcept(B)` specifier of a function type is `bool`. ``` template<bool> struct A {}; template<auto> struct B; template<auto X, void (*F)() noexcept(X)> struct B<F> { A<X> ax; }; void f_nothrow() noexcept; B<f_nothrow> bn; // OK: X is deduced as true and the type of X is deduced as bool. ``` | (since C++17) | If a non-type template parameter of function template is used in the template parameter list of function parameter (which is also a template), and the corresponding template argument is deduced, the type of the deduced template argument ( as specified in its enclosing template parameter list, meaning references are preserved) must match the type of the non-type template parameter exactly, except that cv-qualifiers are dropped, and except where the template argument is deduced from an array bound—in that case any integral type is allowed, even `bool` though it would always become `true`: ``` template<int i> class A {}; template<short s> void f(A<s>); // the type of the non-type template param is short void k1() { A<1> a; // the type of the non-type template param of a is int f(a); // P = A<(short)s>, A = A<(int)1> // error: deduced non-type template argument does not have the same // type as its corresponding template argument f<1>(a); // OK: the template argument is not deduced, // this calls f<(short)1>(A<(short)1>) } template<int&> struct X; template<int& R> void k2(X<R>&); int n; void g(X<n> &x) { k2(x); // P = X<R>, A = X<n> // parameter type is int& // argument type is int& in struct X's template declaration // OK (with CWG 2091): deduces R to refer to n } ``` Type template parameter cannot be deduced from the type of a function default argument: ``` template<typename T> void f(T = 5, T = 7); void g() { f(1); // OK: calls f<int>(1, 7) f(); // error: cannot deduce T f<int>(); // OK: calls f<int>(5, 7) } ``` Deduction of template template parameter can use the type used in the template specialization used in the function call: ``` template<template<typename> class X> struct A {}; // A is a template with a TT param template<template<typename> class TT> void f(A<TT>) {} template<class T> struct B {}; A<B> ab; f(ab); // P = A<TT>, A = A<B>: deduced TT = B, calls f(A<B>) ``` ### Other contexts Besides function calls and operator expressions, template argument deduction is used in the following situations: | | | | --- | --- | | auto type deduction Template argument deduction is used in [declarations](declarations "cpp/language/declarations") of variables, when deducing the meaning of the **[auto specifier](auto "cpp/language/auto")** from the variable's initializer. The parameter `P` is obtained as follows: in `T`, the declared type of the variable that includes `auto`, every occurrence of `auto` is replaced with an imaginary type template parameter `U` or, if the initialization is copy-list-initialization, with `std::initializer_list<U>`. The argument `A` is the initializer expression. After deduction of `U` from `P` and `A` following the rules described above, the deduced `U` is substituted into `P` to get the actual variable type: ``` const auto& x = 1 + 2; // P = const U&, A = 1 + 2: // same rules as for calling f(1 + 2) where f is // template<class U> void f(const U& u) // deduced U = int, the type of x is const int& auto l = {13}; // P = std::initializer_list<U>, A = {13}: // deduced U = int, the type of l is std::initializer_list<int> ``` In direct-list-initialization (but not in copy-list-initalization), when deducing the meaning of the [auto](auto "cpp/language/auto") from a braced-init-list, the braced-init-list must contain only one element, and the type of auto will be the type of that element: ``` auto x1 = {3}; // x1 is std::initializer_list<int> auto x2{1, 2}; // error: not a single element auto x3{3}; // x3 is int // (before N3922 x2 and x3 were both std::initializer_list<int>) ``` | (since C++11) | | | | | --- | --- | | auto-returning functions Template argument deduction is used in declarations of [functions](functions "cpp/language/functions"), when deducing the meaning of the [auto](auto "cpp/language/auto") specifier in the function's return type, from the return statement. For auto-returning functions, the parameter `P` is obtained as follows: in `T`, the declared return type of the function that includes `auto`, every occurrence of `auto` is replaced with an imaginary type template parameter `U`. The argument `A` is the expression of the [return](return "cpp/language/return") statement, and if the return statement has no operand, `A` is `void()`. After deduction of `U` from `P` and `A` following the rules described above, the deduced `U` is substituted into `T` to get the actual return type: ``` auto f() { return 42; } // P = auto, A = 42: // deduced U = int, the return type of f is int ``` If such function has multiple return statements, the deduction is performed for each return statement. All the resulting types must be the same and become the actual return type. If such function has no return statement, `A` is `void()` when deducing. Note: the meaning of `decltype(auto)` placeholder in variable and function declarations does not use template argument deduction. | (since C++14) | #### Overload resolution Template argument deduction is used during [overload resolution](overload_resolution "cpp/language/overload resolution"), when generating specializations from a candidate template function. `P` and `A` are the same as in a regular function call: ``` std::string s; std::getline(std::cin, s); // "std::getline" names 4 function templates, // 2 of which are candidate functions (correct number of parameters) // 1st candidate template: // P1 = std::basic_istream<CharT, Traits>&, A1 = std::cin // P2 = std::basic_string<CharT, Traits, Allocator>&, A2 = s // deduction determines the type template parameters CharT, Traits, and Allocator // specialization std::getline<char, std::char_traits<char>, std::allocator<char>> // 2nd candidate template: // P1 = std::basic_istream<CharT, Traits>&&, A1 = std::cin // P2 = std::basic_string<CharT, Traits, Allocator>&, A2 = s // deduction determines the type template parameters CharT, Traits, and Allocator // specialization std::getline<char, std::char_traits<char>, std::allocator<char>> // overload resolution ranks reference binding from lvalue std::cin // and picks the first of the two candidate specializations ``` If deduction fails, or if deduction succeeds, but the specialization it produces would be invalid (for example, an overloaded operator whose parameters are neither class nor enumeration types), the specialization is not included in the overload set, similar to [SFINAE](sfinae "cpp/language/sfinae"). #### Address of an overload set Template argument deduction is used when taking an [address of a overload set](overloaded_address "cpp/language/overloaded address"), which includes function templates. The function type of the function template is `P`. The [target type](overloaded_address "cpp/language/overloaded address") is the type of `A`: ``` std::cout << std::endl; // std::endl names a function template // type of endl P = // std::basic_ostream<CharT, Traits>& (std::basic_ostream<CharT, Traits>&) // operator<< parameter A = // std::basic_ostream<char, std::char_traits<char>>& (*)( // std::basic_ostream<char, std::char_traits<char>>& // ) // (other overloads of operator<< are not viable) // deduction determines the type template parameters CharT and Traits ``` An additional rule is applied to the deduction in this case: when comparing function parameters `P`i and `A`i, if any `P`i is an rvalue reference to cv-unqualified template parameter (a "forwarding reference") and the corresponding `A`i is an lvalue reference, then `P`i is adjusted to the template parameter type (T&& becomes T). | | | | --- | --- | | If the return type of the function template is a placeholder (`auto` or `decltype(auto)`), that return type is a non-deduced context and is determined from the instantiation. | (since C++14) | #### Partial ordering Template argument deduction is used during [partial ordering of overloaded function templates](function_template "cpp/language/function template"). #### Conversion function template Template argument deduction is used when selecting [user-defined conversion function](cast_operator "cpp/language/cast operator") template arguments. `A` is the type that is required as the result of the conversion. `P` is the return type of the conversion function template. If `P` is a reference type, then the referred type is used in place of `P` for the following parts of the section. If `A` is not a reference type: a) if the `P` is an array type, then the pointer type obtained by array-to-pointer conversion is used in place of `P`; b) if the `P` is a function type, then the function pointer type obtained by function-to-pointer conversion is used in place of `P`; c) if `P` is cv-qualified, the top-level cv-qualifiers are ignored. If `A` is cv-qualified, the top-level cv-qualifiers are ignored. If `A` is a reference type, the referred type is used by deduction. If the usual deduction from `P` and `A` (as described above) fails, the following alternatives are additionally considered: a) if `A` is a reference type, `A` can be more cv-qualified than the deduced `A`; b) if `A` is a pointer or pointer to member type, the deduced `A` is allowed to be any pointer that can be converted to `A` by qualification conversion: ``` struct A { template<class T> operator T***(); }; A a; const int* const* const* p1 = a; // P = T***, A = const int* const* const* // regular function-call deduction for // template<class T> void f(T*** p) as if called with the argument // of type const int* const* const* fails // additional deduction for conversion functions determines T = int // (deduced A is int***, convertible to const int* const* const*) ``` | | | | --- | --- | | c) if `A` is a function pointer type, the deduced `A` is allowed to be pointer to noexcept function, convertible to `A` by function pointer conversion; d) if `A` is a pointer to member function, the deduced `A` is allowed to be a pointer to noexcept member function, convertible to `A` by function pointer conversion. | (since C++17) | See [member template](member_template#Conversion_function_templates "cpp/language/member template") for other rules regarding conversion function templates. #### Explicit instantiation Template argument deduction is used in [explicit instantiations](function_template#Explicit_instantiation "cpp/language/function template"), [explicit specializations](template_specialization "cpp/language/template specialization"), and those [friend declarations](friend#Template_friends "cpp/language/friend") where the declarator-id happens to refer to a specialization of a function template (for example, `friend ostream& operator<< <> (...)`), if not all template arguments are explicitly specified or defaulted, template argument deduction is used to determine which template's specialization is referred to. `P` is the type of the function template that is being considered as a potential match, and `A` is the function type from the declaration. If there are no matches or more than one match (after partial ordering), the function declaration is ill-formed: ``` template<class X> void f(X a); // 1st template f template<class X> void f(X* a); // 2nd template f template<> void f<>(int* a) {} // explicit specialization of f // P1 = void(X), A1 = void(int*): deduced X = int*, f<int*>(int*) // P2 = void(X*), A2 = void(int*): deduced X = int, f<int>(int*) // f<int*>(int*) and f<int>(int*) are then submitted to partial ordering // which selects f<int>(int*) as the more specialized template ``` An additional rule is applied to the deduction in this case: when comparing function parameters `P`i and `A`i, if any `P`i is an rvalue reference to cv-unqualified template parameter (a "forwarding reference") and the corresponding `A`i is an lvalue reference, then `P`i is adjusted to the template parameter type (T&& becomes T). #### Deallocation function template Template argument deduction is used when determining if a [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete") template specialization matches a given placement form of `operator new`. `P` is the type of the function template that is being considered as a potential match, and `A` is the function type of the deallocation function that would be the match for the placement operator new under consideration. If there is no match or more than one match (after overload resolution), the placement deallocation function is not called (memory leak may occur): ``` struct X { X() { throw std::runtime_error(""); } static void* operator new(std::size_t sz, bool b) { return ::operator new(sz); } static void* operator new(std::size_t sz, double f) { return ::operator new(sz); } template<typename T> static void operator delete(void* ptr, T arg) { ::operator delete(ptr); } }; int main() { try { X* p1 = new (true) X; // when X() throws, operator delete is looked up // P1 = void(void*, T), A1 = void(void*, bool): // deduced T = bool // P2 = void(void*, T), A2 = void(void*, double): // deduced T = double // overload resolution picks operator delete<bool> } catch(const std::exception&) {} try { X* p1 = new (13.2) X; // same lookup, picks operator delete<double> } catch(const std::exception&) {} } ``` ### Alias templates [Alias templates](type_alias "cpp/language/type alias") are not deduced , except in [class template argument deduction](class_template_argument_deduction#Deduction_for_alias_templates "cpp/language/class template argument deduction") (since C++20): ``` template<class T> struct Alloc {}; template<class T> using Vec = vector<T, Alloc<T>>; Vec<int> v; template<template<class, class> class TT> void g(TT<int, Alloc<int>>); g(v); // OK: deduced TT = vector template<template<class> class TT> void f(TT<int>); f(v); // error: TT cannot be deduced as "Vec" because Vec is an alias template ``` ### Implicit conversions Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for [overload resolution](overload_resolution "cpp/language/overload resolution"), which happens later. However, if deduction succeeds for all parameters that participate in template argument deduction, and all template arguments that aren't deduced are explicitly specified or defaulted, then the remaining function parameters are compared with the corresponding function arguments. For each remaining parameter `P` with a type that was non-dependent before substitution of any explicitly-specified template arguments, if the corresponding argument `A` cannot be implicitly converted to `P`, deduction fails. Parameters with dependent types in which no template-parameters participate in template argument deduction, and parameters that became non-dependent due to substitution of explicitly-specified template arguments will be checked during overload resolution: ``` template<class T> struct Z { typedef typename T::x xx; }; template<class T> typename Z<T>::xx f(void*, T); // #1 template<class T> void f(int, T); // #2 struct A {} a; int main() { f(1, a); // for #1, deduction determines T = struct A, but the remaining argument 1 // cannot be implicitly converted to its parameter void*: deduction fails // instantiation of the return type is not requested // for #2, deduction determines T = struct A, and the remaining argument 1 // can be implicitly converted to its parameter int: deduction succeeds // the function call compiles as a call to #2 (deduction failure is SFINAE) } ``` ### 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 70](https://cplusplus.github.io/CWG/issues/70.html) | C++98 | whether array bounds would be deduced was not specified | specified as non-deduced | | [CWG 300](https://cplusplus.github.io/CWG/issues/300.html) | C++98 | deduction took place for function parameters of form`type(*)(T)/T(*)()/T(*)(T)`, function pointersmatch these forms but function references do not | change these forms to`type(T)/T()/T(T)` so theycan also cover references | | [CWG 322](https://cplusplus.github.io/CWG/issues/322.html) | C++98 | type parameters of reference types were notadjusted to use the referenced type for deduction | adjustment added | | [CWG 976](https://cplusplus.github.io/CWG/issues/976.html) | C++98 | in the deduction for conversion operator templates,`const T&` return type could never match `T` result type | rules adjusted toallow such matches | | [CWG 1387](https://cplusplus.github.io/CWG/issues/1387.html) | C++11 | the expression of a decltype-specifier was not a non-deduced context | it is | | [CWG 1391](https://cplusplus.github.io/CWG/issues/1391.html) | C++98 | effect of implicit conversions of the argumentsthat aren't involved in deduction were not specified | specified as described above | | [CWG 1591](https://cplusplus.github.io/CWG/issues/1591.html) | C++11 | cannot deduce array bound and element type from a *braced-init-list* | deduction allowed | | [CWG 2052](https://cplusplus.github.io/CWG/issues/2052.html) | C++98 | deducing an operator with non-classnon-enum arguments was a hard error | soft error if thereare other overloads | | [CWG 2091](https://cplusplus.github.io/CWG/issues/2091.html) | C++98 | deducing a reference non-type parameter did notwork due to type mismatch against the argument | type mismatch avoided | | [N3922](https://wg21.link/N3922) | C++11 | direct-list-initialization of `auto` deduces `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` | ill-formed for more than oneelements, deduce elementtype for single element | | [CWG 2355](https://cplusplus.github.io/CWG/issues/2355.html) | C++17 | value in a `noexcept` specifier of a function type was not deducible | made deducible |
programming_docs
cpp Identifiers Identifiers =========== An *identifier* is an arbitrarily long sequence of digits, underscores, lowercase and uppercase Latin letters, and most Unicode characters. A valid identifier must begin with a non-digit character (Latin letter, underscore, or Unicode character of class [XID\_Start](https://www.unicode.org/reports/tr31/#Table_Lexical_Classes_for_Identifiers)) and may contain non-digit characters, digits, and Unicode characters of class [XID\_Continue](https://www.unicode.org/reports/tr31/#Table_Lexical_Classes_for_Identifiers) in non-initial positions. Identifiers are case-sensitive (lowercase and uppercase letters are distinct), and every character is significant. Every identifier must conform to [Normalization Form C](https://www.unicode.org/charts/normalization/). Note: Support of Unicode identifiers is limited in most implementations, e.g. [gcc (until 10)](https://gcc.gnu.org/wiki/FAQ#What_is_the_status_of_adding_the_UTF-8_support_for_identifier_names_in_GCC.3F). ### In declarations An identifier can be used [to name](declarations "cpp/language/declarations") objects, references, functions, enumerators, types, class members, namespaces, templates, template specializations, parameter packs (since C++11) goto labels, and other entities, with the following exceptions: * the identifiers that are [keywords](../keyword "cpp/keyword") cannot be used for other purposes; | | | | --- | --- | | * The only place they can be used as non-keywords is in an attribute-token. (e.g. `[[private]]` is a valid [attribute](attributes "cpp/language/attributes")) | (since C++11) | * the identifiers that are [alternative representations](operator_alternative "cpp/language/operator alternative") for certain operators and punctuators cannot be used for other purposes; | | | | --- | --- | | * the identifiers with special meaning (`final`, `import`, `module` (since C++20) and `override`) are used explicitly in a certain context rather than being regular identifiers; + Unless otherwise specified, any ambiguity as to whether a given identifier has a special meaning is resolved to interpret the token as a regular identifier. | (since C++11) | * the identifiers with a double underscore anywhere are reserved; * the identifiers that begin with an underscore followed by an uppercase letter are reserved; * the identifiers that begin with an underscore are reserved in the global namespace. "Reserved" here means that the standard library headers `#define` or declare such identifiers for their internal needs, the compiler may predefine non-standard identifiers of that kind, and that name mangling algorithm may assume that some of these identifiers are not in use. If the programmer uses such identifiers, the behavior is undefined. In addition, it's undefined behavior to `#define` or `#undef` certain names in a translation unit, see [reserved macro names](../preprocessor/replace "cpp/preprocessor/replace") for more details. #### Zombie identifiers As of C++14, some identifiers are removed from the C++ standard library. They are listed in the [list of zombie names](../symbol_index/zombie_names "cpp/symbol index/zombie names"). However, these identifiers are still reserved for previous standardization in a certain context. Removed member function names may not be used as a name for function-like macros, and other removed member names may not be used as a name for object-like macros in portable code. ### In expressions An identifier that names a variable, a function, specialization of a [concept](constraints "cpp/language/constraints"), (since C++20) or an enumerator can be used as an [expression](expressions "cpp/language/expressions"). The result of an expression consisting of just the identifier is the entity named by the identifier. The [value category](value_category "cpp/language/value category") of the expression is *lvalue* if the identifier names a function, a variable, a [template parameter object](template_parameters#Non-type_template_parameter "cpp/language/template parameters") (since C++20), or a data member, and *rvalue* (until C++11)*prvalue* (since C++11) otherwise (e.g. an [enumerator](enum "cpp/language/enum") is an rvalue (until C++11)a prvalue (since C++11) expression, a specialization of a concept is a bool prvalue (since C++20)). The type of the expression is determined as follows: | | | | --- | --- | | * If the entity named by the (unqualified) identifier is a local entity, and would result in an intervening [lambda expression](lambda "cpp/language/lambda") capturing it by copy if it were named outside of an unevaluated operand in the declarative region in which the identifier appears, then the type of the expression is the type of a [class member access expression](operator_member_access "cpp/language/operator member access") naming the non-static data member that would be declared for such a capture in the closure object of the innermost such intervening lambda expression. ``` void f() { float x, &r = x; [=] { decltype(x) y1; // y1 has type float decltype((x)) y2 = y1; // y2 has type float const& because this lambda // is not mutable and x is an lvalue decltype(r) r1 = y1; // r1 has type float& decltype((r)) r2 = y2; // r2 has type float const& }; } ``` | (since C++11) | | * If the entity named is a template parameter object for a template parameter of type `T`, the type of the expression is `const T`. | (since C++20) | * Otherwise, the type of the expression is the same as the type of the entity named. Within the body of a non-static [member function](member_functions "cpp/language/member functions"), each identifier that names a non-static member is implicitly transformed to a class member access expression `this->member`. #### Unqualified identifiers Besides suitably declared identifiers, the following can be used in expressions in the same role: * an [overloaded operator](operators "cpp/language/operators") name in function notation, such as `operator+` or `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)`; * a [user-defined conversion function](cast_operator "cpp/language/cast operator") name, such as `operator bool`; | | | | --- | --- | | * a [user-defined literal operator](user_literal "cpp/language/user literal") name, such as `operator "" _km`; | (since C++11) | * a [template](templates "cpp/language/templates") name followed by its argument list, such as `MyTemplate<int>`; * the character `~` followed by a class name, such as `~MyClass`; | | | | --- | --- | | * the character `~` followed by a [decltype](decltype "cpp/language/decltype") specifier, such as `~decltype(str)`. | (since C++11) | Together with identifiers they are known as *unqualified id-expressions*. #### Qualified identifiers A *qualified id-expression* is an unqualified id-expression prepended by a scope resolution operator `::`, and optionally, a sequence of any of the following separated by scope resolution operators: * a namespace name; * a class name; | | | | --- | --- | | * an enumeration name; * a [decltype expression](decltype "cpp/language/decltype") denoting a class or enumeration type. | (since C++11) | For example, the expression `[std::string::npos](http://en.cppreference.com/w/cpp/string/basic_string/npos)` is an expression that names the static member `npos` in the class `string` in namespace `std`. The expression `::tolower` names the function `tolower` in the global namespace. The expression `::[std::cout](http://en.cppreference.com/w/cpp/io/cout)` names the global variable `cout` in namespace `std`, which is a top-level namespace. The expression `boost::signals2::connection` names the type `connection` declared in namespace `signals2`, which is declared in namespace `boost`. The keyword [`template`](../keyword/template "cpp/keyword/template") may appear in qualified identifiers as necessary to disambiguate [dependent template names](dependent_name "cpp/language/dependent name"). See [qualified lookup](qualified_lookup "cpp/language/qualified lookup") for the details of the name lookup for qualified identifiers. ### Names A *name* is the use of one of the following to refer to an entity: * an identifier; * an overloaded operator name in function notation (`operator+`, `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)`); * a user-defined conversion function name (`operator bool`); | | | | --- | --- | | * a user-defined literal operator name (`operator "" _km`); | (since C++11) | * a template name followed by its argument list (`MyTemplate<int>`). Every name is introduced into the program by a [declaration](declarations "cpp/language/declarations"). A name used in more than one translation unit may refer to the same or different entities, depending on [linkage](storage_duration#Linkage "cpp/language/storage duration"). When the compiler encounters an unknown name in a program, it associates it with the declaration that introduced the name by means of [name lookup](lookup "cpp/language/lookup"), except for the [dependent names](dependent_name "cpp/language/dependent name") in template declarations and definitions (for those names, the compiler determines whether they name a type, a template, or some other entity, which may require [explicit disambiguation](dependent_name "cpp/language/dependent name")). ### 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 1440](https://cplusplus.github.io/CWG/issues/1440.html) | C++11 | decltype expressions preceding `::` could denote any type | can only denote class or enumeration types | | [CWG 1963](https://cplusplus.github.io/CWG/issues/1963.html) | C++11 | implementation-defined characters other than digits, non-digitsand universal character names could be used in an identifier | prohobited | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/identifier "c/language/identifier") for Identifiers | cpp Other operators Other operators =============== | Operatorname | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | function call | `a(a1, a2)` | Yes | `R T::operator()(Arg1 &a1, Arg2 &a2, ...);` | N/A | | comma | `a, b` | Yes | `T2& T::operator,(T2 &b);` | `T2& operator,(const T &a, T2 &b);` | | conditional operator | `a ? b : c` | No | N/A | N/A | ### Explanation The *function call* operator provides function semantics for any object. The *conditional operator* (colloquially referred to as *ternary conditional*) checks the boolean value of the first expression and, depending on the resulting value, evaluates and returns either the second or the third expression. #### Built-in function call operator The function call expressions have the form. | | | | | --- | --- | --- | | E `(` A1`,` A2`,` A3`,`...`)` | | | where. * E is an expression that names a [function](functions "cpp/language/functions") * A1`,` A2`,` A3`,`... is a possibly empty list of arbitrary expressions or braced-init-lists (since C++11), except the comma operator is not allowed at the top level to avoid ambiguity. The expression that names the function can be. a) lvalue expression that refers to a function b) pointer to function c) explicit [class member access](operator_member_access "cpp/language/operator member access") expression that selects a member function d) implicit class member access expression, e.g. member function name used within another member function. The function (or member) name specified by `E` can be overloaded, [overload resolution](overload_resolution "cpp/language/overload resolution") rules used to decide which overload is to be called. If `E` specifies a member function, it may be virtual, in which case the final overrider of that function will be called, using dynamic dispatch at runtime. To call the function, | | | | --- | --- | | The expression `E` as well as all expressions `A1`, `A2`, `A3`, etc, provided as arguments are evaluated in arbitrary order, [unsequenced](eval_order "cpp/language/eval order") with respect to each other. | (until C++17) | | The expression `E` is sequenced before each of the expressions `A1`, `A2`, `A3` as well as default arguments, if any. The argument expressions are evaluated in arbitrary order, [indeterminately sequenced](eval_order "cpp/language/eval order") with respect to each other. | (since C++17) | Each function parameter is initialized with its corresponding argument after [implicit conversion](implicit_conversion "cpp/language/implicit conversion") if necessary. If there is no corresponding argument, the corresponding [default argument](default_arguments "cpp/language/default arguments") is used, and if there is none, the program is ill-formed. If the call is made to a member function, then the `this` pointer to current object is converted as if by explicit cast to the `this` pointer expected by the function. The initialization and destruction of each parameter occurs in the context of the caller, which means, for example, that if constructor of a parameter throws an exception, the exception handlers defined within the function, even as a function-try block, are not considered. If the function is a variadic function, [default argument promotions](variadic_arguments#Default_conversions "cpp/language/variadic arguments") are applied to all arguments matched by the ellipsis parameter. It is implementation-defined whether the [lifetime](lifetime "cpp/language/lifetime") of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression. The return type of a function call expression is the return type of the chosen function, decided using static binding (ignoring the `virtual` keyword), even if the overriding function that's actually called returns a different type. This allows the overriding functions to return pointers or references to classes that are derived from the return type returned by the base function, i.e. C++ supports [covariant return types](https://en.wikipedia.org/wiki/Covariant_return_type "enwiki:Covariant return type"). If `E` specifies a destructor, the return type is `void`. | | | | --- | --- | | When an object of class type `X` is passed to or returned from a function, if each copy constructor, move constructor, and destructor of `X` is either trivial or deleted, and `X` has at least one non-deleted copy or move constructor, implementations are permitted to create a temporary object to hold the function parameter or result object. The temporary object is constructed from the function argument or return value, respectively, and the function's parameter or return object is initialized as if by using the non-deleted trivial constructor to copy the temporary (even if that constructor is inaccessible or would not be selected by overload resolution to perform a copy or move of the object). This allows objects of small class types, such as `[std::complex](../numeric/complex "cpp/numeric/complex")` or `std::span`, to be passed to or returned from functions in registers. | (since C++17) | The value category of a function call expression is lvalue if the function returns an lvalue reference or an rvalue reference to function, is an xvalue if the function returns an rvalue reference to object, and is a prvalue otherwise. If the function call expression is a prvalue of object type, it must have complete type except when the prvalue is not materialized, such as (since C++17) when used as the operand of [`decltype`](decltype "cpp/language/decltype") (or as the right operand of a [built-in comma operator](#Built-in_comma_operator) that is the operand of `decltype`). Function call expression is similar in syntax to value initialization `T()`, to [function-style cast](explicit_cast "cpp/language/explicit cast") expression `T(A1)`, and to direct initialization of a temporary `T(A1, A2, A3, ...)`, where `T` is the name of a type. ``` #include <cstdio> struct S { int f1(double d) { return printf("%f \n", d); // variable argument function call } int f2() { return f1(7); // member function call, same as this->f1() // integer argument converted to double } }; void f() { puts("function called"); // function call } int main() { f(); // function call S s; s.f2(); // member function call } ``` Output: ``` function called 7.000000 ``` #### Built-in comma operator The comma operator expressions have the form. | | | | | --- | --- | --- | | E1 `,` E2 | | | In a comma expression `E1, E2`, the expression `E1` is evaluated, its result is [discarded](expressions#Discarded-value_expressions "cpp/language/expressions") (although if it has class type, it won't be destroyed [until the end of the containing full expression](lifetime#Temporary_object_lifetime "cpp/language/lifetime")), and its side effects are completed before evaluation of the expression `E2` begins (note that a user-defined `operator,` cannot guarantee sequencing) (until C++17). The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, `E2`. If `E2` is a temporary expression (since C++17), the result of the expression is that temporary expression (since C++17). If `E2` is a bit-field, the result is a bit-field. The comma in various comma-separated lists, such as function argument lists (`f(a, b, c)`) and initializer lists `int a[] = {1, 2, 3}`, is not the comma operator. If the comma operator needs to be used in such contexts, it has to be parenthesized: `f(a, (n++, n + b), c)`. | | | | --- | --- | | Using an unparenthesized comma expression as second (right) argument of a [subscript operator](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") is deprecated. For example, `a[b, c]` is deprecated and `a[(b, c)]` is not. | (since C++20)(until C++23) | | An unparenthesized comma expression cannot be second (right) argument of a [subscript operator](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access"). For example, `a[b, c]` is either ill-formed or equivalent to `a.operator[](b, c)`. Parentheses are needed to for using a comma expression as the subscript, e.g., `a[(b, c)]`. | (since C++23) | ``` #include <iostream> int main() { int n = 1; int m = (++n, std::cout << "n = " << n << '\n', ++n, 2 * n); std::cout << "m = " << (++m, m) << '\n'; } ``` Output: ``` n = 2 m = 7 ``` #### Conditional operator The conditional operator expressions have the form. | | | | | --- | --- | --- | | E1 `?` E2 `:` E3 | | | The first operand of the conditional operator is evaluated and [contextually converted](implicit_conversion "cpp/language/implicit conversion") to `bool`. After both the value evaluation and all side effects of the first operand are completed, if the result was `true`, the second operand is evaluated. If the result was `false`, the third operand is evaluated. The type and value category of the conditional expression `E1 ? E2 : E3` are determined according to the following rules: 1) If either `E2` or `E3` has type `void`, then one of the following must be true, or the program is ill-formed: 1.1) Either `E2` or `E3` (but not both) is a (possibly parenthesized) [throw-expression](throw "cpp/language/throw"). The result of the conditional operator has the type and the value category of the other expression. If the other expression is a [bit-field](bit_field "cpp/language/bit field"), the result is a bit-field. Such conditional operator was commonly used in C++11 [constexpr programming](constexpr "cpp/language/constexpr") prior to C++14. ``` std::string str = 2 + 2 == 4 ? "OK" : throw std::logic_error("2 + 2 != 4"); ``` 1.2) Both `E2` and `E3` are of type `void` (including the case when they are both throw-expressions). The result is a prvalue of type `void`. ``` 2 + 2 == 4 ? throw 123 : throw 456; ``` 2) Otherwise, if `E2` or `E3` are glvalue bit-fields of the same value category and of types cv1 T and cv2 T, respectively, the operands are considered to be of type cv T for the remainder of this section, where cv is the union of cv1 and cv2. 3) Otherwise, if `E2` and `E3` have different types, at least one of which is a (possibly cv-qualified) class type, or both are glvalues of the same value category and have the same type except for cv-qualification, then an attempt is made to form an [implicit conversion sequence](implicit_conversion "cpp/language/implicit conversion") ignoring member access, whether an operand is a bit-field, or whether a conversion function is deleted from each of the operands to the *target type* determined by the other operand (since C++11), as described below. An operand (call it `X`) of type `TX` can be converted to the *target type* of the other operand (call it `Y`) of type `TY` as follows: 3.1) If `Y` is an lvalue, the target type is `TY&`, and the reference must bind directly to an lvalue (until C++11)a glvalue (since C++11); | | | | --- | --- | | 3.2) If `Y` is an xvalue, the target type is `TY&&`, and the reference must bind directly; | (since C++11) | 3.3) If `Y` is an rvalue (until C++11)a prvalue (since C++11), or if neither the above conversion sequences can be formed and at least one of `TX` and `TY` is a (possibly cv-qualified) class type, 3.3.1) if `TX` and `TY` are the same class type (ignoring cv-qualification) and `TY` is at least as cv-qualified as `TX`, the target type is `TY`, 3.3.2) otherwise, if `TY` is a base class of `TX`, the target type is `TY` with the cv-qualifiers of `TX`: ``` struct A {}; struct B : A {}; using T = const B; A a = true ? A() : T(); // Y = A(), TY = A, X = T(), TX = const B, Target = const A ``` 3.3.3) otherwise, the target type is the type that `Y` would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer [standard conversions](implicit_conversion "cpp/language/implicit conversion") 3.4) If both sequences can be formed (`E2` to target type of `E3` and `E3` to target type of `E2`), or only one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. 3.5) If exactly one conversion sequence can be formed (note that it may still be ill-formed e.g. due to access violation), that conversion sequence is applied and the converted operand is used in place of the original operand for the remained of this description (starting at (4)) 3.6) If no conversion sequence can be formed, the operands are left unchanged for the remainder of this description 4) If `E2` and `E3` are glvalues of the same type and the same value category, then the result has the same type and value category, and is a bit-field if at least one of `E2` and `E3` is a bit-field. 5) Otherwise, the result is a prvalue. If `E2` and `E3` do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is performed using the built-in candidates below to attempt to convert the operands to built-in types. If the overload resolution fails, the program is ill-formed. Otherwise, the selected conversions are applied and the converted operands are used in place of the original operands for step 6. 6) The lvalue-to-rvalue, array-to-pointer, and function-to-pointer conversions are applied to the second and third operands. Then, 6.1) If both `E2` and `E3` now have the same type, the result is a prvalue of that type designating a temporary object (until C++17)whose result object is (since C++17) copy-initialized from whatever operand was selected after evaluating `E1`. 6.2) If both `E2` and `E3` have arithmetic or enumeration type: the [*usual arithmetic conversions*](operator_arithmetic#conversions "cpp/language/operator arithmetic") are applied to bring them to *common type*, and that type is the result. 6.3) If both `E2` and `E3` are pointers, or one is a pointer and the other is a null pointer constant, then pointer conversions and qualification conversions are applied to bring them to common type, and that type is the result. ``` int* intPtr; using Mixed = decltype(true ? nullptr : intPtr); static_assert(std::is_same_v<Mixed, int*>); // nullptr becoming int* ``` 6.4) If both `E2` and `E3` are pointers to members, or one is a pointer to member and the other is a null pointer constant, then pointer-to-member conversions and qualification conversions are applied to bring them to common type, and that type is the result. ``` struct A { int* m_ptr; } a; int* A::* memPtr = &A::m_ptr; // memPtr is a pointer to member m_ptr of A // memPtr makes nullptr as type of pointer to member m_ptr of A static_assert(std::is_same_v<decltype(false ? memPtr : nullptr), int*A::*>); // a.*memPtr is now just pointer to int and nullptr also becomes pointer to int static_assert(std::is_same_v<decltype(false ? a.*memPtr : nullptr), int*>); ``` 6.5) If both `E2` and `E3` are null pointer constants, and at least one of which is of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`, then the result's type is `std::nullptr_t`. 6.6) In all other cases, the program is ill-formed. For every pair of promoted arithmetic types `L` and `R` and for every type `P`, where `P` is a pointer, pointer-to-member, or scoped enumeration type, the following function signatures participate in the overload resolution performed in step 5 of the rules above: | | | | | --- | --- | --- | | ``` LR operator?:(bool, L, R); ``` | | | | ``` P operator?:(bool, P, P); ``` | | | where LR is the result of [usual arithmetic conversions](operator_arithmetic "cpp/language/operator arithmetic") performed on `L` and `R`. The operator “`?:`” cannot be overloaded, these function signatures only exist for the purpose of overload resolution. The return type of a conditional operator is also accessible as the binary type trait `[std::common\_type](../types/common_type "cpp/types/common type")`. ``` #include <string> #include <iostream> struct Node { Node* next; int data; // deep-copying copy constructor Node(const Node& other) : next(other.next ? new Node(*other.next) : NULL) , data(other.data) {} Node(int d) : next(NULL), data(d) {} ~Node() { delete next ; } }; int main() { // simple rvalue example int n = 1 > 2 ? 10 : 11; // 1 > 2 is false, so n = 11 // simple lvalue example int m = 10; (n == m ? n : m) = 7; // n == m is false, so m = 7 //output the result std::cout << "n = " << n << "\nm = " << m; } ``` Output: ``` n = 11 m = 7 ``` ### Standard library Many classes in the standard library overload `operator()` to be used as function objects. | | | | --- | --- | | [operator()](../memory/default_delete "cpp/memory/default delete") | deletes the object or array (public member function of `std::default_delete<T>`) | | [operator()](../utility/functional/plus "cpp/utility/functional/plus") | returns the sum of two arguments (public member function of `std::plus<T>`) | | [operator()](../utility/functional/minus "cpp/utility/functional/minus") | returns the difference between two arguments (public member function of `std::minus<T>`) | | [operator()](../utility/functional/multiplies "cpp/utility/functional/multiplies") | returns the product of two arguments (public member function of `std::multiplies<T>`) | | [operator()](../utility/functional/divides "cpp/utility/functional/divides") | returns the result of the division of the first argument by the second argument (public member function of `std::divides<T>`) | | [operator()](../utility/functional/modulus "cpp/utility/functional/modulus") | returns the remainder from the division of the first argument by the second argument (public member function of `std::modulus<T>`) | | [operator()](../utility/functional/negate "cpp/utility/functional/negate") | returns the negation of the argument (public member function of `std::negate<T>`) | | [operator()](../utility/functional/equal_to "cpp/utility/functional/equal to") | checks if the arguments are equal (public member function of `std::equal_to<T>`) | | [operator()](../utility/functional/not_equal_to "cpp/utility/functional/not equal to") | checks if the arguments are not equal (public member function of `std::not_equal_to<T>`) | | [operator()](../utility/functional/greater "cpp/utility/functional/greater") | checks if the first argument is greater than the second (public member function of `std::greater<T>`) | | [operator()](../utility/functional/less "cpp/utility/functional/less") | checks if the first argument is less than the second (public member function of `std::less<T>`) | | [operator()](../utility/functional/greater_equal "cpp/utility/functional/greater equal") | checks if the first argument is greater than or equal to the second (public member function of `std::greater_equal<T>`) | | [operator()](../utility/functional/less_equal "cpp/utility/functional/less equal") | checks if the first argument is less than or equal to the second (public member function of `std::less_equal<T>`) | | [operator()](../utility/functional/logical_and "cpp/utility/functional/logical and") | returns the logical AND of the two arguments (public member function of `std::logical_and<T>`) | | [operator()](../utility/functional/logical_or "cpp/utility/functional/logical or") | returns the logical OR of the two arguments (public member function of `std::logical_or<T>`) | | [operator()](../utility/functional/logical_not "cpp/utility/functional/logical not") | returns the logical NOT of the argument (public member function of `std::logical_not<T>`) | | [operator()](../utility/functional/bit_and "cpp/utility/functional/bit and") | returns the result of bitwise AND of two arguments (public member function of `std::bit_and<T>`) | | [operator()](../utility/functional/bit_or "cpp/utility/functional/bit or") | returns the result of bitwise OR of two arguments (public member function of `std::bit_or<T>`) | | [operator()](../utility/functional/bit_xor "cpp/utility/functional/bit xor") | returns the result of bitwise XOR of two arguments (public member function of `std::bit_xor<T>`) | | [operator()](../utility/functional/unary_negate "cpp/utility/functional/unary negate") | returns the logical complement of the result of a call to the stored predicate (public member function of `std::unary_negate<Predicate>`) | | [operator()](../utility/functional/binary_negate "cpp/utility/functional/binary negate") | returns the logical complement of the result of a call to the stored predicate (public member function of `std::binary_negate<Predicate>`) | | [operator()](../utility/functional/reference_wrapper/operator() "cpp/utility/functional/reference wrapper/operator()") | calls the stored function (public member function of `std::reference_wrapper<T>`) | | [operator()](../utility/functional/function/operator() "cpp/utility/functional/function/operator()") | invokes the target (public member function of `std::function<R(Args...)>`) | | [operator()](../locale/locale/operator() "cpp/locale/locale/operator()") | lexicographically compares two strings using this locale's collate facet (public member function of `std::locale`) | | [operator()](../container/map/value_compare "cpp/container/map/value compare") | compares two values of type `value_type` (public member function of `std::map<Key,T,Compare,Allocator>::value_compare`) | | [operator()](../container/multimap/value_compare "cpp/container/multimap/value compare") | compares two values of type `value_type` (public member function of `std::multimap<Key,T,Compare,Allocator>::value_compare`) | | [operator()](../thread/packaged_task/operator() "cpp/thread/packaged task/operator()") | executes the function (public member function of `std::packaged_task<R(Args...)>`) | | [operator()](../numeric/random/linear_congruential_engine/operator() "cpp/numeric/random/linear congruential engine/operator()") (C++11) | advances the engine's state and returns the generated value (public member function of `std::linear_congruential_engine<UIntType,a,c,m>`) | | [operator()](../numeric/random/uniform_int_distribution/operator() "cpp/numeric/random/uniform int distribution/operator()") (C++11) | generates the next random number in the distribution (public member function of `std::uniform_int_distribution<IntType>`) | The comma operator is not overloaded by any class in the standard library. The boost library uses `operator,` in [boost.assign](https://www.boost.org/doc/libs/release/libs/assign/doc/index.html#intro), [boost.spirit](https://www.boost.org/doc/libs/release/libs/spirit/doc/html/index.html), and other libraries. The database access library [SOCI](http://soci.sourceforge.net/doc.html) also overloads `operator,`. ### 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 446](https://cplusplus.github.io/CWG/issues/446.html) | C++98 | it was unspecified whether a temporary is created for anlvalue-to-rvalue conversion on the conditional operator | always creates a temporary ifthe operator returns a class rvalue | | [CWG 462](https://cplusplus.github.io/CWG/issues/462.html) | C++98 | if the second operand of a comma operator is a temporary,it was unspecified whether its lifetime will be extended whenthe result of the comma expression is bound to a reference | the result of the comma expressionis the temporary in this case(hence its lifetime is extended) | | [CWG 587](https://cplusplus.github.io/CWG/issues/587.html) | C++98 | when the second and third operands of a conditionaloperator are lvalues of the same type except forcv-qualification, the result was an lvalue if theseoperands have class types or an rvalue otherwise | the result is alwaysan lvalue in this case | | [CWG 1029](https://cplusplus.github.io/CWG/issues/1029.html) | C++98 | the type of a destructor call was unspecified | specified as `void` | | [CWG 1550](https://cplusplus.github.io/CWG/issues/1550.html) | C++98 | parenthesized throw-expression were not allowed inconditional expressions if other operand is non-void | accepted | | [CWG 1560](https://cplusplus.github.io/CWG/issues/1560.html) | C++98 | void operand of conditional operators causedgratuitous lvalue-to-rvalue conversion on theother operand, always resulting in rvalue | a conditional expressionwith a void can be lvalue | | [CWG 1805](https://cplusplus.github.io/CWG/issues/1805.html) | C++98 | in case 3.3.3) of conditional expressions, array-to-pointerand function-to-pointer conversions were not applied | apply these conversions | | [CWG 1895](https://cplusplus.github.io/CWG/issues/1895.html) | C++98C++11 | unclear if deleted (C++11) or inaccessible (C++98)conversion function prevents conversion inconditional expressions, and conversions from baseclass to derived class prvalue were not considered | handled likeoverload resolution | | [CWG 1932](https://cplusplus.github.io/CWG/issues/1932.html) | C++98 | same-type bit-fields were missing in conditional expressions | handled by underlying types | | [CWG 2226](https://cplusplus.github.io/CWG/issues/2226.html) | C++11 | when determining the target type of the otheroperand of a conditional operator, reference couldnot bind to an xvalue if that operand is an lvalue | allowed | | [CWG 2321](https://cplusplus.github.io/CWG/issues/2321.html) | C++98 | when determining the target type of the other operandof a conditional operator, a derived class type couldnot be converted to a less cv-qualified base class type | allowed to convert to the baseclass type with the cv-qualificationfrom the derived class operand | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence") [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | **other** | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_other "c/language/operator other") for Other operators |
programming_docs
cpp asm declaration asm declaration =============== *asm-declaration* gives the ability to embed assembly language source code within a C++ program. This declaration is conditionally-supported and implementation defined, meaning that it may not be present and, even when provided by the implementation, it does not have a fixed meaning. ### Syntax | | | | | --- | --- | --- | | attr(optional) `asm (` string-literal `)` `;` | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | string-literal | - | a [string literal](string_literal "cpp/language/string literal") | ### Explanation The string-literal is typically a short program written in assembly language, which is executed whenever this declaration is executed. Different C++ compilers have wildly varying rules for asm-declarations, and different conventions for the interaction with the surrounding C++ code. As other [block declarations](declarations "cpp/language/declarations"), this declaration can appear inside a block (a function body or another compound statement), and, as all other declarations, this declaration can also appear outside a block. ### Examples Demonstrates two kinds of inline assembly syntax offered by the GCC compiler. This program will only work correctly on x86\_64 platform under Linux. ``` #include <iostream> extern "C" int func(); // the definition of func is written in assembly language // raw string literal could be very useful asm(R"( .globl func .type func, @function func: .cfi_startproc movl $7, %eax ret .cfi_endproc )"); int main() { int n = func(); // extended inline assembly asm ("leal (%0,%0,4),%0" : "=r" (n) : "0" (n)); std::cout << "7*5 = " << n << std::endl; // flush is intentional // standard inline assembly asm ("movq $60, %rax\n\t" // the exit syscall number on Linux "movq $2, %rdi\n\t" // this program returns 2 "syscall"); } ``` Output: ``` 7*5 = 35 ``` ### 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 195](https://cplusplus.github.io/CWG/issues/195.html) | C++98 | it was required to support all asm declarations | made conditionally-supported | | [CWG 2262](https://cplusplus.github.io/CWG/issues/2262.html) | C++11 | attributes could not be applied to asm declarations | allowed | ### External links * [GCC Inline Assembly HOWTO](http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html) * [IBM XL C/C++ Inline Assembly](https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=compatibility-inline-assembly-statements) * [Intel C++ Inline Assembly](https://www.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/data-align-mem-alloc-intrins-and-inline-asmbly/inline-assembly.html) * [Visual Studio 2013 Inline Assembler](http://msdn.microsoft.com/en-us/library/4ks26t93(v=vs.120).aspx) * [Sun Studio 12 Asm Statements](https://web.archive.org/web/20160528215011/https://blogs.oracle.com/x86be/entry/gcc_style_asm_inlining_support) * [Inline assembly for Itanium-based HP-UX](https://web.archive.org/web/20151009200102/https://h21007.www2.hp.com/portal/site/dspp/menuitem.863c3e4cbcdc3f3515b49c108973a801?ciid=4308e2f5bde02110e2f5bde02110275d6e10RCRD) ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/asm "c/language/asm") for Inline assembly | cpp throw expression `throw` expression =================== Signals an erroneous condition and executes an error handler. ### Syntax | | | | | --- | --- | --- | | `throw` expression | (1) | | | `throw` | (2) | | ### Explanation See [try-catch block](try_catch "cpp/language/try catch") for more information about *try* and *catch* (exception handler) blocks 1) First, [copy-initializes](copy_initialization "cpp/language/copy initialization") the *exception object* from expression | | | | --- | --- | | * This may call the move constructor for rvalue expression. Even if copy initialization selects the move constructor, copy initialization from lvalue must be well-formed, and the destructor must be accessible | (since C++11) | | | | | --- | --- | | * This may also call the move constructor for expressions that name local variables or function or catch-clause parameters whose scope does not extend past the innermost enclosing try-block (if any), by same overload resolution as in [return statement](return "cpp/language/return") | (since C++17) | * The copy/move (since C++11) may be subject to [copy elision](copy_elision "cpp/language/copy elision") then transfers control to the [exception handler](try_catch "cpp/language/try catch") with the matching type for which the compound statement or member initializer list that follows the keyword `try` was most recently entered and not exited by this thread of execution. 2) Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls `[std::terminate](../error/terminate "cpp/error/terminate")` if used otherwise). The catch clause associated with a [function-try-block](function-try-block "cpp/language/function-try-block") must exit via rethrowing if used on a constructor. See `[std::terminate](../error/terminate "cpp/error/terminate")` and `[std::unexpected](../error/unexpected "cpp/error/unexpected")` (until C++17) for the handling of errors that arise during exception handling. ### The exception object The exception object is a temporary object in unspecified storage that is constructed by the `throw` expression. The type of the *exception object* is the static type of expression with top-level [cv-qualifiers](cv "cpp/language/cv") removed. Array and function types are adjusted to pointer and pointer to function types, respectively. If the type of the exception object would be an [incomplete type](incomplete_type "cpp/language/incomplete type"), an [abstract class](abstract_class "cpp/language/abstract class") type, or pointer to incomplete type other than pointer to (cv-qualified) void, the throw-expression is a compile-time error. If the type of expression is a class type, its copy/move (since C++11) constructor and destructor must be accessible even if [copy elision](copy_elision "cpp/language/copy elision") takes place. Unlike other temporary objects, the exception object is considered to be an lvalue argument when initializing the catch clause parameters, so it can be caught by lvalue reference, modified, and rethrown. The exception object persists until the last catch clause exits other than by rethrowing (if not by rethrowing, it is destroyed immediately after the destruction of the catch clause's parameter), or until the last `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` that references this object is destroyed (in which case the exception object is destroyed just before the destructor of `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` returns. ### Stack unwinding Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a [try block](try_catch "cpp/language/try catch"), at which point the parameters of all associated `catch` blocks are compared, in order of appearance, with the type of the exception object to find a match (see [try-catch](try_catch "cpp/language/try catch") for details on this process). If no match is found, the control flow continues to unwind the stack until the next `try` block, and so on. If a match is found, the control flow jumps to the matching `catch` block. As the control flow moves up the call stack, destructors are invoked for all objects with [automatic storage duration](storage_duration "cpp/language/storage duration") that are constructed, but not yet destroyed, since the corresponding try-block was entered, in reverse order of completion of their constructors. If an exception is thrown from a destructor of a local variable or of a temporary used in a [return](return "cpp/language/return") statement, the destructor for the object returned from the function is also invoked. If an exception is thrown from a constructor or (rare) from a destructor of an object (regardless of the object's storage duration), destructors are called for all fully-constructed non-static non-variant members and base classes, in reverse order of completion of their constructors. Variant members of [union-like classes](union#Union-like_classes "cpp/language/union") are only destroyed in the case of unwinding from constructor, and if the active member changed between initialization and destruction, the behavior is undefined. | | | | --- | --- | | If a delegating constructor exits with an exception after the non-delegating constructor successfully completed, the destructor for this object is called. | (since C++11) | If the exception is thrown from a constructor that is invoked by a [new-expression](new "cpp/language/new"), the matching [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete") is called, if available. This process is called *stack unwinding*. If any function that is called directly by the stack unwinding mechanism, after initialization of the exception object and before the start of the exception handler, exits with an exception, `[std::terminate](../error/terminate "cpp/error/terminate")` is called. Such functions include [destructors](destructor "cpp/language/destructor") of objects with automatic storage duration whose scopes are exited, and the copy constructor of the exception object that is called (if not [elided](copy_elision "cpp/language/copy elision")) to initialize catch-by-value arguments. If an exception is thrown and not caught, including exceptions that escape the initial function of `[std::thread](../thread/thread "cpp/thread/thread")`, the main function, and the constructor or destructor of any static or thread-local objects, then `[std::terminate](../error/terminate "cpp/error/terminate")` is called. It is implementation-defined whether any stack unwinding takes place for uncaught exceptions. ### Notes When rethrowing exceptions, the second form must be used to avoid object slicing in the (typical) case where exception objects use inheritance: ``` try { std::string("abc").substr(10); // throws std::length_error } catch (const std::exception& e) { std::cout << e.what() << '\n'; // throw e; // copy-initializes a new exception object of type std::exception throw; // rethrows the exception object of type std::length_error } ``` The throw-expression is classified as [prvalue expression](value_category "cpp/language/value category") of type `void`. Like any other expression, it may be a sub-expression in another expression, most commonly in the [conditional operator](operator_other#Conditional_operator "cpp/language/operator other"): ``` double f(double d) { return d > 1e7 ? throw std::overflow_error("too big") : d; } int main() { try { std::cout << f(1e10) << '\n'; } catch (const std::overflow_error& e) { std::cout << e.what() << '\n'; } } ``` ### Keywords [`throw`](../keyword/throw "cpp/keyword/throw"). ### Example ``` #include <iostream> #include <stdexcept> struct A { int n; A(int n = 0): n(n) { std::cout << "A(" << n << ") constructed successfully\n"; } ~A() { std::cout << "A(" << n << ") destroyed\n"; } }; int foo() { throw std::runtime_error("error"); } struct B { A a1, a2, a3; B() try : a1(1), a2(foo()), a3(3) { std::cout << "B constructed successfully\n"; } catch(...) { std::cout << "B::B() exiting with exception\n"; } ~B() { std::cout << "B destroyed\n"; } }; struct C : A, B { C() try { std::cout << "C::C() completed successfully\n"; } catch(...) { std::cout << "C::C() exiting with exception\n"; } ~C() { std::cout << "C destroyed\n"; } }; int main () try { // creates the A base subobject // creates the a1 member of B // fails to create the a2 member of B // unwinding destroys the a1 member of B // unwinding destroys the A base subobject C c; } catch (const std::exception& e) { std::cout << "main() failed to create C with: " << e.what(); } ``` Output: ``` A(0) constructed successfully A(1) constructed successfully A(1) destroyed B::B() exiting with exception A(0) destroyed C::C() exiting with exception main() failed to create C with: error ``` ### 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 499](https://cplusplus.github.io/CWG/issues/499.html) | C++98 | an array with unknown bound could not be thrown becuaseits type is incomplete, but an exception object can becreated from the decayed pointer without any problem | apply the type completionrequirement to theexception object instead | | [CWG 668](https://cplusplus.github.io/CWG/issues/668.html) | C++98 | `[std::terminate](../error/terminate "cpp/error/terminate")` was not called if an exception is thrownfrom the destructor of a local non-automatic object | call `[std::terminate](../error/terminate "cpp/error/terminate")`in this case | | [CWG 1863](https://cplusplus.github.io/CWG/issues/1863.html) | C++11 | copy constructor was not required for move-onlyexception objects when thrown, but copying allowed later | copy constructor required | | [CWG 1866](https://cplusplus.github.io/CWG/issues/1866.html) | C++98 | variant members were leaked on stack unwinding from constructor | variant members destroyed | | [CWG 2176](https://cplusplus.github.io/CWG/issues/2176.html) | C++98 | throw from a local variable destructorcould skip return value destructor | function return valueadded to unwinding | ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [try-catch block](try_catch "cpp/language/try catch") * [`noexcept` specifier](noexcept_spec "cpp/language/noexcept spec") * [dynamic exception specifications](except_spec "cpp/language/except spec") cpp SFINAE SFINAE ====== "Substitution Failure Is Not An Error" This rule applies during overload resolution of function templates: When [substituting](function_template#Template_argument_substitution "cpp/language/function template") the explicitly specified or [deduced type](template_argument_deduction "cpp/language/template argument deduction") for the template parameter fails, the specialization is discarded from the [overload set](overload_resolution "cpp/language/overload resolution") instead of causing a compile error. This feature is used in template metaprogramming. ### Explanation Function template parameters are substituted (replaced by template arguments) twice: * explicitly specified template arguments are substituted before template argument deduction * deduced arguments and the arguments obtained from the defaults are substituted after template argument deduction Substitution occurs in. * all types used in the function type (which includes return type and the types of all parameters) * all types used in the template parameter declarations | | | | --- | --- | | * all expressions used in the function type * all expressions used in a template parameter declaration | (since C++11) | | | | | --- | --- | | * all expressions used in the [explicit specifier](explicit "cpp/language/explicit") | (since C++20) | A *substitution failure* is any situation when the type or expression above would be ill-formed (with a required diagnostic), if written using the substituted arguments. Only the failures in the types and expressions in the *immediate context* of the function type or its template parameter types or its [explicit specifier](explicit "cpp/language/explicit") (since C++20) are SFINAE errors. If the evaluation of a substituted type/expression causes a side-effect such as instantiation of some template specialization, generation of an implicitly-defined member function, etc, errors in those side-effects are treated as hard errors. A [lambda expression](lambda "cpp/language/lambda") is not considered part of the immediate context. (since C++20). Substitution proceeds in lexical order and stops when a failure is encountered. | | | | --- | --- | | If there are multiple declarations with different lexical orders (e.g. a function template declared with trailing return type, to be substituted after a parameter, and redeclared with ordinary return type that would be substituted before the parameter), and that would cause template instantiations to occur in a different order or not at all, then the program is ill-formed; no diagnostic required. | (since C++11) | ``` template<typename A> struct B { using type = typename A::type; }; template< class T, class U = typename T::type, // SFINAE failure if T has no member type class V = typename B<T>::type> // hard error if T has no member type // (guaranteed to not occur via CWG 1227 because // substitution into the default template argument // of U would fail first) void foo (int); template<class T> typename T::type h(typename B<T>::type); template<class T> auto h(typename B<T>::type) -> typename T::type; // redeclaration template<class T> void h(...) {} using R = decltype(h<int>(0)); // ill-formed, no diagnostic required ``` ### Type SFINAE The following type errors are SFINAE errors: | | | | --- | --- | | * attempting to instantiate a pack expansion containing multiple packs of different lengths | (since C++11) | * attempting to create an array of void, array of reference, array of function, array of negative size, array of non-integral size, or array of size zero: ``` template<int I> void div(char(*)[I % 2 == 0] = 0) { // this overload is selected when I is even } template<int I> void div(char(*)[I % 2 == 1] = 0) { // this overload is selected when I is odd } ``` * attempting to use a type on the left of a scope resolution operator `::` and it is not a class or enumeration: ``` template<class T> int f(typename T::B*); template<class T> int f(T); int i = f<int>(0); // uses second overload ``` * attempting to use a member of a type, where + the type does not contain the specified member + the specified member is not a type where a type is required + the specified member is not a template where a template is required + the specified member is not a non-type where a non-type is required ``` template<int I> struct X {}; template<template<class T> class> struct Z {}; template<class T> void f(typename T::Y*) {} template<class T> void g(X<T::N>*) {} template<class T> void h(Z<T::template TT>*) {} struct A {}; struct B { int Y; }; struct C { typedef int N; }; struct D { typedef int TT; }; struct B1 { typedef int Y; }; struct C1 { static const int N = 0; }; struct D1 { template<typename T> struct TT {}; }; int main() { // Deduction fails in each of these cases: f<A>(0); // A does not contain a member Y f<B>(0); // The Y member of B is not a type g<C>(0); // The N member of C is not a non-type h<D>(0); // The TT member of D is not a template // Deduction succeeds in each of these cases: f<B1>(0); g<C1>(0); h<D1>(0); } // todo: needs to demonstrate overload resolution, not just failure ``` * attempting to create a pointer to reference * attempting to create a reference to void * attempting to create pointer to member of T, where T is not a class type: ``` template<typename T> class is_class { typedef char yes[1]; typedef char no[2]; template<typename C> static yes& test(int C::*); // selected if C is a class type template<typename C> static no& test(...); // selected otherwise public: static bool const value = sizeof(test<T>(0)) == sizeof(yes); }; ``` * attempting to give an invalid type to a non-type template parameter: ``` template<class T, T> struct S {}; template<class T> int f(S<T, T()>*); struct X {}; int i0 = f<X>(0); // todo: needs to demonstrate overload resolution, not just failure ``` * attempting to perform an invalid conversion in + in a template argument expression + in an expression used in function declaration: ``` template<class T, T*> int f(int); int i2 = f<int,1>(0); // can’t conv 1 to int* // todo: needs to demonstrate overload resolution, not just failure ``` * attempting to create a function type with a parameter of type void * attempting to create a function type which returns an array type or a function type ### Expression SFINAE | | | | --- | --- | | Only constant expressions that are used in types (such as array bounds) were required to be treated as SFINAE (and not hard errors) before C++11. | (until C++11) | | The following expression errors are SFINAE errors.* Ill-formed expression used in a template parameter type * Ill-formed expression used in the function type: ``` struct X {}; struct Y { Y(X){} }; // X is convertible to Y template<class T> auto f(T t1, T t2) -> decltype(t1 + t2); // overload #1 X f(Y, Y); // overload #2 X x1, x2; X x3 = f(x1, x2); // deduction fails on #1 (expression x1 + x2 is ill-formed) // only #2 is in the overload set, and is called ``` | (since C++11) | ### SFINAE in partial specializations Deduction and substitution also occur while determining whether a specialization of a class or variable (since C++14) template is generated by some [partial specialization](partial_specialization "cpp/language/partial specialization") or the primary template. Compilers do not treat a substitution failure as a hard-error during such determination, but ignore the corresponding partial specialization declaration instead, as if in the overload resolution involving function templates. ``` // primary template handles non-referenceable types: template<class T, class = void> struct reference_traits { using add_lref = T; using add_rref = T; }; // specialization recognizes referenceable types: template<class T> struct reference_traits<T, std::void_t<T&>> { using add_lref = T&; using add_rref = T&&; }; template<class T> using add_lvalue_reference_t = typename reference_traits<T>::add_lref; template<class T> using add_rvalue_reference_t = typename reference_traits<T>::add_rref; ``` Notes: currently partial specialization SFINAE is not formally supported by the standard (see also [CWG issue 2054](https://cplusplus.github.io/CWG/issues/2054.html)), however, LFTS requires it works since version 2 (see also [detection idiom](https://en.cppreference.com/w/cpp/experimental/is_detected "cpp/experimental/is detected")). ### Library support | | | | --- | --- | | The standard library component `[std::enable\_if](../types/enable_if "cpp/types/enable if")` allows for creating a substitution failure in order to enable or disable particular overloads based on a condition evaluated at compile time. In addition, many [type traits](../types "cpp/types") must be implemented with SFINAE if appropriate compiler extensions are unavailable. | (since C++11) | | | | | --- | --- | | The standard library component `[std::void\_t](../types/void_t "cpp/types/void t")` is another utility metafunction that simplifies partial specialization SFINAE applications. | (since C++17) | ### Alternatives Where applicable, [tag dispatch](../iterator/iterator_tags#Example "cpp/iterator/iterator tags"), [`if constexpr`](if#Constexpr_if "cpp/language/if") (since C++17), and [concepts](constraints "cpp/language/constraints") (since C++20) are usually preferred over use of SFINAE. | | | | --- | --- | | [`static_assert`](static_assert "cpp/language/static assert") is usually preferred over SFINAE if only a conditional compile time error is wanted. | (since C++11) | ### Examples A common idiom is to use expression SFINAE on the return type, where the expression uses the comma operator, whose left subexpression is the one that is being examined (cast to void to ensure the user-defined operator comma on the returned type is not selected), and the right subexpression has the type that the function is supposed to return. ``` #include <iostream> // this overload is always in the set of overloads // ellipsis parameter has the lowest ranking for overload resolution void test(...) { std::cout << "Catch-all overload called\n"; } // this overload is added to the set of overloads if // C is a reference-to-class type and F is a pointer to member function of C template<class C, class F> auto test(C c, F f) -> decltype((void)(c.*f)(), void()) { std::cout << "Reference overload called\n"; } // this overload is added to the set of overloads if // C is a pointer-to-class type and F is a pointer to member function of C template<class C, class F> auto test(C c, F f) -> decltype((void)((c->*f)()), void()) { std::cout << "Pointer overload called\n"; } struct X { void f() {} }; int main() { X x; test(x, &X::f); test(&x, &X::f); test(42, 1337); } ``` Output: ``` Reference overload called Pointer overload called Catch-all overload called ``` ### 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 295](https://cplusplus.github.io/CWG/issues/295.html) | C++98 | creating cv-qualified function typecould result in substitution failure | made not failure,discarding cv-qualification | | [CWG 1227](https://cplusplus.github.io/CWG/issues/1227.html) | C++98 | the order of substitution was unspecified | same as the lexical order | | [CWG 2322](https://cplusplus.github.io/CWG/issues/2322.html) | C++11 | declarations in different lexical orders would cause templateinstantiations to occur in a different order or not at all | such case is ill-formed,no diagnostic required |
programming_docs
cpp Copy constructors Copy constructors ================= A copy constructor of class `T` is a non-template [constructor](initializer_list "cpp/language/initializer list") whose first parameter is `T&`‍, `const T&`‍, `volatile T&`‍, or `const volatile T&`‍, and either there are no other parameters, or the rest of the parameters all have default values. ### Syntax | | | | | --- | --- | --- | | class-name ( `const` class-name `&` ) | (1) | | | class-name ( `const` class-name `&` ) = `default;` | (2) | (since C++11) | | class-name ( `const` class-name `&` ) = `delete;` | (3) | (since C++11) | Where class-name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name. ### Explanation 1) Typical declaration of a copy constructor. 2) Forcing a copy constructor to be generated by the compiler. 3) Avoiding implicit generation of the copy constructor. The copy constructor is called whenever an object is [initialized](initialization "cpp/language/initialization") (by [direct-initialization](direct_initialization "cpp/language/direct initialization") or [copy-initialization](copy_initialization "cpp/language/copy initialization")) from another object of the same type (unless [overload resolution](overload_resolution "cpp/language/overload resolution") selects a better match or the call is [elided](copy_elision "cpp/language/copy elision")), which includes. * initialization: `T a = b;` or `T a(b);`, where b is of type `T`; * function argument passing: `f(a);`, where `a` is of type `T` and `f` is `void f(T t)`; * function return: `return a;` inside a function such as `T f()`, where `a` is of type `T`, which has no [move constructor](move_constructor "cpp/language/move constructor"). ### Implicitly-declared copy constructor If no user-defined copy constructors are provided for a class type (`struct`, `class`, or `union`), the compiler will always declare a copy constructor as a non-[explicit](explicit "cpp/language/explicit") `inline public` member of its class. This implicitly-declared copy constructor has the form `T::T(const T&)` if all of the following are true: * each direct and virtual base `B` of `T` has a copy constructor whose parameters are `const B&` or `const volatile B&`; * each non-static data member `M` of `T` of class type or array of class type has a copy constructor whose parameters are `const M&` or `const volatile M&`. Otherwise, the implicitly-declared copy constructor is `T::T(T&)`. (Note that due to these rules, the implicitly-declared copy constructor cannot bind to a volatile lvalue argument.). A class can have multiple copy constructors, e.g. both `T::T(const T&)` and `T::T(T&)`. | | | | --- | --- | | If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword `default`. | (since C++11) | The implicitly-declared (or defaulted on its first declaration) copy constructor has an exception specification as described in [dynamic exception specification](except_spec "cpp/language/except spec") (until C++17)[noexcept specification](noexcept_spec "cpp/language/noexcept spec") (since C++17). ### Deleted implicitly-declared copy constructor | | | | --- | --- | | The implicitly-declared copy constructor for class `T` is undefined if any of the following conditions are true: | (until C++11) | | The implicitly-declared or defaulted copy constructor for class `T` is defined as *deleted* if any of the following conditions are true: | (since C++11) | * `T` has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors); * `T` has direct or virtual base class that cannot be copied (has deleted, inaccessible, or ambiguous copy constructors); * `T` has direct or virtual base class or a non-static data member with a deleted or inaccessible destructor; | | | | --- | --- | | * `T` is a union-like class and has a variant member with non-trivial copy constructor; * `T` has a data member of rvalue reference type; * `T` has a user-defined [move constructor](move_constructor "cpp/language/move constructor") or [move assignment operator](move_assignment "cpp/language/move assignment") (this condition only causes the implicitly-declared, not the defaulted, copy constructor to be deleted). | (since C++11) | ### Trivial copy constructor The copy constructor for class `T` is trivial if all of the following are true: * it is not user-provided (that is, it is implicitly-defined or defaulted) ; * `T` has no virtual member functions; * `T` has no virtual base classes; * the copy constructor selected for every direct base of `T` is trivial; * the copy constructor selected for every non-static class type (or array of class type) member of `T` is trivial; A trivial copy constructor for a non-union class effectively copies every scalar subobject (including, recursively, subobject of subobjects and so forth) of the argument and performs no other action. However, padding bytes need not be copied, and even the object representations of the copied subobjects need not be the same as long as their values are identical. [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") objects can be copied by copying their object representations manually, e.g. with `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`. All data types compatible with the C language (POD types) are trivially copyable. ### Eligible copy constructor | | | | --- | --- | | A copy constructor is eligible if it is either user-declared or both implicitly-declared and definable. | (until C++11) | | A copy constructor is eligible if it is not deleted. | (since C++11)(until C++20) | | A copy constructor is eligible if.* it is not deleted, and * its [associated constraints](constraints "cpp/language/constraints"), if any, are satisfied, and * no copy constructor with the same first parameter type is [more constrained](constraints#Partial_ordering_of_constraints "cpp/language/constraints") than it. | (since C++20) | Triviality of eligible copy constructors determines whether the class is an [implicit-lifetime type](lifetime#Implicit-lifetime_types "cpp/language/lifetime"), and whether the class is a [trivially copyable type](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Implicitly-defined copy constructor If the implicitly-declared copy constructor is not deleted, it is defined (that is, a function body is generated and compiled) by the compiler if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") (since C++11). For union types, the implicitly-defined copy constructor copies the object representation (as by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`). For non-union class types (`class` and `struct`), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization. If this satisfies the requirements of a [constexpr constructor](constexpr "cpp/language/constexpr"), the generated copy constructor is `constexpr`. (since C++11). | | | | --- | --- | | The generation of the implicitly-defined copy constructor is deprecated if `T` has a user-defined destructor or user-defined copy assignment operator. | (since C++11) | ### Notes In many situations, copy constructors are optimized out even if they would produce observable side-effects, see [copy elision](copy_elision "cpp/language/copy elision"). ### Example ``` struct A { int n; A(int n = 1) : n(n) { } A(const A& a) : n(a.n) { } // user-defined copy ctor }; struct B : A { // implicit default ctor B::B() // implicit copy ctor B::B(const B&) }; struct C : B { C() : B() { } private: C(const C&); // non-copyable, C++98 style }; int main() { A a1(7); A a2(a1); // calls the copy ctor B b; B b2 = b; A a3 = b; // conversion to A& and copy ctor volatile A va(10); // A a4 = va; // compile error C c; // C c2 = c; // compile error } ``` ### 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 2094](https://cplusplus.github.io/CWG/issues/2094.html) | C++11 | volatile members make copy non-trivial ([CWG 496](https://cplusplus.github.io/CWG/issues/496.html)) | triviality not affected | | [CWG 2171](https://cplusplus.github.io/CWG/issues/2171.html) | C++11 | `X(X&) = default` was non-trivial | made trivial | ### See also * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new") cpp dynamic_cast conversion `dynamic_cast` conversion ========================== Safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy. ### Syntax | | | | | --- | --- | --- | | `dynamic_cast` `<` new-type `>` `(` expression `)` | | | | | | | | --- | --- | --- | | new-type | - | pointer to complete class type, reference to complete class type, or pointer to (optionally cv-qualified) void | | expression | - | lvalue (until C++11)glvalue (since C++11) of a complete class type if new-type is a reference, prvalue of a pointer to complete class type if new-type is a pointer. | If the cast is successful, `dynamic_cast` returns a value of type new-type. If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type `[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")`. ### Explanation Only the following conversions can be done with `dynamic_cast`, except when such conversions would cast away *constness* or *volatility*. 1) If the type of expression is exactly new-type or a less cv-qualified version of new-type, the result is the value of expression, with type new-type. (In other words, `dynamic_cast` can be used to add constness. An implicit conversion and `static_cast` can perform this conversion as well.) 2) If the value of expression is the null pointer value, the result is the null pointer value of type new-type. 3) If new-type is a pointer or reference to `Base`, and the type of expression is a pointer or reference to `Derived`, where `Base` is a unique, accessible base class of `Derived`, the result is a pointer or reference to the `Base` class subobject within the `Derived` object pointed or identified by expression. (Note: an implicit conversion and `static_cast` can perform this conversion as well.) 4) If expression is a pointer to a [polymorphic type](object#Polymorphic_objects "cpp/language/object"), and new-type is a pointer to `void`, the result is a pointer to the most derived object pointed or referenced by expression. 5) If expression is a pointer or reference to a [polymorphic type](object#Polymorphic_objects "cpp/language/object") `Base`, and new-type is a pointer or reference to the type `Derived` a runtime check is performed: a) The most derived object pointed/identified by expression is examined. If, in that object, expression points/refers to a public base of `Derived`, and if only one object of `Derived` type is derived from the subobject pointed/identified by expression, then the result of the cast points/refers to that `Derived` object. (This is known as a "downcast".) b) Otherwise, if expression points/refers to a public base of the most derived object, and, simultaneously, the most derived object has an unambiguous public base class of type `Derived`, the result of the cast points/refers to that `Derived` (This is known as a "sidecast".) c) Otherwise, the runtime check fails. If the `dynamic_cast` is used on pointers, the null pointer value of type new-type is returned. If it was used on references, the exception `[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")` is thrown. 6) When `dynamic_cast` is used in a constructor or a destructor (directly or indirectly), and expression refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If new-type is not a pointer or reference to the constructor's/destructor's own class or one of its bases, the behavior is undefined. Similar to other cast expressions, the result is: | | | | --- | --- | | * an lvalue if new-type is a reference type * an rvalue if new-type is a pointer type | (until C++11) | | * an lvalue if new-type is an lvalue reference type (expression must be an lvalue) * an xvalue if new-type is an rvalue reference type (expression may be lvalue or rvalue (until C++17)must be a glvalue (prvalues are [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion")) (since C++17) of a complete class type) * a prvalue if new-type is a pointer type | (since C++11) | ### Notes * A downcast can also be performed with `static_cast`, which avoids the cost of the runtime check, but it's only safe if the program can guarantee (through some other logic) that the object pointed to by expression is definitely `Derived`. * Some forms of `dynamic_cast` rely on [runtime type identification](https://en.wikipedia.org/wiki/Run-time_type_information "enwiki:Run-time type information") (RTTI), that is, information about each polymorphic class in the compiled program. Compilers typically have options to disable the inclusion of this information. ### Keywords [`dynamic_cast`](../keyword/dynamic_cast "cpp/keyword/dynamic cast"). ### Example ``` #include <iostream> struct V { virtual void f() {} // must be polymorphic to use runtime-checked dynamic_cast }; struct A : virtual V {}; struct B : virtual V { B(V* v, A* a) { // casts during construction (see the call in the constructor of D below) dynamic_cast<B*>(v); // well-defined: v of type V*, V base of B, results in B* dynamic_cast<B*>(a); // undefined behavior: a has type A*, A not a base of B } }; struct D : A, B { D() : B(static_cast<A*>(this), this) {} }; struct Base { virtual ~Base() {} }; struct Derived: Base { virtual void name() {} }; int main() { D d; // the most derived object A& a = d; // upcast, dynamic_cast may be used, but unnecessary [[maybe_unused]] D& new_d = dynamic_cast<D&>(a); // downcast [[maybe_unused]] B& new_b = dynamic_cast<B&>(a); // sidecast Base* b1 = new Base; if (Derived* d = dynamic_cast<Derived*>(b1); d != nullptr) { std::cout << "downcast from b1 to d successful\n"; d->name(); // safe to call } Base* b2 = new Derived; if (Derived* d = dynamic_cast<Derived*>(b2); d != nullptr) { std::cout << "downcast from b2 to d successful\n"; d->name(); // safe to call } delete b1; delete b2; } ``` Output: ``` downcast from b2 to d successful ``` ### 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 1269](https://cplusplus.github.io/CWG/issues/1269.html) | C++11 | the runtime check was not performed for xvalueexpressions if new-type is a rvalue reference type | performed | ### See also * [`const_cast`](const_cast "cpp/language/const cast") * [`static_cast`](static_cast "cpp/language/static cast") * [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") * [explicit cast](explicit_cast "cpp/language/explicit cast") * [implicit conversions](implicit_conversion "cpp/language/implicit conversion") cpp Copy assignment operator Copy assignment operator ======================== A copy assignment operator of class `T` is a non-template [non-static member function](member_functions "cpp/language/member functions") with the name `operator=` that takes exactly one parameter of type `T`, `T&`, `const T&`, `volatile T&`, or `const volatile T&`. For a type to be [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), it must have a public copy assignment operator. ### Syntax | | | | | --- | --- | --- | | class-name `&` class-name `::` `operator=` ( class-name ) | (1) | | | class-name `&` class-name `::` `operator=` ( `const` class-name `&` ) | (2) | | | class-name `&` class-name `::` `operator=` ( `const` class-name `&` ) = `default;` | (3) | (since C++11) | | class-name `&` class-name `::` `operator=` ( `const` class-name `&` ) = `delete;` | (4) | (since C++11) | ### Explanation 1) Typical declaration of a copy assignment operator when [copy-and-swap idiom](operators#Assignment_operator "cpp/language/operators") is used. 2) Typical declaration of a copy assignment operator when copy-and-swap idiom is not used. 3) Forcing a copy assignment operator to be generated by the compiler. 4) Avoiding implicit copy assignment. The copy assignment operator is called whenever selected by [overload resolution](overload_resolution "cpp/language/overload resolution"), e.g. when an object appears on the left side of an assignment expression. ### Implicitly-declared copy assignment operator If no user-defined copy assignment operators are provided for a class type (`struct`, `class`, or `union`), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form `T& T::operator=(const T&)` if all of the following is true: * each direct base `B` of `T` has a copy assignment operator whose parameters are `B` or `const B&` or `const volatile B&`; * each non-static data member `M` of `T` of class type or array of class type has a copy assignment operator whose parameters are `M` or `const M&` or `const volatile M&`. Otherwise the implicitly-declared copy assignment operator is declared as `T& T::operator=(T&)`. (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.). A class can have multiple copy assignment operators, e.g. both `T& T::operator=(T&)` and `T& T::operator=(T)`. If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword `default`. (since C++11). The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in [dynamic exception specification](except_spec "cpp/language/except spec") (until C++17)[noexcept specification](noexcept_spec "cpp/language/noexcept spec") (since C++17). Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a [using-declaration](using_declaration#In_class_definition "cpp/language/using declaration") is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration. ### Deleted implicitly-declared copy assignment operator An implicitly-declared copy assignment operator for class `T` is defined as *deleted* if any of the following is true: * `T` has a user-declared move constructor; * `T` has a user-declared move assignment operator. Otherwise, it is defined as defaulted. A defaulted copy assignment operator for class `T` is defined as *deleted* if any of the following is true: * `T` has a non-static data member of non-class type (or array thereof) that is `const`; * `T` has a non-static data member of a reference type; * `T` has a non-static data member or a direct base class that cannot be copy-assigned (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function); * `T` is a [union-like class](union#Union-like_classes "cpp/language/union"), and has a variant member whose corresponding assignment operator is non-trivial. ### Trivial copy assignment operator The copy assignment operator for class `T` is trivial if all of the following is true: * it is not user-provided (meaning, it is implicitly-defined or defaulted); * `T` has no virtual member functions; * `T` has no virtual base classes; * the copy assignment operator selected for every direct base of `T` is trivial; * the copy assignment operator selected for every non-static class type (or array of class type) member of `T` is trivial. A trivial copy assignment operator makes a copy of the object representation as if by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`. All data types compatible with the C language (POD types) are trivially copy-assignable. ### Eligible copy assignment operator | | | | --- | --- | | A copy assignment operator is eligible if it is either user-declared or both implicitly-declared and definable. | (until C++11) | | A copy assignment operator is eligible if it is not deleted. | (since C++11)(until C++20) | | A copy assignment operator is eligible if.* it is not deleted, and * its [associated constraints](constraints "cpp/language/constraints"), if any, are satisfied, and * no copy assignment operator with the same first parameter type and the same cv/ref-qualifiers (if any) is [more constrained](constraints#Partial_ordering_of_constraints "cpp/language/constraints") than it. | (since C++20) | Triviality of eligible copy assignment operators determines whether the class is a [trivially copyable type](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Implicitly-defined copy assignment operator If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") (since C++14). For union types, the implicitly-defined copy assignment copies the object representation (as by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`). For non-union class types (`class` and `struct`), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types. | | | | --- | --- | | The implicitly-defined copy assignment operator for a class `T` is [`constexpr`](constexpr "cpp/language/constexpr") if.* `T` is a [literal type](../named_req/literaltype "cpp/named req/LiteralType"), and * the assignment operator selected to copy each direct base class subobject is a constexpr function, and * for each non-static data member of `T` that is of class type (or array thereof), the assignment operator selected to copy that member is a constexpr function. | (since C++14) | | | | | --- | --- | | The generation of the implicitly-defined copy assignment operator is deprecated if `T` has a user-declared destructor or user-declared copy constructor. | (since C++11) | ### Notes If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an [*rvalue*](value_category "cpp/language/value category") (either a [*prvalue*](value_category "cpp/language/value category") such as a nameless temporary or an [*xvalue*](value_category "cpp/language/value category") such as the result of `std::move`), and selects the copy assignment if the argument is an [*lvalue*](value_category "cpp/language/value category") (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable. It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to [move assignment](move_assignment "cpp/language/move assignment")). See [assignment operator overloading](operators#Assignment_operator "cpp/language/operators") for additional detail on the expected behavior of a user-defined copy-assignment operator. ### Example ``` #include <iostream> #include <memory> #include <string> #include <algorithm> struct A { int n; std::string s1; A() = default; A(A const&) = default; // user-defined copy assignment (copy-and-swap idiom) A& operator=(A other) { std::cout << "copy assignment of A\n"; std::swap(n, other.n); std::swap(s1, other.s1); return *this; } }; struct B : A { std::string s2; // implicitly-defined copy assignment }; struct C { std::unique_ptr<int[]> data; std::size_t size; // user-defined copy assignment (non copy-and-swap idiom) // note: copy-and-swap would always reallocate resources C& operator=(const C& other) { if (this != &other) // not a self-assignment { if (size != other.size) // resource cannot be reused { data.reset(new int[other.size]); size = other.size; } std::copy(&other.data[0], &other.data[0] + size, &data[0]); } return *this; } }; int main() { A a1, a2; std::cout << "a1 = a2 calls "; a1 = a2; // user-defined copy assignment B b1, b2; b2.s1 = "foo"; b2.s2 = "bar"; std::cout << "b1 = b2 calls "; b1 = b2; // implicitly-defined copy assignment std::cout << "b1.s1 = " << b1.s1 << "; b1.s2 = " << b1.s2 << '\n'; } ``` Output: ``` a1 = a2 calls copy assignment of A b1 = b2 calls copy assignment of A b1.s1 = foo; b1.s2 = 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 | | --- | --- | --- | --- | | [CWG 2094](https://cplusplus.github.io/CWG/issues/2094.html) | C++11 | a volatile subobject made defaulted copyassignment operators non-trivial ([CWG issue 496](https://cplusplus.github.io/CWG/issues/496.html)) | triviality not affected | | [CWG 2171](https://cplusplus.github.io/CWG/issues/2171.html) | C++11 | `operator=(X&) = default` was non-trivial | made trivial | | [CWG 2180](https://cplusplus.github.io/CWG/issues/2180.html) | C++11 | a defaulted copy assignment operator for class `T` was not defined as deletedif `T` is abstract and has non-copy-assignable direct virtual base classes | the operator is definedas deleted in this case | ### See also * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new")
programming_docs
cpp noexcept specifier (since C++11) noexcept specifier (since C++11) ================================ Specifies whether a function could throw exceptions. ### Syntax | | | | | --- | --- | --- | | `noexcept` | (1) | | | `noexcept(`expression`)` | (2) | | | `throw()` | (3) | (since C++17)(deprecated in C++17)(removed in C++20) | 1) Same as `noexcept(true)` 2) If expression evaluates to `true`, the function is declared not to throw any exceptions. A `(` following `noexcept` is always a part of this form (it can never start an initializer). 3) Same as `noexcept(true)` (see [dynamic exception specification](except_spec "cpp/language/except spec") for its semantics before C++17) | | | | | --- | --- | --- | | expression | - | [contextually converted constant expression of type `bool`](constant_expression#Converted_constant_expression "cpp/language/constant expression") | ### Explanation | | | | --- | --- | | The noexcept-specification is not a part of the function type (just like [dynamic exception specification](except_spec "cpp/language/except spec")) and can only appear as a part of a [lambda declarator](lambda "cpp/language/lambda") or a top-level [function declarator](function "cpp/language/function") when declaring functions, variables, non-static data members of type function, pointer to function, reference to function, or pointer to member function, and also when declaring a parameter or a return type in one of those declarations that in turn happens to be a pointer or reference to function. It cannot appear in a [typedef](typedef "cpp/language/typedef") or [type alias](type_alias "cpp/language/type alias") declaration. ``` void f() noexcept; // the function f() does not throw void (*fp)() noexcept(false); // fp points to a function that may throw void g(void pfa() noexcept); // g takes a pointer to function that doesn't throw // typedef int (*pf)() noexcept; // error ``` | (until C++17) | | The noexcept-specification is a part of the function type and may appear as part of any [function declarator](function "cpp/language/function"). | (since C++17) | Every function in C++ is either *non-throwing* or *potentially throwing*: * *potentially-throwing* functions are: | | | | --- | --- | | * functions declared with a non-empty [dynamic exception specification](except_spec "cpp/language/except spec") | (until C++17) | * functions declared with `noexcept` specifier whose expression evaluates to `false` * functions declared without `noexcept` specifier except for * [destructors](destructor "cpp/language/destructor") unless the destructor of any potentially-constructed base or member is *potentially-throwing* (see below) * [default constructors](default_constructor "cpp/language/default constructor"), [copy constructors](copy_constructor "cpp/language/copy constructor"), [move constructors](move_constructor "cpp/language/move constructor") that are implicitly-declared or defaulted on their first declaration unless + a constructor for a base or member that the implicit definition of the constructor would call is *potentially-throwing* (see below) + a subexpression of such an initialization, such as a default argument expression, is *potentially-throwing* (see below) + a default member initializer (for default constructor only) is *potentially-throwing* (see below) * [copy assignment](copy_assignment "cpp/language/copy assignment") operators, [move assignment](move_assignment "cpp/language/move assignment") operators that are implicitly-declared or defaulted on their first declaration unless the invocation of any assignment operator in the implicit definition is *potentially-throwing* (see below) | | | | --- | --- | | * [comparison operators](default_comparisons "cpp/language/default comparisons") that are defaulted on their first declaration unless the invocation of any comparison operator in the implicit definition is *potentially-throwing* (see below) | (since C++20) | * [deallocation functions](../memory/new/operator_delete "cpp/memory/new/operator delete") * non-throwing functions are all others (those with noexcept specifier whose expression evaluates to `true` as well as destructors, defaulted special member functions, and deallocation functions) [Explicit instantiations](function_template#Explicit_instantiation "cpp/language/function template") may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations. A diagnostic is required only if the exception specifications are not the same within a single translation unit. Functions differing only in their exception specification cannot be overloaded (just like the return type, exception specification is part of function type, but not part of the function signature) (since C++17). ``` void f() noexcept; void f(); // error: different exception specification void g() noexcept(false); void g(); // ok, both declarations for g are potentially-throwing ``` Pointers (including pointers to member function) to non-throwing functions can be assigned to or used to initialize (until C++17)are [implicitly convertible](implicit_conversion#Function_pointer_conversions "cpp/language/implicit conversion") to (since C++17) pointers to potentially-throwing functions, but not the other way around. ``` void ft(); // potentially-throwing void (*fn)() noexcept = ft; // error ``` If a virtual function is non-throwing, all declarations, including the definition, of every overrider must be non-throwing as well, unless the overrider is defined as deleted: ``` struct B { virtual void f() noexcept; virtual void g(); virtual void h() noexcept = delete; }; struct D: B { void f(); // ill-formed: D::f is potentially-throwing, B::f is non-throwing void g() noexcept; // OK void h() = delete; // OK }; ``` Non-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function `[std::terminate](../error/terminate "cpp/error/terminate")` is called: ``` extern void f(); // potentially-throwing void g() noexcept { f(); // valid, even if f throws throw 42; // valid, effectively a call to std::terminate } ``` | | | | --- | --- | | The exception specification of a function template specialization is not instantiated along with the function declaration; it is instantiated only when *needed* (as defined below). The exception-specification of an implicitly-declared special member function is also evaluated only when needed (in particular, implicit declaration of a member function of a derived class does not require the exception-specification of a base member function to be instantiated). When the noexcept-specification of a function template specialization is *needed*, but hasn't yet been instantiated, the dependent names are looked up and any templates used in the expression are instantiated as if for the declaration of the specialization. A noexcept-specification of a function is considered to be *needed* in the following contexts:* in an expression, where the function is selected by overload resolution * the function is [odr-used](definition#ODR-use "cpp/language/definition") * the function would be odr-used but appears in an unevaluated operand ``` template<class T> T f() noexcept(sizeof(T) < 4); int main() { decltype(f<void>()) *p; // f unevaluated, but noexcept-spec is needed // error because instantiation of the noexcept specification // calculates sizeof(void) } ``` * the specification is needed to compare to another function declaration (e.g. on an virtual function overrider or on an explicit specialization of a function template) * in a function definition * the specification is needed because a defaulted special member function needs to check it in order to decide its own exception specification (this takes place only when the specification of the defaulted special member function is, itself, needed). | (since C++14) | Formal definition of *potentially-throwing expression* (used to determine the default exception specification of destructors, constructors, and assignment operators as described above): An expression `e` is *potentially-throwing* if: * `e` is a function call to a function, pointer to function, or pointer to member function which is *potentially-throwing*, unless `e` is a [core constant expression](constant_expression "cpp/language/constant expression") (until C++17) * `e` makes an implicit call to a *potentially-throwing* function (such as an overloaded operator, an allocation function in a `new`-expression, a constructor for a function argument, or a destructor if `e` is a full-expression) * `e` is a [`throw`-expression](throw "cpp/language/throw") * `e` is a [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") that casts a polymorphic reference type * `e` is a [`typeid`](typeid "cpp/language/typeid") expression applied to a dereferenced pointer to a polymorphic type * `e` has an immediate subexpression that is potentially-throwing ``` struct A { A(int = (A(5), 0)) noexcept; A(const A&) noexcept; A(A&&) noexcept; ~A(); }; struct B { B() throw(); B(const B&) = default; // implicit exception specification is noexcept(true) B(B&&, int = (throw Y(), 0)) noexcept; ~B() noexcept(false); }; int n = 7; struct D : public A, public B { int * p = new int[n]; // D::D() potentially-throwing because of the new operator // D::D(const D&) non-throwing // D::D(D&&) potentially-throwing: the default argument for B’s constructor may throw // D::~D() potentially-throwing // note; if A::~A() were virtual, this program would be ill-formed because an overrider // of a non-throwing virtual cannot be potentially-throwing }; ``` ### Notes One of the uses of the constant expression is (along with the [`noexcept` operator](noexcept "cpp/language/noexcept")) to define function templates that declare `noexcept` for some types but not others. Note that a `noexcept` specification on a function is not a compile-time check; it is merely a method for a programmer to inform the compiler whether or not a function should throw exceptions. The compiler can use this information to enable certain optimizations on non-throwing functions as well as enable the [`noexcept` operator](noexcept "cpp/language/noexcept"), which can check at compile time if a particular expression is declared to throw any exceptions. For example, containers such as `[std::vector](../container/vector "cpp/container/vector")` will move their elements if the elements' move constructor is `noexcept`, and copy otherwise (unless the copy constructor is not accessible, but a potentially throwing move constructor is, in which case the strong exception guarantee is waived). #### Deprecates `noexcept` is an improved version of [`throw()`](except_spec "cpp/language/except spec"), which is deprecated in C++11. Unlike pre-C++17 [`throw()`](except_spec "cpp/language/except spec"), `noexcept` will not call `[std::unexpected](../error/unexpected "cpp/error/unexpected")`, may or may not unwind the stack, and will call `[std::terminate](../error/terminate "cpp/error/terminate")`, which potentially allows the compiler to implement `noexcept` without the runtime overhead of [`throw()`](except_spec "cpp/language/except spec"). As of C++17, `throw()` is redefined to be an exact equivalent of `noexcept(true)`. ### Keywords [`noexcept`](../keyword/noexcept "cpp/keyword/noexcept"). ### Example ``` // whether foo is declared noexcept depends on if the expression // T() will throw any exceptions template<class T> void foo() noexcept(noexcept(T())) {} void bar() noexcept(true) {} void baz() noexcept { throw 42; } // noexcept is the same as noexcept(true) int main() { foo<int>(); // noexcept(noexcept(int())) => noexcept(true), so this is fine bar(); // fine baz(); // compiles, but at runtime this calls std::terminate } ``` ### 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 1740](https://cplusplus.github.io/CWG/issues/1740.html) | C++11 | a `(` following `noexcept` might start an initializer | it can only be a part ofnoexcept specification | | [CWG 2039](https://cplusplus.github.io/CWG/issues/2039.html) | C++11 | only the expression before conversion is required to be constant | the conversion must also bevalid in a constant expression | ### See also | | | | --- | --- | | [`noexcept` operator](noexcept "cpp/language/noexcept")(C++11) | determines if an expression throws any exceptions | | [Dynamic exception specification](except_spec "cpp/language/except spec")(until C++17) | specifies what exceptions are thrown by a function (deprecated in C++11) | | [`throw` expression](throw "cpp/language/throw") | signals an error and transfers control to error handler | | [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 Template parameters and template arguments Template parameters and template arguments ========================================== ### Template parameters Every [template](templates "cpp/language/templates") is parameterized by one or more template parameters, indicated in the parameter-list of the template declaration syntax: | | | | | --- | --- | --- | | `template` `<` parameter-list `>` declaration | | | Each parameter in parameter-list may be: * a non-type template parameter; * a type template parameter; * a template template parameter. #### Non-type template parameter | | | | | --- | --- | --- | | type name(optional) | (1) | | | type name(optional) `=` default | (2) | | | type `...` name(optional) | (3) | (since C++11) | | placeholder name | (4) | (since C++17) | 1) A non-type template parameter with an optional name. 2) A non-type template parameter with an optional name and a default value. 3) A non-type template [parameter pack](parameter_pack "cpp/language/parameter pack") with an optional name. 4) A non-type template parameter with a placeholder type. placeholder may be any type that includes the placeholder [`auto`](auto "cpp/language/auto") (such as plain `auto`, `auto **` or `auto &`), a [placeholder for a deduced class type](class_template_argument_deduction "cpp/language/class template argument deduction") (since C++20), or `decltype(auto)`. A non-type template parameter must have a *structural type*, which is one of the following types (optionally cv-qualified, the qualifiers are ignored): * [lvalue reference type](reference#lvalue_references "cpp/language/reference") (to object or to function); * an [integral type](type "cpp/language/type"); * a [pointer type](pointer "cpp/language/pointer") (to object or to function); * a [pointer to member type](pointer#Pointers_to_members "cpp/language/pointer") (to member object or to member function); * an [enumeration type](enum "cpp/language/enum"); | | | | --- | --- | | * `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`; | (since C++11) | | | | | --- | --- | | * a [floating-point type](type "cpp/language/type"); * a [literal class type](../named_req/literaltype "cpp/named req/LiteralType") with the following properties: + all base classes and non-static data members are public and non-mutable and + the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof. | (since C++20) | Array and function types may be written in a template declaration, but they are automatically replaced by pointer to object and pointer to function as appropriate. When the name of a non-type template parameter is used in an expression within the body of the class template, it is an unmodifiable [prvalue](value_category "cpp/language/value category") unless its type was an lvalue reference type, or unless its type is a class type (since C++20). A template parameter of the form `class Foo` is not an unnamed non-type template parameter of type `Foo`, even if otherwise `class Foo` is an [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") and `class Foo x;` declares `x` to be of type `Foo`. | | | | --- | --- | | The type of a non-type template parameter may be deduced if it includes a placeholder type (`auto`, a placeholder for a deduced class type (since C++20), or `decltype(auto)`). The deduction is performed as if by deducing the type of the variable `x` in the invented declaration `T x = template-argument;`, where `T` is the declared type of the template parameter. If the deduced type is not permitted for a non-type template parameter, the program is ill-formed. ``` template<auto n> struct B { /* ... */ }; B<5> b1; // OK: non-type template parameter type is int B<'a'> b2; // OK: non-type template parameter type is char B<2.5> b3; // error (until C++20): non-type template parameter type cannot be double // C++20 deduced class type placeholder, class template arguments are deduced at the call site template<std::array arr> void f(); f<std::array<double, 8>{}>(); ``` For non-type template parameter packs whose type uses a placeholder type, the type is independently deduced for each template argument and need not match: ``` template<auto...> struct C {}; C<'C', 0, 2L, nullptr> x; // OK ``` | (since C++17) | | | | | --- | --- | | An [identifier](identifiers "cpp/language/identifiers") that names a non-type template parameter of class type `T` denotes a static storage duration object of type `const T`, called a *template parameter object*, whose value is that of the corresponding template argument after it has been converted to the type of the template parameter. All such template parameters in the program of the same type with the same value denote the same template parameter object. A template parameter object shall have [constant destruction](constexpr#Constant_destruction "cpp/language/constexpr"). ``` struct A { friend bool operator==(const A&, const A&) = default; }; template<A a> void f() { &a; // OK const A& ra = a, &rb = a; // Both bound to the same template parameter object assert(&ra == &rb); // passes } ``` | (since C++20) | #### Type template parameter | | | | | --- | --- | --- | | type-parameter-key name(optional) | (1) | | | type-parameter-key name(optional) `=` default | (2) | | | type-parameter-key `...` name(optional) | (3) | (since C++11) | | type-constraint name(optional) | (4) | (since C++20) | | type-constraint name(optional) `=` default | (5) | (since C++20) | | type-constraint `...` name(optional) | (6) | (since C++20) | | | | | | --- | --- | --- | | type-parameter-key | - | either `typename` or `class`. There is no difference between these keywords in a type template parameter declaration | | type-constraint | - | either the name of a [concept](constraints "cpp/language/constraints") or the name of a concept followed by a list of template arguments (in angle brackets). Either way, the concept name may be optionally qualified | 1) A type template parameter without a default. ``` template<class T> class My_vector { /* ... */ }; ``` 2) A type template parameter with a default. ``` template<class T = void> struct My_op_functor { /* ... */ }; ``` 3) A type template [parameter pack](parameter_pack "cpp/language/parameter pack"). ``` template<typename... Ts> class My_tuple { /* ... */ }; ``` 4) A constrained type template parameter without a default. ``` template<My_concept T> class My_constrained_vector { /* ... */ }; ``` 5) A constrained type template parameter with a default. ``` template<My_concept T = void> class My_constrained_op_functor { /* ... */ }; ``` 6) A constrained type template [parameter pack](parameter_pack "cpp/language/parameter pack"). ``` template<My_concept... Ts> class My_constrained_tuple { /* ... */ }; ``` The name of the parameter is optional: ``` // Declarations of the templates shown above: template<class> class My_vector; template<class = void> struct My_op_functor; template<typename...> class My_tuple; ``` In the body of the template declaration, the name of a type parameter is a typedef-name which aliases the type supplied when the template is instantiated. | | | | --- | --- | | Each constrained parameter `P` whose type-constraint is Q designating the concept `C` introduces a [constraint-expression](constraints "cpp/language/constraints") `E` according to the following rules:* if `Q` is `C` (without an argument list), + if `P` is not a parameter pack, `E` is simply `C<P>` + otherwise, `P` is a parameter pack, `E` is a fold-expression `(C<P> && ...)` * if `Q` is `C<A1,A2...,AN>`, then `E` is `C<P,A1,A2,...AN>` or `(C<P,A1,A2,...AN> && ...)`, respectively. ``` template<typename T> concept C1 = true; template<typename... Ts> // variadic concept concept C2 = true; template<typename T, typename U> concept C3 = true; template<C1 T> struct s1; // constraint-expression is C1<T> template<C1... T> struct s2; // constraint-expression is (C1<T> && ...) template<C2... T> struct s3; // constraint-expression is (C2<T> && ...) template<C3<int> T> struct s4; // constraint-expression is C3<T, int> template<C3<int>... T> struct s5; // constraint-expression is (C3<T, int> && ...) ``` | (since C++20) | #### Template template parameter | | | | | --- | --- | --- | | `template` `<` parameter-list `>` type-parameter-key name(optional) | (1) | | | `template` `<` parameter-list `>` type-parameter-key name(optional) `=` default | (2) | | | `template` `<` parameter-list `>` type-parameter-key `...` name(optional) | (3) | (since C++11) | | | | | | --- | --- | --- | | type-parameter-key | - | `class` or `typename` (since C++17) | 1) A template template parameter with an optional name. 2) A template template parameter with an optional name and a default. 3) A template template [parameter pack](parameter_pack "cpp/language/parameter pack") with an optional name. In the body of the template declaration, the name of this parameter is a template-name (and needs arguments to be instantiated). ``` template<typename T> class my_array {}; // two type template parameters and one template template parameter: template<typename K, typename V, template<typename> typename C = my_array> class Map { C<K> key; C<V> value; }; ``` #### Name resolution for template parameters The name of a template parameter is not allowed to be redeclared within its scope (including nested scopes). A template parameter is not allowed to have the same name as the template name. ``` template<class T, int N> class Y { int T; // error: template parameter redeclared void f() { char T; // error: template parameter redeclared } }; template<class X> class X; // error: template parameter redeclared ``` In the definition of a member of a class template that appears outside of the class template definition, the name of a member of the class template hides the name of a template parameter of any enclosing class templates, but not a template parameter of the member if the member is a class or function template. ``` template<class T> struct A { struct B {}; typedef void C; void f(); template<class U> void g(U); }; template<class B> void A<B>::f() { B b; // A's B, not the template parameter } template<class B> template<class C> void A<B>::g(C) { B b; // A's B, not the template parameter C c; // the template parameter C, not A's C } ``` In the definition of a member of a class template that appears outside of the namespace containing the class template definition, the name of a template parameter hides the name of a member of this namespace. ``` namespace N { class C {}; template<class T> class B { void f(T); }; } template<class C> void N::B<C>::f(C) { C b; // C is the template parameter, not N::C } ``` In the definition of a class template or in the definition of a member of such a template that appears outside of the template definition, for each non-[dependent](dependent_name#Dependent_types "cpp/language/dependent name") base class, if the name of the base class or the name of a member of the base class is the same as the name of a template parameter, the base class name or member name hides the template parameter name. ``` struct A { struct B {}; int C; int Y; }; template<class B, class C> struct X : A { B b; // A's B C b; // error: A's C isn't a type name }; ``` ### Template arguments In order for a template to be instantiated, every template parameter (type, non-type, or template) must be replaced by a corresponding template argument. For [class templates](class_template "cpp/language/class template"), the arguments are either explicitly provided, [deduced from the initializer](class_template_argument_deduction "cpp/language/class template argument deduction"), (since C++17) or defaulted. For [function templates](function_template "cpp/language/function template"), the arguments are explicitly provided, [deduced from the context](template_argument_deduction "cpp/language/template argument deduction"), or defaulted. If an argument can be interpreted as both a [type-id](type-id "cpp/language/type-id") and an expression, it is always interpreted as a type-id, even if the corresponding template parameter is non-type: ``` template<class T> void f(); // #1 template<int I> void f(); // #2 void g() { f<int()>(); // "int()" is both a type and an expression, // calls #1 because it is interpreted as a type } ``` #### Template non-type arguments The following limitations apply when instantiating templates that have non-type template parameters: | | | | --- | --- | | * For integral and arithmetic types, the template argument provided during instantiation must be a [converted constant expression](constant_expression "cpp/language/constant expression") of the template parameter's type (so certain implicit conversion applies). * For pointers to objects, the template arguments have to designate the address of a complete object with static [storage duration](storage_duration "cpp/language/storage duration") and a [linkage](storage_duration#Linkage "cpp/language/storage duration") (either internal or external), or a constant expression that evaluates to the appropriate null pointer or `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` (since C++11) value. * For pointers to functions, the valid arguments are pointers to functions with linkage (or constant expressions that evaluate to null pointer values). * For lvalue reference parameters, the argument provided at instantiation cannot be a temporary, an unnamed lvalue, or a named lvalue with no linkage (in other words, the argument must have linkage). * For pointers to members, the argument has to be a pointer to member expressed as `&Class::Member` or a constant expression that evaluates to null pointer or `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` (since C++11) value. In particular, this implies that string literals, addresses of array elements, and addresses of non-static members cannot be used as template arguments to instantiate templates whose corresponding non-type template parameters are pointers to objects. | (until C++17) | | The template argument that can be used with a non-type template parameter can be any [converted constant expression](constant_expression "cpp/language/constant expression") of the type of the template parameter. ``` template<const int* pci> struct X {}; int ai[10]; X<ai> xi; // OK: array to pointer conversion and cv-qualification conversion struct Y {}; template<const Y& b> struct Z {}; Y y; Z<y> z; // OK: no conversion template<int (&pa)[5]> struct W {}; int b[5]; W<b> w; // OK: no conversion void f(char); void f(int); template<void (*pf)(int)> struct A {}; A<&f> a; // OK: overload resolution selects f(int) ``` The only exceptions are that non-type template parameters of *reference* or *pointer* type and non-static data members of reference or pointer type in a non-type template parameter of class type and its subobjects (since C++20) cannot refer to/be the address of.* a temporary object (including one created during [reference initialization](reference_initialization "cpp/language/reference initialization")); * a [string literal](string_literal "cpp/language/string literal"); * the result of [`typeid`](typeid "cpp/language/typeid"); * the predefined variable `__func__`; * or a subobject (including non-static class member, base subobject, or array element) of one of the above (since C++20). ``` template<class T, const char* p> class X {}; X<int, "Studebaker"> x1; // error: string literal as template-argument template<int* p> class X {}; int a[10]; struct S { int m; static int s; } s; X<&a[2]> x3; // error (until C++20): address of array element X<&s.m> x4; // error (until C++20): address of non-static member X<&s.s> x5; // OK: address of static member X<&S::s> x6; // OK: address of static member template<const int& CRI> struct B {}; B<1> b2; // error: temporary would be required for template argument int c = 1; B<c> b1; // OK ``` | (since C++17) | #### Template type arguments A template argument for a type template parameter must be a [type-id](type#Type_naming "cpp/language/type"), which may name an incomplete type: ``` template<typename T> class X {}; // class template struct A; // incomplete type typedef struct {} B; // type alias to an unnamed type int main() { X<A> x1; // OK: 'A' names a type X<A*> x2; // OK: 'A*' names a type X<B> x3; // OK: 'B' names a type } ``` #### Template template arguments A template argument for a template template parameter must be an [id-expression](identifiers#In_expressions "cpp/language/identifiers") which names a class template or a template alias. When the argument is a class template, only the primary template is considered when matching the parameter. The partial specializations, if any, are only considered when a specialization based on this template template parameter happens to be instantiated. ``` template<typename T> // primary template class A { int x; }; template<typename T> // partial specialization class A<T*> { long x; }; // class template with a template template parameter V template<template<typename> class V> class C { V<int> y; // uses the primary template V<int*> z; // uses the partial specialization }; C<A> c; // c.y.x has type int, c.z.x has type long ``` To match a template template argument `A` to a template template parameter `P`, `P` must be *at least as specialized* as `A` (see below). If `P`'s parameter list includes a [parameter pack](parameter_pack "cpp/language/parameter pack"), zero or more template parameters (or parameter packs) from `A`'s template parameter list are matched by it. (since C++11). Formally, a template template-parameter `P` is *at least as specialized* as a template template argument `A` if, given the following rewrite to two function templates, the function template corresponding to `P` is at least as specialized as the function template corresponding to `A` according to the partial ordering rules for [function templates](function_template "cpp/language/function template"). Given an invented class template `X` with the template parameter list of `A` (including default arguments): * Each of the two function templates has the same template parameters, respectively, as `P` or `A`. * Each function template has a single function parameter whose type is a specialization of `X` with template arguments corresponding to the template parameters from the respective function template where, for each template parameter `PP` in the template parameter list of the function template, a corresponding template argument `AA` is formed. If `PP` declares a parameter pack, then `AA` is the pack expansion `PP...`; otherwise, (since C++11) `AA` is the id-expression `PP`. If the rewrite produces an invalid type, then `P` is not at least as specialized as `A`. ``` template<typename T> struct eval; // primary template template<template<typename, typename...> class TT, typename T1, typename... Rest> struct eval<TT<T1, Rest...>> {}; // partial specialization of eval template<typename T1> struct A; template<typename T1, typename T2> struct B; template<int N> struct C; template<typename T1, int N> struct D; template<typename T1, typename T2, int N = 17> struct E; eval<A<int>> eA; // OK: matches partial specialization of eval eval<B<int, float>> eB; // OK: matches partial specialization of eval eval<C<17>> eC; // error: C does not match TT in partial specialization // because TT's first parameter is a // type template parameter, while 17 does not name a type eval<D<int, 17>> eD; // error: D does not match TT in partial specialization // because TT's second parameter is a // type parameter pack, while 17 does not name a type eval<E<int, float>> eE; // error: E does not match TT in partial specialization // because E's third (default) parameter is a non-type ``` Before the adoption of [P0522R0](https://wg21.link/p0522r0), each of the template parameters of `A` must match corresponding template parameters of `P` exactly. This hinders many reasonable template argument from being accepted. Although it was pointed out very early ([CWG#150](https://wg21.cmeerw.net/cwg/issue150)), by the time it was resolved, the changes were applied to the C++17 working paper and the resolution became a de facto C++17 feature. Many compilers disable it by default: * [GCC](https://gcc.gnu.org/gcc-7/changes.html#cxx) disables it in all language modes prior to C++17 by default, it can only be enabled by setting a compiler flag in these modes. * [Clang](https://clang.llvm.org/cxx_status.html#p0522) disables it in all language modes by default, it can only be enabled by setting a compiler flag. * [Microsoft Visual Studio](https://docs.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance) treats it as a normal C++17 feature and only enables it in C++17 and later language modes (i.e. no support in C++14 language mode, which is the default mode). ``` template<class T> class A { /* ... */ }; template<class T, class U = T> class B { /* ... */ }; template<class... Types> class C { /* ... */ }; template<template<class> class P> class X { /* ... */ }; X<A> xa; // OK X<B> xb; // OK after P0522R0 // Error earlier: not an exact match X<C> xc; // OK after P0522R0 // Error earlier: not an exact match template<template<class...> class Q> class Y { /* ... */ }; Y<A> ya; // OK Y<B> yb; // OK Y<C> yc; // OK template<auto n> class D { /* ... */ }; // note: C++17 template<template<int> class R> class Z { /* ... */ }; Z<D> zd; // OK after P0522R0: the template parameter // is more specialized than the template argument template<int> struct SI { /* ... */ }; template<template<auto> class> void FA(); // note: C++17 FA<SI>(); // Error ``` #### Default template arguments Default template arguments are specified in the parameter lists after the `=` sign. Defaults can be specified for any kind of template parameter (type, non-type, or template), but not to parameter packs (since C++11). If the default is specified for a template parameter of a primary class template, primary variable template, (since C++14) or alias template, each subsequent template parameter must have a default argument, except the very last one may be a template parameter pack (since C++11). In a function template, there are no restrictions on the parameters that follow a default, and a parameter pack may be followed by more type parameters only if they have defaults or can be deduced from the function arguments (since C++11). Default parameters are not allowed. * in the out-of-class definition of a member of a [class template](class_template "cpp/language/class template") (they have to be provided in the declaration inside the class body). Note that [member templates](member_template "cpp/language/member template") of non-template classes can use default parameters in their out-of-class definitions (see [GCC bug 53856](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53856)) * in [friend class template](friend#Template_friends "cpp/language/friend") declarations | | | | --- | --- | | * in any [function template](function_template "cpp/language/function template") declaration or definition | (until C++11) | | | | | --- | --- | | On a friend function template declaration, default template arguments are allowed only if the declaration is a definition, and no other declarations of this function appear in this translation unit. | (since C++11) | Default template arguments that appear in the declarations are merged similarly to default function arguments: ``` template<typename T1, typename T2 = int> class A; template<typename T1 = int, typename T2> class A; // the above is the same as the following: template<typename T1 = int, typename T2 = int> class A; ``` But the same parameter cannot be given default arguments twice in the same scope: ``` template<typename T = int> class X; template<typename T = int> class X {}; // error ``` When parsing a default template argument for a non-type template parameter, the first non-nested `>` is taken as the end of the template parameter list rather than a greater-than operator: ``` template<int i = 3 > 4> // syntax error class X { /* ... */ }; template<int i = (3 > 4)> // OK class Y { /* ... */ }; ``` The template parameter lists of template template parameters can have their own default arguments, which are only in effect where the template template parameter itself is in scope: ``` // class template, with a type template parameter with a default template<typename T = float> struct B {}; // template template parameter T has a parameter list, which // consists of one type template parameter with a default template<template<typename = float> typename T> struct A { void f(); void g(); }; // out-of-body member function template definitions template<template<typename TT> class T> void A<T>::f() { T<> t; // error: TT has no default in scope } template<template<typename TT = char> class T> void A<T>::g() { T<> t; // OK: t is T<char> } ``` [Member access](access "cpp/language/access") for the names used in a default template parameter is checked at the declaration, not at the point of use: ``` class B {}; template<typename T> class C { protected: typedef T TT; }; template<typename U, typename V = typename U::TT> class D: public U {}; D<C<B>>* d; // error: C::TT is protected ``` | | | | --- | --- | | The default template argument is implicitly instantiated when the value of that default argument is needed, except if the template is used to name a function: ``` template<typename T, typename U = int> struct S {}; S<bool>* p; // The default argument for U is instantiated at this point // the type of p is S<bool, int>* ``` | (since C++14) | #### Template argument equivalence Template argument equivalence is used to determine whether two [template-ids](templates#template-id "cpp/language/templates") are same. Two values are *template-argument-equivalent* if they are of the same type and. * they are of integral or enumeration type and their values are the same * or they are of pointer type and they have the same pointer value * or they are of pointer-to-member type and they refer to the same class member or are both the null member pointer value * or they are of lvalue reference type and they refer to the same object or function | | | | --- | --- | | * or they are of type `std::nullptr_t` | (since C++11) | | | | | --- | --- | | * or they are of floating-point type and their values are identical * or they are of array type (in which case the arrays must be member objects of some class/union) and their corresponding elements are template-argument-equivalent * or they are of union type and either they both have no active member or they have the same active member and their active members are template-argument-equivalent * or they are of non-union class type and their corresponding direct subobjects and reference members are template-argument-equivalent | (since C++20) | ### Examples ``` #include <array> #include <iostream> #include <numeric> // simple non-type template parameter template<int N> struct S { int a[N]; }; template<const char*> struct S2 {}; // complicated non-type example template < char c, // integral type int (&ra)[5], // lvalue reference to object (of array type) int (*pf)(int), // pointer to function int (S<10>::*a)[10] // pointer to member object (of type int[10]) > struct Complicated { // calls the function selected at compile time // and stores the result in the array selected at compile time void foo(char base) { ra[4] = pf(c - base); } }; // S2<"fail"> s2; // error: string literal cannot be used char okay[] = "okay"; // static object with linkage // S2<&okay[0]> s3; // error: array element has no linkage S2<okay> s4; // works int a[5]; int f(int n) { return n; } // C++20: NTTP can be a literal class type template<std::array arr> constexpr auto sum() { return std::accumulate(arr.cbegin(), arr.cend(), 0); } // C++20: class template arguments are deduced at the call site static_assert(sum<std::array<double, 8>{3, 1, 4, 1, 5, 9, 2, 6}>() == 31.0); // C++20: NTTP argument deduction and CTAD static_assert(sum<std::array{2, 7, 1, 8, 2, 8}>() == 28); int main() { S<10> s; // s.a is an array of 10 int s.a[9] = 4; Complicated<'2', a, f, &S<10>::a> c; c.foo('0'); std::cout << s.a[9] << a[4] << '\n'; } ``` Output: ``` 42 ``` ### 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 150](https://cplusplus.github.io/CWG/issues/150.html) | C++98 | template-template arguments had to match parameterlists of template-template parameters exactly | more specialized also allowed(resolved by [P0522R0](https://wg21.link/p0522r0)) | | [CWG 184](https://cplusplus.github.io/CWG/issues/184.html) | C++98 | whether the template parameters of template templateparameters are allowed to have default arguments is unspecified | specification added | | [CWG 354](https://cplusplus.github.io/CWG/issues/354.html) | C++98 | null pointer values could not be non-type template arguments | allowed | | [CWG 1398](https://cplusplus.github.io/CWG/issues/1398.html) | C++11 | template non-type arguments could not have type `std::nullptr_t` | allowed | | [CWG 1570](https://cplusplus.github.io/CWG/issues/1570.html) | C++98 | template non-type arguments could designate addresses of subobjects | not allowed | | [CWG 1922](https://cplusplus.github.io/CWG/issues/1922.html) | C++98 | it was unclear whether a class template whose name is aninjected-class-name can use the default arguments in prior declarations | allowed | | [CWG 2032](https://cplusplus.github.io/CWG/issues/2032.html) | C++14 | for variable templates, there was no restriction on the templateparameters after a template parameter with a default argument | apply the same restriction as onclass templates and alias templates |
programming_docs
cpp constexpr specifier (since C++11) constexpr specifier (since C++11) ================================= * `constexpr` - specifies that the value of a variable or function can appear in [constant expressions](constant_expression "cpp/language/constant expression") ### Explanation The `constexpr` specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time [constant expressions](constant_expression "cpp/language/constant expression") are allowed (provided that appropriate function arguments are given). A `constexpr` specifier used in an object declaration or non-static member function (until C++14) implies `const`. A `constexpr` specifier used in a function or [static](static "cpp/language/static") data member (since C++17) declaration implies `inline`. If any declaration of a function or function template has a `constexpr` specifier, then every declaration must contain that specifier. A **`constexpr` variable** must satisfy the following requirements: * its type must be a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType"). * it must be immediately initialized * the [full-expression](eval_order "cpp/language/eval order") of its initialization, including all implicit conversions, constructors calls, etc, must be a [constant expression](constant_expression "cpp/language/constant expression") | | | | --- | --- | | * it must have constant destruction, i.e. either: + it is not of class type nor (possibly multi-dimensional) array thereof, or + it is of class type or (possibly multi-dimensional) array thereof, that class type has a constexpr destructor, and for a hypothetical expression `e` whose only effect is to destroy the object, `e` would be a core constant expression if the lifetime of the object and its non-mutable subobjects (but not its mutable subobjects) were considered to start within `e`. | (since C++20) | | | | | --- | --- | | If a `constexpr` variable is not [translation-unit-local](tu_local "cpp/language/tu local"), it should not be initialized to point to, or refer to, or have a (possibly recursive) subobject that points to or refers to, a translation-unit-local entity that is usable in constant expressions. Such initialization is disallowed in a [module interface unit](modules "cpp/language/modules") (outside its private-module-fragment, if any) or a module partition, and is deprecated in any other context. | (since C++20) | A **`constexpr` function** must satisfy the following requirements: | | | | --- | --- | | * it must not be [virtual](virtual "cpp/language/virtual") | (until C++20) | | | | | --- | --- | | * it must not be a [coroutine](coroutines "cpp/language/coroutines") | (since C++20) | * its return type (if any) must be a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") * each of its parameters must be a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") * for constructor and destructor (since C++20), the class must have no virtual base classes * there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a [core constant expression](constant_expression#Core_constant_expressions "cpp/language/constant expression") (for constructors, use in a [constant initializer](constant_initialization "cpp/language/constant initialization") is sufficient) (since C++14). No diagnostic is required for a violation of this bullet. | | | | --- | --- | | * its function body must not be a [function-try-block](function-try-block "cpp/language/function-try-block") | (until C++20) | | | | | --- | --- | | * the function body must be either deleted or defaulted or contain only the following: + [null statements](statements#Expression_statements "cpp/language/statements") (plain semicolons) + [static\_assert](static_assert "cpp/language/static assert") declarations + [typedef](typedef "cpp/language/typedef") declarations and [alias](type_alias "cpp/language/type alias") declarations that do not define classes or enumerations + [using declarations](namespace#Using-declarations "cpp/language/namespace") + [using directives](namespace#Using-directives "cpp/language/namespace") + if the function is not a constructor, exactly one [return](return "cpp/language/return") statement | (until C++14) | | * the function body must **not** contain: + a [goto](goto "cpp/language/goto") statement + a statement with a [label](statements#Labels "cpp/language/statements") other than `case` and `default` | | | | --- | --- | | * a [try-block](try_catch "cpp/language/try catch") * an [asm declaration](asm "cpp/language/asm") * a definition of a variable for which [no initialization is performed](default_initialization "cpp/language/default initialization") | (until C++20) | * a definition of a variable of non-literal type * a definition of a variable of static or thread [storage duration](storage_duration "cpp/language/storage duration") (A function body that is `=default;` or `=delete;` contains none of the above.) | (since C++14)(until C++23) | A **`constexpr` constructor** whose function body is not `=delete;` must satisfy the following additional requirements: | | | | --- | --- | | * for the constructor of a [class or struct](class "cpp/language/class"), every base class sub-object and every [non-variant](union#Union-like_classes "cpp/language/union") non-static data member must be initialized. If the class is a [union-like class](union#Union-like_classes "cpp/language/union"), for each of its non-empty anonymous union members, exactly one variant member must be initialized * for the constructor of a non-empty [union](union "cpp/language/union"), exactly one non-static data member must be initialized | (until C++20) | * every constructor selected to initializing non-static data members and base class must be a constexpr constructor. | | | | --- | --- | | Destructors cannot be `constexpr`, but a [trivial destructor](destructor#Trivial_destructor "cpp/language/destructor") can be implicitly called in constant expressions. | (until C++20) | | A **`constexpr` destructor** whose function body is not `=delete;` must satisfy the following additional requirements:* every destructor used to destroy non-static data members and base class must be a constexpr destructor. | (since C++20) | For constexpr function templates and constexpr member functions of class templates, at least one specialization must satisfy the abovementioned requirements. Other specializations are still considered as constexpr, even though a call to such a function cannot appear in a constant expression. ### Notes | | | | --- | --- | | Because the [noexcept](noexcept "cpp/language/noexcept") operator always returns `true` for a constant expression, it can be used to check if a particular invocation of a constexpr function takes the constant expression branch: ``` constexpr int f(); constexpr bool b1 = noexcept(f()); // false, undefined constexpr function constexpr int f() { return 0; } constexpr bool b2 = noexcept(f()); // true, f() is a constant expression ``` | (until C++17) | Constexpr constructors are permitted for classes that aren't literal types. For example, the default constructor of `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` is constexpr, allowing [constant initialization](constant_initialization "cpp/language/constant initialization"). Reference variables can be declared constexpr (their initializers have to be [reference constant expressions](constant_expression#Constant_expression "cpp/language/constant expression")): ``` static constexpr int const& x = 42; // constexpr reference to a const int object // (the object has static storage duration // due to life extension by a static reference) ``` | | | | --- | --- | | Even though `try` blocks and inline assembly are allowed in constexpr functions, throwing exceptions or executing the assembly is still disallowed in a constant expression. If a variable has constant destruction, there is no need to generate machine code in order to call destructor for it, even if its destructor is not trivial. | (since C++20) | ### Keywords [`constexpr`](../keyword/constexpr "cpp/keyword/constexpr"). ### Example Definition of a C++11 constexpr function which computes factorials and a literal type that extends string literals: ``` #include <iostream> #include <stdexcept> // C++11 constexpr functions use recursion rather than iteration // (C++14 constexpr functions may use local variables and loops) constexpr int factorial(int n) { return n <= 1 ? 1 : (n * factorial(n - 1)); } // literal class class conststr { const char* p; std::size_t sz; public: template<std::size_t N> constexpr conststr(const char(&a)[N]): p(a), sz(N - 1) {} // constexpr functions signal errors by throwing exceptions // in C++11, they must do so from the conditional operator ?: constexpr char operator[](std::size_t n) const { return n < sz ? p[n] : throw std::out_of_range(""); } constexpr std::size_t size() const { return sz; } }; // C++11 constexpr functions had to put everything in a single return statement // (C++14 doesn't have that requirement) constexpr std::size_t countlower(conststr s, std::size_t n = 0, std::size_t c = 0) { return n == s.size() ? c : 'a' <= s[n] && s[n] <= 'z' ? countlower(s, n + 1, c + 1) : countlower(s, n + 1, c); } // output function that requires a compile-time constant, for testing template<int n> struct constN { constN() { std::cout << n << '\n'; } }; int main() { std::cout << "4! = " ; constN<factorial(4)> out1; // computed at compile time volatile int k = 8; // disallow optimization using volatile std::cout << k << "! = " << factorial(k) << '\n'; // computed at run time std::cout << "the number of lowercase letters in \"Hello, world!\" is "; constN<countlower("Hello, world!")> out2; // implicitly converted to conststr } ``` Output: ``` 4! = 24 8! = 40320 the number of lowercase letters in "Hello, world!" is 9 ``` ### 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 1712](https://cplusplus.github.io/CWG/issues/1712.html) | C++14 | a constexpr variable template was required to have allits declarations contain the `constexpr` specifier(it is redundant because there cannot be more than onedeclaration of a variable template with the `constexpr` specifier) | not required anymore | | [CWG 1911](https://cplusplus.github.io/CWG/issues/1911.html) | C++11 | constexpr constructors for non-literal types were not allowed | allowed in constant initialization | | [CWG 2004](https://cplusplus.github.io/CWG/issues/2004.html) | C++11 | copy/move of a union with a mutable memberwas allowed in a constant expression | mutable variants disqualifyimplicit copy/move | | [CWG 2163](https://cplusplus.github.io/CWG/issues/2163.html) | C++14 | labels were allowed in constexpr functionseven though gotos are prohibited | labels also prohibited | | [CWG 2268](https://cplusplus.github.io/CWG/issues/2268.html) | C++11 | copy/move of a union with a mutablemember was prohibited by [CWG issue 2004](https://cplusplus.github.io/CWG/issues/2004.html) | allowed if the object is createdwithin the constant expression | ### See also | | | | --- | --- | | [constant expression](constant_expression "cpp/language/constant expression") | defines an [expression](expressions "cpp/language/expressions") that can be evaluated at compile time | | [`consteval` specifier](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](constinit "cpp/language/constinit")(C++20) | asserts that a variable has static initialization, i.e. [zero initialization](zero_initialization "cpp/language/zero initialization") and [constant initialization](constant_initialization "cpp/language/constant initialization") | cpp Undefined behavior Undefined behavior ================== Renders the entire program meaningless if certain rules of the language are violated. ### Explanation The C++ standard precisely defines the [observable behavior](as_if "cpp/language/as if") of every C++ program that does not fall into one of the following classes: * *ill-formed* - the program has syntax errors or diagnosable semantic errors. A conforming C++ compiler is required to issue a diagnostic, even if it defines a language extension that assigns meaning to such code (such as with variable-length arrays). The text of the standard uses *shall*, *shall not*, and *ill-formed* to indicate these requirements. * *ill-formed, [no diagnostic required](ndr "cpp/language/ndr")* - the program has semantic errors which may not be diagnosable in general case (e.g. violations of the [ODR](definition "cpp/language/definition") or other errors that are only detectable at link time). The behavior is undefined if such program is executed. * *implementation-defined behavior* - the behavior of the program varies between implementations, and the conforming implementation must document the effects of each behavior. For example, the type of `[std::size\_t](../types/size_t "cpp/types/size t")` or the number of bits in a byte, or the text of `[std::bad\_alloc::what](../memory/new/bad_alloc "cpp/memory/new/bad alloc")`. A subset of implementation-defined behavior is *locale-specific behavior*, which depends on the implementation-supplied [locale](../locale "cpp/locale"). * *unspecified behavior* - the behavior of the program varies between implementations, and the conforming implementation is not required to document the effects of each behavior. For example, [order of evaluation](eval_order "cpp/language/eval order"), whether identical [string literals](string_literal "cpp/language/string literal") are distinct, the amount of array allocation overhead, etc. Each unspecified behavior results in one of a set of valid results. * *undefined behavior* - there are no restrictions on the behavior of the program. Examples of undefined behavior are data races, memory accesses outside of array bounds, signed integer overflow, null pointer dereference, [more than one](eval_order "cpp/language/eval order") modifications of the same scalar in an expression without any intermediate sequence point (until C++11)that is unsequenced (since C++11), access to an object through [a pointer of a different type](reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast"), etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful. ### UB and optimization Because correct C++ programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled: For example, #### Signed overflow ``` int foo(int x) { return x+1 > x; // either true or UB due to signed overflow } ``` may be compiled as ([demo](https://godbolt.org/z/y4vIi1)). ``` foo(int): movl $1, %eax ret ``` #### Access out of bounds ``` int table[4] = {}; bool exists_in_table(int v) { // return true in one of the first 4 iterations or UB due to out-of-bounds access for (int i = 0; i <= 4; i++) { if (table[i] == v) return true; } return false; } ``` May be compiled as ([demo](https://godbolt.org/z/e2bC84)). ``` exists_in_table(int): movl $1, %eax ret ``` #### Uninitialized scalar ``` std::size_t f(int x) { std::size_t a; if(x) // either x nonzero or UB a = 42; return a; } ``` May be compiled as ([demo](https://godbolt.org/z/QYZvsl)). ``` f(int): mov eax, 42 ret ``` The output shown was observed on an older version of gcc. ``` bool p; // uninitialized local variable if(p) // UB access to uninitialized scalar std::puts("p is true"); if(!p) // UB access to uninitialized scalar std::puts("p is false"); ``` Possible output: ``` p is true p is false ``` #### Invalid scalar ``` int f() { bool b = true; unsigned char* p = reinterpret_cast<unsigned char*>(&b); *p = 10; // reading from b is now UB return b == 0; } ``` May be compiled as ([demo](https://gcc.godbolt.org/z/6itUO1)). ``` f(): movl $11, %eax ret ``` #### Null pointer dereference ``` int foo(int* p) { int x = *p; if(!p) return x; // Either UB above or this branch is never taken else return 0; } int bar() { int* p = nullptr; return *p; // Unconditional UB } ``` may be compiled as ([foo with gcc, bar with clang](https://godbolt.org/z/kzr8VJ)). ``` foo(int*): xorl %eax, %eax ret bar(): retq ``` #### Access to pointer passed to realloc Choose clang to observe the output shown. ``` #include <iostream> #include <cstdlib> int main() { int *p = (int*)std::malloc(sizeof(int)); int *q = (int*)std::realloc(p, sizeof(int)); *p = 1; // UB access to a pointer that was passed to realloc *q = 2; if (p == q) // UB access to a pointer that was passed to realloc std::cout << *p << *q << '\n'; } ``` Possible output: ``` 12 ``` #### Infinite loop without side-effects Choose clang or the latest gcc to observe the output shown. ``` #include <iostream> bool fermat() { const int MAX = 1000; int a=1, b=1, c=1; // Endless loop with no side effects is UB while (true) { if (((a*a*a) == ((b*b*b)+(c*c*c)))) return true; a++; if (a>MAX) { a=1; b++; } if (b>MAX) { b=1; c++; } if (c>MAX) { c=1; } } return false; } int main() { if (fermat()) std::cout << "Fermat's Last Theorem has been disproved.\n"; else std::cout << "Fermat's Last Theorem has not been disproved.\n"; } ``` Possible output: ``` Fermat's Last Theorem has been disproved. ``` ### External links * [The LLVM Project Blog: What Every C Programmer Should Know About Undefined Behavior #1/3](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html) * [The LLVM Project Blog: What Every C Programmer Should Know About Undefined Behavior #2/3](https://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html) * [The LLVM Project Blog: What Every C Programmer Should Know About Undefined Behavior #3/3](https://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html) * [Undefined behavior can result in time travel (among other things, but time travel is the funkiest)](http://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx) * [Understanding Integer Overflow in C/C++](http://www.cs.utah.edu/~regehr/papers/overflow12.pdf) * [Fun with NULL pointers, part 1](http://lwn.net/Articles/342330/) (local exploit in Linux 2.6.30 caused by UB due to null pointer dereference) * [Undefined Behavior and Fermat’s Last Theorem](https://web.archive.org/web/20201108094235/https://kukuruku.co/post/undefined-behavior-and-fermats-last-theorem/) ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/behavior "c/language/behavior") for Undefined behavior | cpp Attribute specifier sequence(since C++11) Attribute specifier sequence(since C++11) ========================================= Introduces implementation-defined attributes for types, objects, code, etc. `[[` attr`]]` `[[`attr1, attr2, attr3`(`args`)``]]` `[[`namespace`::`attr`(`args`)``]]` alignas-specifier Formally, the syntax is. | | | | | --- | --- | --- | | `[[` attribute-list `]]` | | (since C++11) | | `[[` `using` attribute-namespace `:` attribute-list `]]` | | (since C++17) | where attribute-list is a comma-separated sequence of zero or more attributes (possibly ending with an ellipsis `...` indicating a [pack expansion](parameter_pack "cpp/language/parameter pack")). | | | | | --- | --- | --- | | identifier | (1) | | | attribute-namespace `::` identifier | (2) | | | identifier `(` argument-list `)` | (3) | | | attribute-namespace `::` identifier `(` argument-list `)` | (4) | | 1) simple attribute, such as `[[noreturn]]` 2) attribute with a namespace, such as `[[gnu::unused]]` 3) attribute with arguments, such as `[[deprecated("because")]]` 4) attribute with both a namespace and an argument list | | | | --- | --- | | If `using namespace:` appears in the beginning of an attribute list, no other attributes in the attribute list can specify a namespace: the namespace specified in a using applies to them all: ``` [[using CC: opt(1), debug]] // same as [[CC::opt(1), CC::debug]] [[using CC: CC::opt(1)]] // error: cannot combine using and scoped attribute ``` | (since C++17) | ### Explanation Attributes provide the unified standard syntax for implementation-defined language extensions, such as the GNU and IBM language extensions `__attribute__((...))`, Microsoft extension `__declspec()`, etc. An attribute can be used almost everywhere in the C++ program, and can be applied to almost everything: to types, to variables, to functions, to names, to code blocks, to entire translation units, although each particular attribute is only valid where it is permitted by the implementation: `[[expect_true]]` could be an attribute that can only be used with an `if`, and not with a class declaration. `[[omp::parallel()]]` could be an attribute that applies to a code block or to a `for` loop, but not to the type `int`, etc. (note these two attributes are fictional examples, see below for the standard and some non-standard attributes). In declarations, attributes may appear both before the whole declaration and directly after the name of the entity that is declared, in which case they are combined. In most other situations, attributes apply to the directly preceding entity. The [`alignas` specifier](alignas "cpp/language/alignas") is a part of the attribute specifier sequence, although it has different syntax. It may appear where the `[...](https://en.cppreference.com/mwiki/index.php?title=...&action=edit&redlink=1 "... (page does not exist)")` attributes appear and may mix with them (provided it is used where `alignas` is permitted). Two consecutive left square bracket tokens (`[[`) may only appear when introducing an attribute-specifier or inside an attribute argument. ``` void f() { int y[3]; y[[] { return 0; }()] = 1; // error int i [[cats::meow([[]])]]; // OK } ``` Besides the standard attributes listed below, implementations may support arbitrary non-standard attributes with implementation-defined behavior. All attributes unknown to an implementation are ignored without causing an error. (since C++17). | | | | --- | --- | | An attribute without attribute-namespace and an attribute-namespace whose name is either `std` or `std` followed by one or more digits is reserved for future standardization. That is, every non-standard attribute is in the attribute-namespace provided by the implementation, e.g. `[[gnu::may_alias]]`, `[[clang::trivial_abi]]`, and `[[msvc::noop_dtor]]`. | (since C++20) | ### Standard attributes Only the following attributes are defined by the C++ standard. | | | | --- | --- | | `[[[noreturn](attributes/noreturn "cpp/language/attributes/noreturn")]]`(since C++11) | indicates that the function does not return | | `[[[carries\_dependency](attributes/carries_dependency "cpp/language/attributes/carries dependency")]]`(since C++11) | indicates that dependency chain in release-consume `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")` propagates in and out of the function | | `[[[deprecated](attributes/deprecated "cpp/language/attributes/deprecated")]]`(since C++14)`[[deprecated("reason")]]`(since C++14) | indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason | | `[[[fallthrough](attributes/fallthrough "cpp/language/attributes/fallthrough")]]`(since C++17) | indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fall-through | | `[[[nodiscard](attributes/nodiscard "cpp/language/attributes/nodiscard")]]`(since C++17)`[[nodiscard("reason")]]`(since C++20) | encourages the compiler to issue a warning if the return value is discarded | | `[[[maybe\_unused](attributes/maybe_unused "cpp/language/attributes/maybe unused")]]`(since C++17) | suppresses compiler warnings on unused entities, if any | | `[[[likely](attributes/likely "cpp/language/attributes/likely")]]`(since C++20)`[[[unlikely](attributes/likely "cpp/language/attributes/likely")]]`(since C++20) | indicates that the compiler should optimize for the case where a path of execution through a statement is more or less likely than any other path of execution | | `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]`(since C++20) | indicates that a non-static data member need not have an address distinct from all other non-static data members of its class | | `[[[optimize\_for\_synchronized](attributes/optimize_for_synchronized "cpp/language/attributes/optimize for synchronized")]]`(TM TS) | indicates that the function definition should be optimized for invocation from a [synchronized statement](transactional_memory "cpp/language/transactional memory") | ### Example ``` [[gnu::always_inline]] [[gnu::hot]] [[gnu::const]] [[nodiscard]] inline int f(); // declare f with four attributes [[gnu::always_inline, gnu::const, gnu::hot, nodiscard]] int f(); // same as above, but uses a single attr specifier that contains four attributes // C++17: [[using gnu : const, always_inline, hot]] [[nodiscard]] int f[[gnu::always_inline]](); // an attribute may appear in multiple specifiers int f() { return 0; } int main() {} ``` ### 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 2079](https://cplusplus.github.io/CWG/issues/2079.html) | C++11 | `[[` could not appear inside an attribute argument | allowed | | [P2156R1](https://wg21.link/P2156R1) | C++11 | every standard attribute was required to appear at most once in an attribute-list | not required | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/attributes "c/language/attributes") for Attributes specifier sequence | ### External links * [Attributes in GCC](https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#Attribute-Syntax) + these attributes can be used as `[[gnu::...]]`, see [here](https://stackoverflow.com/questions/54639524/which-gnu-attributes-have-c11-syntax#comment96071307_54639524) * [Attributes in Clang](https://clang.llvm.org/docs/AttributeReference.html)
programming_docs
cpp ASCII Chart ASCII Chart =========== The following chart contains all 128 ASCII decimal **(dec)**, octal **(oct)**, hexadecimal **(hex)** and character **(ch)** codes. | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `dec` | `oct` | `hex` | `ch` | | `dec` | `oct` | `hex` | `ch` | | `dec` | `oct` | `hex` | `ch` | | `dec` | `oct` | `hex` | `ch` | | `0` | `0` | `00` | `NUL` (null) | `32` | `40` | `20` | (space) | `64` | `100` | `40` | `@` | `96` | `140` | `60` | ``` | | `1` | `1` | `01` | `SOH` (start of header) | `33` | `41` | `21` | `!` | `65` | `101` | `41` | `A` | `97` | `141` | `61` | `a` | | `2` | `2` | `02` | `STX` (start of text) | `34` | `42` | `22` | `"` | `66` | `102` | `42` | `B` | `98` | `142` | `62` | `b` | | `3` | `3` | `03` | `ETX` (end of text) | `35` | `43` | `23` | `#` | `67` | `103` | `43` | `C` | `99` | `143` | `63` | `c` | | `4` | `4` | `04` | `EOT` (end of transmission) | `36` | `44` | `24` | `$` | `68` | `104` | `44` | `D` | `100` | `144` | `64` | `d` | | `5` | `5` | `05` | `ENQ` (enquiry) | `37` | `45` | `25` | `%` | `69` | `105` | `45` | `E` | `101` | `145` | `65` | `e` | | `6` | `6` | `06` | `ACK` (acknowledge) | `38` | `46` | `26` | `&` | `70` | `106` | `46` | `F` | `102` | `146` | `66` | `f` | | `7` | `7` | `07` | `BEL` (bell) | `39` | `47` | `27` | `'` | `71` | `107` | `47` | `G` | `103` | `147` | `67` | `g` | | `8` | `10` | `08` | `BS` (backspace) | `40` | `50` | `28` | `(` | `72` | `110` | `48` | `H` | `104` | `150` | `68` | `h` | | `9` | `11` | `09` | `HT` (horizontal tab) | `41` | `51` | `29` | `)` | `73` | `111` | `49` | `I` | `105` | `151` | `69` | `i` | | `10` | `12` | `0a` | `LF` (line feed - new line) | `42` | `52` | `2a` | `*` | `74` | `112` | `4a` | `J` | `106` | `152` | `6a` | `j` | | `11` | `13` | `0b` | `VT` (vertical tab) | `43` | `53` | `2b` | `+` | `75` | `113` | `4b` | `K` | `107` | `153` | `6b` | `k` | | `12` | `14` | `0c` | `FF` (form feed - new page) | `44` | `54` | `2c` | `,` | `76` | `114` | `4c` | `L` | `108` | `154` | `6c` | `l` | | `13` | `15` | `0d` | `CR` (carriage return) | `45` | `55` | `2d` | `-` | `77` | `115` | `4d` | `M` | `109` | `155` | `6d` | `m` | | `14` | `16` | `0e` | `SO` (shift out) | `46` | `56` | `2e` | `.` | `78` | `116` | `4e` | `N` | `110` | `156` | `6e` | `n` | | `15` | `17` | `0f` | `SI` (shift in) | `47` | `57` | `2f` | `/` | `79` | `117` | `4f` | `O` | `111` | `157` | `6f` | `o` | | `16` | `20` | `10` | `DLE` (data link escape) | `48` | `60` | `30` | `0` | `80` | `120` | `50` | `P` | `112` | `160` | `70` | `p` | | `17` | `21` | `11` | `DC1` (device control 1) | `49` | `61` | `31` | `1` | `81` | `121` | `51` | `Q` | `113` | `161` | `71` | `q` | | `18` | `22` | `12` | `DC2` (device control 2) | `50` | `62` | `32` | `2` | `82` | `122` | `52` | `R` | `114` | `162` | `72` | `r` | | `19` | `23` | `13` | `DC3` (device control 3) | `51` | `63` | `33` | `3` | `83` | `123` | `53` | `S` | `115` | `163` | `73` | `s` | | `20` | `24` | `14` | `DC4` (device control 4) | `52` | `64` | `34` | `4` | `84` | `124` | `54` | `T` | `116` | `164` | `74` | `t` | | `21` | `25` | `15` | `NAK` (negative acknowledge) | `53` | `65` | `35` | `5` | `85` | `125` | `55` | `U` | `117` | `165` | `75` | `u` | | `22` | `26` | `16` | `SYN` (synchronous idle) | `54` | `66` | `36` | `6` | `86` | `126` | `56` | `V` | `118` | `166` | `76` | `v` | | `23` | `27` | `17` | `ETB` (end of transmission block) | `55` | `67` | `37` | `7` | `87` | `127` | `57` | `W` | `119` | `167` | `77` | `w` | | `24` | `30` | `18` | `CAN` (cancel) | `56` | `70` | `38` | `8` | `88` | `130` | `58` | `X` | `120` | `170` | `78` | `x` | | `25` | `31` | `19` | `EM` (end of medium) | `57` | `71` | `39` | `9` | `89` | `131` | `59` | `Y` | `121` | `171` | `79` | `y` | | `26` | `32` | `1a` | `SUB` (substitute) | `58` | `72` | `3a` | `:` | `90` | `132` | `5a` | `Z` | `122` | `172` | `7a` | `z` | | `27` | `33` | `1b` | `ESC` (escape) | `59` | `73` | `3b` | `;` | `91` | `133` | `5b` | `[` | `123` | `173` | `7b` | `{` | | `28` | `34` | `1c` | `FS` (file separator) | `60` | `74` | `3c` | `<` | `92` | `134` | `5c` | `\` | `124` | `174` | `7c` | `|` | | `29` | `35` | `1d` | `GS` (group separator) | `61` | `75` | `3d` | `=` | `93` | `135` | `5d` | `]` | `125` | `175` | `7d` | `}` | | `30` | `36` | `1e` | `RS` (record separator) | `62` | `76` | `3e` | `>` | `94` | `136` | `5e` | `^` | `126` | `176` | `7e` | `~` | | `31` | `37` | `1f` | `US` (unit separator) | `63` | `77` | `3f` | `?` | `95` | `137` | `5f` | `_` | `127` | `177` | `7f` | `DEL` (delete) | Note: in Unicode, the ASCII character block is known as [`U+0000..U+007F` Basic Latin](http://www.unicode.org/charts/PDF/U0000.pdf). ### Example ``` #include <iostream> int main() { std::cout << "Printable ASCII [32..126]:\n"; for (char c{' '}; c <= '~'; c++) { std::cout << c << ((c+1) % 32 ? ' ' : '\n'); } } ``` Possible output: ``` Printable ASCII [32..126]: ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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 [ \ ] ^ _ ` 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 { | } ~ ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/ascii "c/language/ascii") for ASCII Chart | cpp Definitions and ODR (One Definition Rule) Definitions and ODR (One Definition Rule) ========================================= *Definitions* are [declarations](declarations "cpp/language/declarations") that fully define the entity introduced by the declaration. Every declaration is a definition, except for the following: * A function declaration without a function body: ``` int f(int); // declares, but doesn't define f ``` * Any declaration with an `extern` [storage class specifier](storage_duration "cpp/language/storage duration") or with a [language linkage](language_linkage "cpp/language/language linkage") specifier (such as `extern "C"`) without an initializer: ``` extern const int a; // declares, but doesn't define a extern const int b = 1; // defines b ``` * Declaration of a non-inline (since C++17) [static data member](static "cpp/language/static") inside a class definition: ``` struct S { int n; // defines S::n static int i; // declares, but doesn't define S::i inline static int x; // defines S::x }; // defines S int S::i; // defines S::i ``` | | | | --- | --- | | * (deprecated) Namespace scope declaration of a static data member that was defined within the class with the `[constexpr](constexpr "cpp/language/constexpr")` specifier: ``` struct S { static constexpr int x = 42; // implicitly inline, defines S::x }; constexpr int S::x; // declares S::x, not a redefinition ``` | (since C++17) | * Declaration of a class name (by [forward declaration](class#Forward_declaration "cpp/language/class") or by the use of the elaborated type specifier in another declaration): ``` struct S; // declares, but doesn't define S class Y f(class T p); // declares, but doesn't define Y and T (and also f and p) ``` | | | | --- | --- | | * An [opaque declaration](enum "cpp/language/enum") of an enumeration: ``` enum Color : int; // declares, but doesn't define Color ``` | (since C++11) | * Declaration of a [template parameter](template_parameters "cpp/language/template parameters"): ``` template<typename T> // declares, but doesn't define T ``` * A parameter declaration in a function declaration that isn't a definition: ``` int f(int x); // declares, but doesn't define f and x int f(int x) // defines f and x { return x + a; } ``` * A [typedef](typedef "cpp/language/typedef") declaration: ``` typedef S S2; // declares, but doesn't define S2 (S may be incomplete) ``` | | | | --- | --- | | * An [alias-declaration](type_alias "cpp/language/type alias"): ``` using S2 = S; // declares, but doesn't define S2 (S may be incomplete) ``` | (since C++11) | * A [using-declaration](using_declaration "cpp/language/using declaration"): ``` using N::d; // declares, but doesn't define d ``` | | | | --- | --- | | * Declaration of a [deduction guide](class_template_argument_deduction#Explicit_deduction_guides "cpp/language/class template argument deduction") (does not define any entities) | (since C++17) | | * A [static\_assert](static_assert "cpp/language/static assert") declaration (does not define any entities) * An [attribute declaration](declarations "cpp/language/declarations") (does not define any entities) | (since C++11) | * An [empty declaration](declarations "cpp/language/declarations") (does not define any entities) * A [using-directive](namespace#Using-directives "cpp/language/namespace") (does not define any entities) | | | | --- | --- | | * An [explicit instantiation declaration](class_template#Class_template_instantiation "cpp/language/class template") (an "extern template"): ``` extern template f<int, char>; // declares, but doesn't define f<int, char> ``` | (since C++11) | * An [explicit specialization](template_specialization "cpp/language/template specialization") whose declaration is not a definition: ``` template<> struct A<int>; // declares, but doesn't define A<int> ``` An [asm declaration](asm "cpp/language/asm") does not define any entities, but it is classified as a definition. Where necessary, the compiler may implicitly define the [default constructor](default_constructor "cpp/language/default constructor"), [copy constructor](copy_constructor "cpp/language/copy constructor"), [move constructor](move_constructor "cpp/language/move constructor"), [copy assignment operator](as_operator "cpp/language/as operator"), [move assignment operator](move_operator "cpp/language/move operator"), and the [destructor](destructor "cpp/language/destructor"). If the definition of any object results in an object of [incomplete type](incomplete_type "cpp/language/incomplete type") or [abstract class type](abstract_class "cpp/language/abstract class"), the program is ill-formed. ### One Definition Rule Only one definition of any variable, function, class type, enumeration type, [concept](constraints "cpp/language/constraints") (since C++20) or template is allowed in any one translation unit (some of these may have multiple declarations, but only one definition is allowed). One and only one definition of every non-[inline](inline "cpp/language/inline") function or variable that is *odr-used* (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined. For an inline function or inline variable (since C++17), a definition is required in every translation unit where it is *odr-used*. For a class, a definition is required wherever the class is used in a way that requires it to be [complete](incomplete_type "cpp/language/incomplete type"). There can be more than one definition in a program of each of the following: class type, enumeration type, inline function, inline variable (since C++17), [templated entity](templates#Templated_entity "cpp/language/templates") (template or member of template, but not full [template specialization](template_specialization "cpp/language/template specialization")), as long as all of the following is true: * each definition appears in a different translation unit | | | | --- | --- | | * the definitions are not [attached to a named module](modules "cpp/language/modules") | (since C++20) | * each definition consists of the same sequence of tokens (typically, appears in the same header file) * name lookup from within each definition finds the same entities (after overload-resolution), except that + constants with internal or no linkage may refer to different objects as long as they are not odr-used and have the same values in every definition | | | | --- | --- | | * lambda-expressions that are not in a default argument or a default template argument (since C++20) are uniquely identified by the sequence of tokens used to define them | (since C++11) | * overloaded operators, including conversion, allocation, and deallocation functions refer to the same function from each definition (unless referring to one defined within the definition) * the language linkage is the same (e.g. the include file isn't inside an extern "C" block) * the three rules above apply to every default argument used in each definition * if the definition is for a class with an implicitly-declared constructor, every translation unit where it is odr-used must call the same constructor for the base and members | | | | --- | --- | | * if the definition is for a class with a defaulted [three-way comparison](default_comparisons "cpp/language/default comparisons"), every translation unit where it is odr-used must call the same comparison operator for the base and members | (since C++20) | * if the definition is for a template, then all these requirements apply to both names at the point of definition and dependent names at the point of instantiation If all these requirements are satisfied, the program behaves as if there is only one definition in the entire program. Otherwise, the program is ill-formed, no diagnostic required. Note: in C, there is no program-wide ODR for types, and even extern declarations of the same variable in different translation units may have different types [as long as they are compatible](https://en.cppreference.com/w/c/language/type#Compatible_types "c/language/type"). In C++, the source-code tokens used in declarations of the same type must be the same as described above: if one .cpp file defines `struct S { int x; };` and the other .cpp file defines `struct S { int y; };`, the behavior of the program that links them together is undefined. This is usually resolved with [unnamed namespaces](namespace "cpp/language/namespace"). #### ODR-use Informally, an object is odr-used if its value is read (unless it is a compile time constant) or written, its address is taken, or a reference is bound to it; a reference is odr-used if it is used and its referent is not known at compile time; and a function is odr-used if a function call to it is made or its address is taken. If an object, a reference or a function is odr-used, its definition must exist somewhere in the program; a violation of that is usually a link-time error. ``` struct S { static const int x = 0; // static data member // a definition outside of class is required if it is odr-used }; const int& f(const int& r); int n = b ? (1, S::x) // S::x is not odr-used here : f(S::x); // S::x is odr-used here: a definition is required ``` Formally, 1) a variable `x` in a *potentially-evaluated* expression `ex` is odr-used unless both of the following are true: * applying lvalue-to-rvalue conversion to `x` yields a constant expression that doesn't invoke non-trivial functions * either `x` is not an object (that is, `x` is a reference) or, if `x` is an object, it is one of the *potential results* of a larger expression `e`, where that larger expression is either a [discarded-value expression](expressions#Discarded-value_expressions "cpp/language/expressions") or has the lvalue-to-rvalue conversion applied to it ``` struct S { static const int x = 1; }; // applying lvalue-to-rvalue conversion // to S::x yields a constant expression int f() { S::x; // discarded-value expression does not odr-use S::x return S::x; // expression where lvalue-to-rvalue conversion // applies does not odr-use S::x } ``` 2) [`*this`](this "cpp/language/this") is odr-used if `this` appears as a *potentially-evaluated* expression (including the implicit `this` in a non-static member function call expression) | | | | --- | --- | | 3) A [structured binding](structured_binding "cpp/language/structured binding") is odr-used if it appears as a *potentially-evaluated* expression. | (since C++17) | In the definitions above, *potentially-evaluated* means the expression is not an [unevaluated operand](expressions#Unevaluated_expressions "cpp/language/expressions") (or its subexpression), such as the operand of [`sizeof`](sizeof "cpp/language/sizeof") and *a set of potential results* of an expression `E` is a (possibly empty) set of id-expressions that appear within `E`, combined as follows: * If `E` is an [id-expression](expressions#Primary_expressions "cpp/language/expressions"), the expression `E` is its only potential result. * If `E` is a subscript expression (`E1[E2]`) where one of the operands is an array, the potential results of that operand is included in the set. * If `E` is a class member access expression of the form `E1.E2` or `E1.template E2` naming a non-static data member, the potential results of `E1` is included in the set. * If `E` is a class member access expression naming a static data member, the id-expression designating the data member is included in the set. * If `E` is a pointer-to-member access expression of the form `E1.*E2` or `E1.*template E2` whose second operand is a constant expression, the potential results of `E1` are included in the set. * If `E` is an expression in parentheses (`(E1)`), the potential results of `E1` are included in the set. * If `E` is a glvalue conditional expression (`E1 ? E2 : E3`, where `E2` and `E3` are glvalues), the union of the potential results of `E2` and `E3` are both included in the set. * If `E` is a comma expression (`E1, E2`), the potential results of `E2` are in the set of potential results. * Otherwise, the set is empty. ``` struct S { static const int a = 1; static const int b = 2; }; int f(bool x) { return x ? S::a : S::b; // x is a part of the subexpression "x" (to the left of ?), // which applies lvalue-to-rvalue conversion, but applying that conversion to x // does not yield a constant expression, so x is odr-used // S::a and S::b are lvalues, and carry over as "potential results" // to the result of the glvalue conditional // That result is then subject to lvalue-to-rvalue conversion requested // to copy-initialize the return value, therefore S::a and S::b are not odr-used } ``` 4) A function is odr-used in following cases: * A function is odr-used if it is named by (see below) a potentially-evaluated expression or conversion. * A [virtual member function](virtual "cpp/language/virtual") is odr-used if it is not a pure virtual member function (addresses of virtual member functions are required to construct the vtable). * A non-placement allocation or deallocation function for a class is odr-used by the definition of a constructor of that class. * A non-placement deallocation function for a class is odr-used by the definition of the destructor of that class, or by being selected by the lookup at the point of definition of a virtual destructor. * An assignment operator in a class `T` that is a member or base of another class `U` is odr-used by an implicitly-defined copy-assignment or move-assignment functions of `U`. * A constructor (including default constructors) for a class is odr-used by the [initialization](initialization "cpp/language/initialization") that selects it. * A destructor for a class is odr-used if it is potentially invoked. #### Naming a function A function is named by an expression or conversion in following cases: * A function whose name appears as an expression or conversion (including named function, overloaded operator, [user-defined conversion](cast_operator "cpp/language/cast operator"), user-defined placement forms of operator new, non-default initialization) is named by that expression if it is selected by overload resolution, except when it is an unqualified pure virtual member function or a pointer-to-member to a pure virtual function. * An [allocation](../memory/new/operator_new "cpp/memory/new/operator new") or [deallocation](../memory/new/operator_delete "cpp/memory/new/operator delete") function for a class is named by a [new expression](new "cpp/language/new") appearing in an expression. * A deallocation function for a class is named by a [delete expression](delete "cpp/language/delete") appearing in an expression. * A constructor selected to copy or move an object is considered to be named by the expression or conversion even if [copy elision](copy_elision "cpp/language/copy elision") takes place. Using a prvalue in some contexts does not copy or move an object, see [Mandatory elision](copy_elision#Mandatory_elision_of_copy.2Fmove_operations "cpp/language/copy elision"). (since C++17) A potentially evaluated expression or conversion odr-uses a function if it names it. | | | | --- | --- | | A potentially constant evaluated expression or conversion that names a constexpr function makes it [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression"), which triggers definition of a defaulted function or instantiation of a function template specialization, even if the expression is unevaluated. | (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 261](https://cplusplus.github.io/CWG/issues/261.html) | C++98 | a deallocation function for a polymorphic classmight be odr-used even if there were no relevantnew or delete expressions in the program | supplemented theodr-use cases to coverconstructors and destructors | | [CWG 678](https://cplusplus.github.io/CWG/issues/678.html) | C++98 | an entity could have definitionswith different language linkages | the behavior isundefined in this case | | [CWG 1472](https://cplusplus.github.io/CWG/issues/1472.html) | C++98 | reference variables which satisfy the requirements forappearing in a constant expression were odr-used evenif the lvalue-to-rvalue conversion is immediately applied | they are not odr-usedin this case | | [CWG 1614](https://cplusplus.github.io/CWG/issues/1614.html) | C++98 | taking address of a pure virtual function odr-used it | the function is not odr-used | | [CWG 1741](https://cplusplus.github.io/CWG/issues/1741.html) | C++98 | constant objects that are immediately lvalue-to-rvalueconverted in potentially-evaluated expressions were odr-used | they are not odr-used | | [CWG 1926](https://cplusplus.github.io/CWG/issues/1926.html) | C++98 | array subscript expressions didn't propagate potential results | they propagate | | [CWG 2300](https://cplusplus.github.io/CWG/issues/2300.html) | C++11 | lambda expressions in different translationunits could never have the same closure type | the closure type can be thesame under one definition rule | | [CWG 2353](https://cplusplus.github.io/CWG/issues/2353.html) | C++98 | a static data member was not a potential resultof a member access expression accesing it | it is | | [CWG 2433](https://cplusplus.github.io/CWG/issues/2433.html) | C++14 | a variable template could not have multiple definitions in a program | it can | ### References * C++20 standard (ISO/IEC 14882:2020): + 6.3 One definition rule [basic.def.odr] * C++17 standard (ISO/IEC 14882:2017): + 6.2 One definition rule [basic.def.odr] * C++14 standard (ISO/IEC 14882:2014): + 3.2 One definition rule [basic.def.odr] * C++11 standard (ISO/IEC 14882:2011): + 3.2 One definition rule [basic.def.odr] * C++03 standard (ISO/IEC 14882:2003): + 3.2 One definition rule [basic.def.odr] * C++98 standard (ISO/IEC 14882:1998): + 3.2 One definition rule [basic.def.odr]
programming_docs
cpp continue statement continue statement ================== Causes the remaining portion of the enclosing [for](for "cpp/language/for"), [range-for](range-for "cpp/language/range-for"), [while](while "cpp/language/while") or [do-while](do "cpp/language/do") loop body to be skipped. Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements. ### Syntax | | | | | --- | --- | --- | | attr(optional) `continue` `;` | | | ### Explanation The `continue` statement causes a jump, as if by [goto](goto "cpp/language/goto") to the end of the loop body (it may only appear within the loop body of [for](for "cpp/language/for"), [range-for](range-for "cpp/language/range-for"), [while](while "cpp/language/while"), and [do-while](do "cpp/language/do") loops). More precisely, For [while](while "cpp/language/while") loop, it acts as. ``` while (/* ... */) { // ... continue; // acts as goto contin; // ... contin:; } ``` For [do-while](do "cpp/language/do") loop, it acts as: ``` do { // ... continue; // acts as goto contin; // ... contin:; } while (/* ... */); ``` For [for](for "cpp/language/for") and [range-for](range-for "cpp/language/range-for") loop, it acts as: ``` for (/* ... */) { // ... continue; // acts as goto contin; // ... contin:; } ``` ### Keywords [`continue`](../keyword/continue "cpp/keyword/continue"). ### Example ``` #include <iostream> int main() { for (int i = 0; i < 10; i++) { if (i != 5) continue; std::cout << i << " "; //this statement is skipped each time i!=5 } std::cout << '\n'; for (int j = 0; j < 2; j++) { for (int k = 0; k < 5; k++) { //only this loop is affected by continue if (k == 3) continue; std::cout << j << k << " "; //this statement is skipped each time k==3 } } } ``` Output: ``` 5 00 01 02 04 10 11 12 14 ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/continue "c/language/continue") for `continue` | cpp Function-try-block Function-try-block ================== Establishes an exception handler around the body of a function. ### Syntax The function-try-block is one of the alternative syntax forms for function-body, which is a part of [function definition](function "cpp/language/function"). | | | | | --- | --- | --- | | `try` ctor-initializer(optional) compound-statement handler-sequence | | | | | | | | --- | --- | --- | | ctor-initializer | - | member [initializer list](initializer_list "cpp/language/initializer list"), only allowed in constructors | | compound-statement | - | the brace-enclosed [sequence of statements](statements#Compound_statements "cpp/language/statements") that constitutes the body of a function | | handler-sequence | - | sequence of one or more [catch-clauses](try_catch "cpp/language/try catch") | ### Explanation A *function-try-block* associates a sequence of catch clauses with the entire function body, and with the [member initializer list](initializer_list "cpp/language/initializer list") (if used in a constructor) as well. Every exception thrown from any statement in the function body, or (for constructors) from any member or base constructor, or (for destructors) from any member or base destructor, transfers control to the handler-sequence the same way an exception thrown in a regular [try block](try_catch "cpp/language/try catch") would. ``` #include <iostream> #include <string> struct S { std::string m; S(const std::string& str, int idx) try : m(str, idx) { std::cout << "S(" << str << ", " << idx << ") constructed, m = " << m << '\n'; } catch(const std::exception& e) { std::cout << "S(" << str << ", " << idx << ") failed: " << e.what() << '\n'; } // implicit "throw;" here }; int main() { S s1{"ABC", 1}; // does not throw (index is in bounds) try { S s2{"ABC", 4}; // throws (out of bounds) } catch (std::exception& e) { std::cout << "S s2... raised an exception: " << e.what() << '\n'; } } ``` Before any catch clauses of a function-try-block on a constructor are entered, all fully-constructed members and bases have already been destroyed. | | | | --- | --- | | If the function-try-block is on a delegating constructor, which called a non-delegating constructor that completed successfully, but then the body of the delegating constructor throws, the destructor of this object will be completed before any catch clauses of the function-try-block are entered. | (since C++11) | Before any catch clauses of a function-try-block on a destructor are entered, all bases and non-variant members have already been destroyed. The behavior is undefined if the catch-clause of a function-try-block used on a constructor or a destructor accesses a base or a non-static member of the object. Every catch-clause in the function-try-block for a constructor must terminate by throwing an exception. If the control reaches the end of such handler, the current exception is automatically rethrown as if by `throw;`. The return statement is not allowed in any catch clause of a constructor's function-try-block. Reaching the end of a catch clause for a function-try-block on a destructor also automatically rethrows the current exception as if by `throw;`, but a return statement is allowed. For all other functions, reaching the end of a catch clause is equivalent to `return;` if the function's return type is (possibly cv-qualified) `void`, otherwise the behavior is undefined. ### Notes The primary purpose of function-try-blocks is to respond to an exception thrown from the member initializer list in a constructor by logging and rethrowing, modifying the exception object and rethrowing, throwing a different exception instead, or terminating the program. They are rarely used with destructors or with regular functions. Function-try-block does not catch the exceptions thrown by the copy/move constructors and the destructors of the function parameters passed by value: those exceptions are thrown in context of the caller. | | | | --- | --- | | Function-try-block of the top-level function of a thread does not catch the exceptions thrown from the constructors and destructors of [thread-local](storage_duration "cpp/language/storage duration") objects (except for the constructors of function-scoped thread-locals). | (since C++11) | Likewise, function-try-block of the [main() function](main_function "cpp/language/main function") does not catch the exceptions thrown from the constructors and destructors of [static](storage_duration "cpp/language/storage duration") objects (except for the constructors of function-local statics). [The scope](scope#Block_scope "cpp/language/scope") and lifetime of the function parameters (but not any objects declared in the function itself), extend to the end of the handler-sequence. ``` int f(int n = 2) try { ++n; // increments the function parameter throw n; } catch(...) { ++n; // n is in scope and still refers to the function parameter assert(n == 4); return n; } ``` ### 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 1167](https://cplusplus.github.io/CWG/issues/1167.html) | C++98 | it was unspecified whether a function-try-block on a destructorwill catch exceptions from a base or member destructor | such exceptions are caught | cpp Non-static member functions Non-static member functions =========================== A non-static member function is a function that is declared in a [member specification](class "cpp/language/class") of a class without a [`static`](static "cpp/language/static") or [`friend`](friend "cpp/language/friend") specifier. (see [static member functions](static#Static_member_functions "cpp/language/static") and [friend declaration](friend "cpp/language/friend") for the effect of those keywords). ``` class S { int mf1(); // non-static member function declaration void mf2() volatile, mf3() &&; // can have cv-qualifiers and/or a reference-qualifier // the declaration above is equivalent to two separate declarations: // void mf2() volatile; // void mf3() &&; int mf4() const { return data; } // can be defined inline virtual void mf5() final; // can be virtual, can use final/override S() : data(12) {} // constructors are member functions too int data; }; int S::mf1() { return 7; } // if not defined inline, has to be defined at namespace ``` [Constructors](constructor "cpp/language/constructor"), [destructors](destructor "cpp/language/destructor"), and [conversion functions](cast_operator "cpp/language/cast operator") use special syntaxes for their declarations. The rules described in this page may not apply to these functions. See their respective pages for details. ### Explanation Any [function declarations](function "cpp/language/function") are allowed, with additional syntax elements that are only available for non-static member functions: [pure-specifiers](abstract_class "cpp/language/abstract class"), cv-qualifiers, ref-qualifiers, [`final`](final "cpp/language/final") and [`override`](override "cpp/language/override") specifiers (since C++11), and [member initialization lists](initializer_list "cpp/language/initializer list"). A non-static member function of class `X` may be called. 1) For an object of type `X` using the class member access operator 2) For an object of a class [derived](derived_class "cpp/language/derived class") from `X` 3) Directly from within the body of a member function of `X` 4) Directly from within the body of a member function of a class derived from `X` Calling a non-static member function of class `X` on an object that is not of type `X`, or of a type derived from `X` invokes undefined behavior. Within the body of a non-static member function of `X`, any [id-expression](expressions "cpp/language/expressions") `e` (e.g. an identifier) that resolves to a non-type non-static member of `X` or of a base class of `X`, is transformed to a member access expression `(*this).e` (unless it's already a part of a member access expression). This does not occur in template definition context, so a name may have to be prefixed with `this->` explicitly to become [dependent](dependent_name "cpp/language/dependent name"). ``` struct S { int n; void f(); }; void S::f() { n = 1; // transformed to (*this).n = 1; } int main() { S s1, s2; s1.f(); // changes s1.n } ``` Within the body of a non-static member function of `X`, any unqualified-id that resolves to a static member, an enumerator or a nested type of `X` or of a base class of `X`, is transformed to the corresponding qualified-id: ``` struct S { static int n; void f(); }; void S::f() { n = 1; // transformed to S::n = 1; } int main() { S s1, s2; s1.f(); // changes S::n } ``` #### member functions with cv-qualifiers A non-static member function can be declared with a [cv-qualifier](cv "cpp/language/cv") sequence (`const`, `volatile`, or a combination of `const` and `volatile`), this sequence appears after the parameter list in the [function declaration](function "cpp/language/function"). Functions with different cv-qualifier sequences (or no sequence) have different types and so may overload each other. In the body of a function with a cv-qualifier sequence, `*this` is cv-qualified, e.g. in a member function with `const` qualifier, only other member functions with `const` qualifier may be called normally. (A member function without `const` qualifier may still be called if [`const_cast`](const_cast "cpp/language/const cast") is applied or through an access path that does not involve [`this`](this "cpp/language/this").). ``` #include <vector> struct Array { std::vector<int> data; Array(int sz) : data(sz) {} // const member function int operator[](int idx) const { // the this pointer has type const Array* return data[idx]; // transformed to (*this).data[idx]; } // non-const member function int& operator[](int idx) { // the this pointer has type Array* return data[idx]; // transformed to (*this).data[idx] } }; int main() { Array a(10); a[1] = 1; // OK: the type of a[1] is int& const Array ca(10); ca[1] = 2; // Error: the type of ca[1] is int } ``` | | | | --- | --- | | member functions with ref-qualifier A non-static member function can be declared with no ref-qualifier, with an lvalue ref-qualifier (the token `&` after the parameter list) or the rvalue ref-qualifier (the token `&&` after the parameter list). During [overload resolution](overload_resolution "cpp/language/overload resolution"), non-static member function with a cv-qualifier sequence of class X is treated as follows:* no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument * lvalue ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X * rvalue ref-qualifier: the implicit object parameter has type rvalue reference to cv-qualified X ``` #include <iostream> struct S { void f() & { std::cout << "lvalue\n"; } void f() && { std::cout << "rvalue\n"; } }; int main() { S s; s.f(); // prints "lvalue" std::move(s).f(); // prints "rvalue" S().f(); // prints "rvalue" } ``` Note: unlike cv-qualification, ref-qualification does not change the properties of the [`this`](this "cpp/language/this") pointer: within a rvalue ref-qualified function, `*this` remains an lvalue expression. | (since C++11) | #### Virtual and pure virtual functions A non-static member function may be declared *virtual* or *pure virtual*. See [virtual functions](virtual "cpp/language/virtual") and [abstract classes](abstract_class "cpp/language/abstract class") for details. | | | | --- | --- | | Explicit object parameter A non-static member function can be declared to take as its first parameter an explicit object parameter, denoted with the prefixed keyword `this`. ``` struct X { void foo(this X const& self, int i); // same as void foo(int i) const &; // void foo(int i) const &; // Error: already declared void bar(this X self, int i); // pass object by value: makes a copy of `*this` }; ``` For template member functions, explicit object parameter allows deduction of type and value category, this language feature is called "deducing `this`" ``` struct X { template<typename Self> void foo(this Self&&, int); }; struct D : X {}; void ex(X& x, D& d) { x.foo(1); // Self = X& move(x).foo(2); // Self = X d.foo(3); // Self = D& } ``` This makes it possible to deduplicate const- and non-const member functions, see [array subscript operator](operators#Array_subscript_operator "cpp/language/operators") for an example. Additionally, explicit object parameter deduces to the derived type, which simplifies [CRTP](crtp "cpp/language/crtp"): ``` // a CRTP trait struct add_postfix_increment { template <typename Self> auto operator++(this Self&& self, int) { auto tmp = self; // Self deduces to "some_type" ++self; return tmp; } }; struct some_type : add_postfix_increment { some_type& operator++() { ... } }; ``` Inside the body of a function with explicit object parameter, the `this` pointer cannot be used: all member access must be done through the first parameter, like in static member functions: ``` struct C { void bar(); void foo(this C c) { auto x = this; // error: no this bar(); // error: no implicit this-> c.bar(); // ok } }; ``` A pointer to a member function with explicit object parameter is an ordinary pointer to function, not a pointer to member: ``` struct Y { int f(int, int) const&; int g(this Y const&, int, int); }; auto pf = &Y::f; pf(y, 1, 2); // error: pointers to member functions are not callable (y.*pf)(1, 2); // ok std::invoke(pf, y, 1, 2); // ok auto pg = &Y::g; pg(y, 3, 4); // ok (y.*pg)(3, 4); // error: pg is not a pointer to member function std::invoke(pg, y, 3, 4); // ok ``` Member functions with an explicit object parameter cannot be static or virtual and they cannot have cv- or ref-qualifiers. | (since C++23) | #### Special member functions Some member functions are *special*: under certain circumstances they are defined by the compiler even if not defined by the user. They are: * [Default constructor](default_constructor "cpp/language/default constructor") * [Copy constructor](copy_constructor "cpp/language/copy constructor") | | | | --- | --- | | * [Move constructor](move_constructor "cpp/language/move constructor") | (since C++11) | * [Copy assignment operator](as_operator "cpp/language/as operator") | | | | --- | --- | | * [Move assignment operator](move_operator "cpp/language/move operator") | (since C++11) | * [Destructor](destructor "cpp/language/destructor") (until C++20)[Prospective destructor](destructor#Prospective_destructor "cpp/language/destructor") (since C++20) Special member functions along with the [comparison operators](default_comparisons "cpp/language/default comparisons") (since C++20) are the only functions that can be *defaulted*, that is, defined using `= default` instead of the function body (see their pages for details). ### Example ``` #include <iostream> #include <string> #include <utility> #include <exception> struct S { int data; // simple converting constructor (declaration) S(int val); // simple explicit constructor (declaration) explicit S(std::string str); // const member function (definition) virtual int getData() const { return data; } }; // definition of the constructor S::S(int val) : data(val) { std::cout << "ctor1 called, data = " << data << '\n'; } // this constructor has a catch clause S::S(std::string str) try : data(std::stoi(str)) { std::cout << "ctor2 called, data = " << data << '\n'; } catch(const std::exception&) { std::cout << "ctor2 failed, string was '" << str << "'\n"; throw; // ctor's catch clause should always rethrow } struct D : S { int data2; // constructor with a default argument D(int v1, int v2 = 11) : S(v1), data2(v2) {} // virtual member function int getData() const override { return data * data2; } // lvalue-only assignment operator D& operator=(D other) & { std::swap(other.data, data); std::swap(other.data2, data2); return *this; } }; int main() { D d1 = 1; S s2("2"); try { S s3("not a number"); } catch(const std::exception&) {} std::cout << s2.getData() << '\n'; D d2(3, 4); d2 = d1; // OK: assignment to lvalue // D(5) = d1; // ERROR: no suitable overload of operator= } ``` Output: ``` ctor1 called, data = 1 ctor2 called, data = 2 ctor2 failed, string was 'not a number' 2 ctor1 called, data = 3 ``` ### 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 194](https://cplusplus.github.io/CWG/issues/194.html) | C++98 | ambiguous whether a non-static member functioncould have the same name as the enclosing class name | explicit naming restriction added | ### See also * [classes](classes "cpp/language/classes") * [non-static data members](data_members "cpp/language/data members") * [static data members](static "cpp/language/static")
programming_docs
cpp Partial template specialization Partial template specialization =============================== Allows customizing class and variable (since C++14) templates for a given category of template arguments. ### Syntax | | | | | --- | --- | --- | | `template` `<` parameter-list `>` class-key class-head-name `<` argument-list `>` declaration | (1) | | | `template` `<` parameter-list `>` decl-specifier-seq declarator `<` argument-list `>` initializer(optional) | (2) | (since C++14) | where class-head-name identifies the name of a previously declared [class template](class_template "cpp/language/class template") and declarator identifies the name of a previously declared [variable template](variable_template "cpp/language/variable template") (since C++14). This declaration must be in the same [namespace](namespace "cpp/language/namespace") or, for [member templates](member_template "cpp/language/member template"), class scope as the primary template definition which it specializes . For example, ``` template<class T1, class T2, int I> class A {}; // primary template template<class T, int I> class A<T, T*, I> {}; // #1: partial specialization where T2 is a pointer to T1 template<class T, class T2, int I> class A<T*, T2, I> {}; // #2: partial specialization where T1 is a pointer template<class T> class A<int, T*, 5> {}; // #3: partial specialization where // T1 is int, I is 5, and T2 is a pointer template<class X, class T, int I> class A<X, T*, I> {}; // #4: partial specialization where T2 is a pointer ``` Examples of partial specializations in the standard library include `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)`, which has a partial specialization for array types. ### The argument list The following restrictions apply to the argument-list of a partial template specialization: 1) The argument list cannot be identical to the non-specialized argument list (it must specialize something): ``` template<class T1, class T2, int I> class B {}; // primary template template<class X, class Y, int N> class B<X, Y, N> {}; // error ``` | | | | --- | --- | | Moreover, the specialization has to be more specialized than the primary template. ``` template<int N, typename T1, typename... Ts> struct B; template<typename... Ts> struct B<0, Ts...> {}; // Error: not more specialized ``` | (since C++11) | 2) Default arguments cannot appear in the argument list 3) If any argument is a pack expansion, it must be the last argument in the list 4) Non-type argument expressions can use template parameters as long as the parameter appears at least once outside a [non-deduced context](template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") (note that only clang supports this feature currently): ``` template<int I, int J> struct A {}; template<int I> struct A<I+5, I*2> {}; // error, I is not deducible template<int I, int J, int K> struct B {}; template<int I> struct B<I, I*2, 2> {}; // OK: first parameter is deducible ``` 5) Non-type template argument cannot specialize a template parameter whose type depends on a parameter of the specialization: ``` template<class T, T t> struct C {}; // primary template template<class T> struct C<T, 1>; // error: type of the argument 1 is T, // which depends on the parameter T template<int X, int (*array_ptr)[X]> class B {}; // primary template int array[5]; template<int X> class B<X, &array> {}; // error: type of the argument &array is // int(*)[X], which depends on the parameter X ``` ### Name lookup Partial template specializations are not found by name lookup. Only if the primary template is found by name lookup, its partial specializations are considered. In particular, a using declaration that makes a primary template visible, makes partial specializations visible as well: ``` namespace N { template<class T1, class T2> class Z {}; // primary template } using N::Z; // refers to the primary template namespace N { template<class T> class Z<T, T*> {}; // partial specialization } Z<int, int*> z; // name lookup finds N::Z (the primary template), // the partial specialization with T = int is then used ``` ### Partial ordering When a class or variable (since C++14) template is instantiated, and there are partial specializations available, the compiler has to decide if the primary template is going to be used or one of its partial specializations. 1) If only one specialization matches the template arguments, that specialization is used 2) If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique (if it is not unique, the program cannot be compiled) 3) If no specializations match, the primary template is used ``` // given the template A as defined above A<int, int, 1> a1; // no specializations match, uses primary template A<int, int*, 1> a2; // uses partial specialization #1 (T=int, I=1) A<int, char*, 5> a3; // uses partial specialization #3, (T=char) A<int, char*, 1> a4; // uses partial specialization #4, (X=int, T=char, I=1) A<int*, int*, 2> a5; // error: matches #2 (T=int, T2=int*, I=2) // matches #4 (X=int*, T=int, I=2) // neither one is more specialized than the other ``` Informally "A is more specialized than B" means "A accepts a subset of the types that B accepts". Formally, to establish more-specialized-than relationship between partial specializations, each is first converted to a fictitious function template as follows: * the first function template has the same template parameters as the first partial specialization and has just one function parameter, whose type is a class template specialization with all the template arguments from the first partial specialization * the second function template has the same template parameters as the second partial specialization and has just one function parameter whose type is a class template specialization with all the template arguments from the second partial specialization. The function templates are then ranked as if for [function template overloading](function_template#Function_template_overloading "cpp/language/function template"). ``` template<int I, int J, class T> struct X {}; // primary template template<int I, int J> struct X<I, J, int> { static const int s = 1; }; // partial specialization #1 // fictitious function template for #1 is // template<int I, int J> void f(X<I, J, int>); #A template<int I> struct X<I, I, int> { static const int s = 2; }; // partial specialization #2 // fictitious function template for #2 is // template<int I> void f(X<I, I, int>); #B int main() { X<2, 2, int> x; // both #1 and #2 match // partial ordering for function templates: // #A from #B: void(X<I,J,int>) from void(X<U1, U1, int>): deduction OK // #B from #A: void(X<I,I,int>) from void(X<U1, U2, int>): deduction fails // #B is more specialized // #2 is the specialization that is instantiated std::cout << x.s << '\n'; // prints 2 } ``` ### Members of partial specializations The template parameter list and the template argument list of a member of a partial specialization must match the parameter list and the argument list of the partial specialization. Just like with members of primary templates, they only need to be defined if used in the program. Members of partial specializations are not related to the members of the primary template. Explicit (full) specialization of a member of a partial specialization is declared the same way as an explicit specialization of the primary template. ``` template<class T, int I> // primary template struct A { void f(); // member declaration }; template<class T, int I> void A<T, I>::f() {} // primary template member definition // partial specialization template<class T> struct A<T, 2> { void f(); void g(); void h(); }; // member of partial specialization template<class T> void A<T, 2>::g() {} // explicit (full) specialization // of a member of partial specialization template<> void A<char, 2>::h() {} int main() { A<char, 0> a0; A<char, 2> a2; a0.f(); // OK, uses primary template’s member definition a2.g(); // OK, uses partial specialization's member definition a2.h(); // OK, uses fully-specialized definition of // the member of a partial specialization a2.f(); // error: no definition of f() in the partial // specialization A<T,2> (the primary template is not used) } ``` If a primary template is a member of another class template, its partial specializations are members of the enclosing class template. If the enclosing template is instantiated, the declaration of each member partial specialization is instantiated as well (the same way declarations, but not definitions, of all other members of a template are instantiated). If the primary member template is explicitly (fully) specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template. If a partial specialization of the member template is explicitly specialized for a given (implicit) specialization of the enclosing class template, the primary member template and its other partial specializations are still considered for this specialization of the enclosing class template. ``` template<class T> struct A // enclosing class template { template<class T2> struct B {}; // primary member template template<class T2> struct B<T2*> {}; // partial specialization of member template }; template<> template<class T2> struct A<short>::B {}; // full specialization of primary member template // (will ignore the partial) A<char>::B<int*> abcip; // uses partial specialization T2=int A<short>::B<int*> absip; // uses full specialization of the primary (ignores partial) A<char>::B<int> abci; // uses primary ``` ### 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 1315](https://cplusplus.github.io/CWG/issues/1315.html) | C++98 | template parameter could not be used in non-typetemplate arguments other than id-expressions | expressions ok as long as deducible | | [CWG 1495](https://cplusplus.github.io/CWG/issues/1495.html) | C++11 | the specification was unclear when involving parameter pack | the specialization shall be more specialized | cpp Union declaration Union declaration ================= A union is a special class type that can hold only one of its non-static [data members](data_members "cpp/language/data members") at a time. The class specifier for a union declaration is similar to [class or struct](class "cpp/language/class") declaration: | | | | | --- | --- | --- | | `union` attr class-head-name `{` member-specification `}` | | | | | | | | --- | --- | --- | | attr | - | (since C++11) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | class-head-name | - | the name of the union that's being defined. Optionally prepended by nested-name-specifier (sequence of names and scope-resolution operators, ending with scope-resolution operator). The name may be omitted, in which case the union is *unnamed* | | member-specification | - | list of access specifiers, member object and member function declarations and definitions. | A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class. A union cannot have non-static data members of reference types. | | | | --- | --- | | Unions cannot contain a non-static data member with a non-trivial special member function ([copy constructor](copy_constructor "cpp/language/copy constructor"), [copy-assignment](copy_assignment "cpp/language/copy assignment") operator, or [destructor](destructor "cpp/language/destructor")). | (until C++11) | | If a union contains a non-static data member with a non-trivial special member function ([copy](copy_constructor "cpp/language/copy constructor")/[move](move_constructor "cpp/language/move constructor") constructor, [copy](copy_assignment "cpp/language/copy assignment")/[move](move_assignment "cpp/language/move assignment") assignment, or [destructor](destructor "cpp/language/destructor")), that function is deleted by default in the union and needs to be defined explicitly by the programmer. If a union contains a non-static data member with a non-trivial [default constructor](default_constructor "cpp/language/default constructor"), the default constructor of the union is deleted by default unless a [variant member](#Union-like_classes) of the union has a default member initializer . At most one [variant member](#Union-like_classes) can have a [default member initializer](data_members#Member_initialization "cpp/language/data members"). | (since C++11) | Just like in [struct](classes "cpp/language/classes") declaration, the default member access in a union is [public](access "cpp/language/access"). ### Explanation The union is only as big as necessary to hold its largest data member. The other data members are allocated in the same bytes as part of that largest member. The details of that allocation are implementation-defined but all non-static data members will have the same address (since C++14). It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union. ``` #include <iostream> #include <cstdint> union S { std::int32_t n; // occupies 4 bytes std::uint16_t s[2]; // occupies 4 bytes std::uint8_t c; // occupies 1 byte }; // the whole union occupies 4 bytes int main() { S s = {0x12345678}; // initializes the first member, s.n is now the active member // at this point, reading from s.s or s.c is undefined behavior std::cout << std::hex << "s.n = " << s.n << '\n'; s.s[0] = 0x0011; // s.s is now the active member // at this point, reading from n or c is UB but most compilers define it std::cout << "s.c is now " << +s.c << '\n' // 11 or 00, depending on platform << "s.n is now " << s.n << '\n'; // 12340011 or 00115678 } ``` Possible output: ``` s.n = 12345678 s.c is now 0 s.n is now 115678 ``` Each member is allocated as if it is the only member of the class. | | | | --- | --- | | If members of a union are classes with user-defined constructors and destructors, to switch the active member, explicit destructor and placement new are generally needed: ``` #include <iostream> #include <string> #include <vector> union S { std::string str; std::vector<int> vec; ~S() {} // needs to know which member is active, only possible in union-like class }; // the whole union occupies max(sizeof(string), sizeof(vector<int>)) int main() { S s = {"Hello, world"}; // at this point, reading from s.vec is undefined behavior std::cout << "s.str = " << s.str << '\n'; s.str.~basic_string(); new (&s.vec) std::vector<int>; // now, s.vec is the active member of the union s.vec.push_back(10); std::cout << s.vec.size() << '\n'; s.vec.~vector(); } ``` Output: ``` s.str = Hello, world 1 ``` | (since C++11) | If two union members are [standard-layout](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") types, it's well-defined to examine their common subsequence on any compiler. #### Member lifetime The [lifetime](lifetime "cpp/language/lifetime") of a union member begins when the member is made active. If another member was active previously, its lifetime ends. When active member of a union is switched by an assignment expression of the form `E1 = E2` that uses either the built-in assignment operator or a trivial assignment operator, for each union member X that appears in the member access and array subscript subexpressions of `E1` that is not a class with non-trivial or deleted default constructors, if modification of X would have undefined behavior under type aliasing rules, an object of the type of X is implicitly created in the nominated storage; no initialization is performed and the beginning of its lifetime is sequenced after the value computation of the left and right operands and before the assignment. ``` union A { int x; int y[4]; }; struct B { A a; }; union C { B b; int k; }; int f() { C c; // does not start lifetime of any union member c.b.a.y[3] = 4; // OK: "c.b.a.y[3]", names union members c.b and c.b.a.y; // This creates objects to hold union members c.b and c.b.a.y return c.b.a.y[3]; // OK: c.b.a.y refers to newly created object } struct X { const int a; int b; }; union Y { X x; int k; }; void g() { Y y = { { 1, 2 } }; // OK, y.x is active union member int n = y.x.a; y.k = 4; // OK: ends lifetime of y.x, y.k is active member of union y.x.b = n; // undefined behavior: y.x.b modified outside its lifetime, // "y.x.b" names y.x, but X's default constructor is deleted, // so union member y.x's lifetime does not implicitly start } ``` Trivial move constructor, move assignment operator, (since C++11)copy constructor and copy assignment operator of union types copy object representations. If the source and the destination are not the same object, these special member functions start lifetime of every object (except for objects that are neither subobjects of the destination nor of [implicit-lifetime type](lifetime#Implicit-lifetime_types "cpp/language/lifetime")) nested in the destination corresponding to the one nested in the source before the copy is performed. Otherwise, they do nothing. Two union objects have the same corresponding active member (if any) after construction or assignment via trivial special functions. #### Anonymous unions An *anonymous union* is an unnamed union definition that does not simultaneously define any variables (including objects of the union type, references, or pointers to the union). | | | | | --- | --- | --- | | `union` `{` member-specification `}` `;` | | | Anonymous unions have further restrictions: they cannot have member functions, cannot have static data members, and all their data members must be public. The only declarations allowed are non-static data members and [`static_assert`](static_assert "cpp/language/static assert") declarations (since C++11). Members of an anonymous union are injected in the enclosing scope (and must not conflict with other names declared there). ``` int main() { union { int a; const char* p; }; a = 1; p = "Jennifer"; } ``` Namespace-scope anonymous unions must be declared static unless they appear in an unnamed namespace. #### Union-like classes A *union-like class* is either a union, or a (non-union) class that has at least one anonymous union as a member. A union-like class has a set of *variant members*: * the non-static data members of its member anonymous unions; * in addition, if the union-like class is a union, its non-static data members that are not anonymous unions. Union-like classes can be used to implement [tagged unions](https://en.wikipedia.org/wiki/Tagged_union "enwiki:Tagged union"). ``` #include <iostream> // S has one non-static data member (tag), three enumerator members (CHAR, INT, DOUBLE), // and three variant members (c, i, d) struct S { enum{CHAR, INT, DOUBLE} tag; union { char c; int i; double d; }; }; void print_s(const S& s) { switch(s.tag) { case S::CHAR: std::cout << s.c << '\n'; break; case S::INT: std::cout << s.i << '\n'; break; case S::DOUBLE: std::cout << s.d << '\n'; break; } } int main() { S s = {S::CHAR, 'a'}; print_s(s); s.tag = S::INT; s.i = 123; print_s(s); } ``` Output: ``` a 123 ``` | | | | --- | --- | | The C++ standard library includes `[std::variant](../utility/variant "cpp/utility/variant")`, which can replace many uses of unions and union-like classes. The example above can be re-written as. ``` #include <variant> #include <iostream> int main() { std::variant<char, int, double> s = 'a'; std::visit([](auto x){ std::cout << x << '\n';}, s); s = 123; std::visit([](auto x){ std::cout << x << '\n';}, s); } ``` Output: ``` a 123 ``` | (since C++17) | ### 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 1940](https://cplusplus.github.io/CWG/issues/1940.html) | C++11 | anonymous unions only allowed non-static data members | `static_assert` also allowed | ### See also | | | | --- | --- | | [variant](../utility/variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [C documentation](https://en.cppreference.com/w/c/language/union "c/language/union") for Union declaration |
programming_docs