Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::is_nothrow_copy_constructible — non-throwing copy construction

This <type_traits> trait checks at compile time whether constructing T from const T& is valid and known not to throw. std::is_nothrow_copy_constructible<T>::value and std::is_nothrow_copy_constructible_v<T> expose the same bool result.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <type_traits>

std::is_nothrow_copy_constructible<T>::value
std::is_nothrow_copy_constructible_v<T>

std::is_nothrow_copy_constructible<T> is a class template from <type_traits> whose ::value member is a constant of type bool. std::is_nothrow_copy_constructible_v<T> is a variable template exposing the same value. The result can be used in static_assert and if constexpr.

For a type T to which a reference can be formed, the result equals std::is_nothrow_constructible_v<T, const T&>: direct initialization must be valid and known not to throw. For other types, the result is false. The test does not execute the constructor; an empty constructor declared noexcept(false) still produces false.

This tests construction, not assignment or trivial copying. If overload resolution for construction from const T& selects a deleted or inaccessible constructor, the result is false. For example, if a class T has a deleted T(T&) and a public T(const T&) declared noexcept, overload resolution selects the public constructor. That alone does not guarantee true: a deleted or inaccessible destructor makes the hypothetical variable definition used by the test ill-formed, so the result is false. For reference types, it checks reference binding rather than copying the referred-to object; for example, std::is_nothrow_copy_constructible_v<int&> is true.

T must be a complete type, possibly cv-qualified void, or an array of unknown bound. Do not use this trait to inspect a forward-declared class before its definition. Do not add your own specializations of these templates: doing so gives the program undefined behavior.

Examples

#include <iostream>
#include <type_traits>

struct Safe {
    Safe(const Safe&) noexcept {}
};

struct Risky {
    Risky(const Risky&) noexcept(false) {}
};

struct Blocked {
    Blocked(const Blocked&) = delete;
};

static_assert(std::is_nothrow_copy_constructible<Safe>::value);
static_assert(!std::is_nothrow_copy_constructible_v<Risky>);
static_assert(!std::is_nothrow_copy_constructible_v<Blocked>);

int main() {
    std::cout << std::boolalpha
              << std::is_nothrow_copy_constructible<Safe>::value << '\n'
              << std::is_nothrow_copy_constructible_v<Risky> << '\n'
              << std::is_nothrow_copy_constructible_v<Blocked> << '\n';
}

Result

true
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources