std::is_copy_constructible, std::is_trivially_copy_constructible, std::is_nothrow_copy_constructible
来自cppreference.com
在标头 <type_traits> 定义 | ||
template<class T > struct is_copy_constructible; | (1) | (C++11 起) |
template<class T > struct is_trivially_copy_constructible; | (2) | (C++11 起) |
template<class T > struct is_nothrow_copy_constructible; | (3) | (C++11 起) |
类型特征 | 成员常量 value 的值 | |
---|---|---|
T 是可引用类型 | T 不是可引用类型 | |
(1) | std::is_constructible<T, const T&>::value | false |
(2) | std::is_trivially_constructible<T, const T&>::value | |
(3) | std::is_nothrow_constructible<T, const T&>::value |
如果 T
不是完整类型,(可有 cv 限定的)void 或未知边界数组,那么行为未定义。
如果上述模板的实例化直接或间接地依赖于不完整类型,并且假设在该类型完整的情况下实例化就会产生不同的结果,那么行为未定义。
如果程序添加了此页面上描述的任何模板的特化,那么行为未定义。
目录 |
[编辑]辅助变量模板
template<class T > inlineconstexprbool is_copy_constructible_v = | (C++17 起) | |
template<class T > inlineconstexprbool is_trivially_copy_constructible_v = | (C++17 起) | |
template<class T > inlineconstexprbool is_nothrow_copy_constructible_v = | (C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] | 如果 T 可复制构造那么是 true,否则是 false(公开静态成员常量) |
成员函数
operator bool | 将对象转换到 bool,返回 value (公开成员函数) |
operator() (C++14) | 返回 value (公开成员函数) |
成员类型
类型 | 定义 |
value_type | bool |
type | std::integral_constant<bool, value> |
[编辑]可能的实现
template<class T>struct is_copy_constructible :std::is_constructible<T, typenamestd::add_lvalue_reference<typenamestd::add_const<T>::type>::type>{}; template<class T>struct is_trivially_copy_constructible :std::is_trivially_constructible<T, typenamestd::add_lvalue_reference<typenamestd::add_const<T>::type>::type>{}; template<class T>struct is_nothrow_copy_constructible :std::is_nothrow_constructible<T, typenamestd::add_lvalue_reference<typenamestd::add_const<T>::type>::type>{}; |
[编辑]注解
多数实现中,is_nothrow_copy_constructible
也检查析构函数是否抛出,因为它相当于 noexcept(T(arg))。同样的情况适用于 is_trivially_copy_constructible
,它在这些实现中也要求析构函数平凡:GCC 漏洞 51452、LWG 问题 2116。
[编辑]示例
运行此代码
#include <string>#include <type_traits> struct S1 {std::string str;// 成员拥有非平凡复制构造函数}; static_assert(std::is_copy_constructible_v<S1>); static_assert(!std::is_trivially_copy_constructible_v<S1>); struct S2 {int n; Ex2(const Ex2&)=default;// 平凡且不抛出}; static_assert(std::is_trivially_copy_constructible_v<S2>); static_assert(std::is_nothrow_copy_constructible_v<S2>); struct S3 { S3(const S3&)= delete;// 显式弃置}; static_assert(!std::is_copy_constructible_v<S3>); struct S4 { S4(S4&){};// 无法绑定 const,因而不是可复制构造}; static_assert(!std::is_copy_constructible_v<S4>); int main(){}
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2196 | C++11 | 无法组成 const T& 时的行为不明确 | 此时产生的值是 false |
[编辑]参阅
(C++11)(C++11)(C++11) | 检查类型是否带有针对特定实参的构造函数 (类模板) |
检查类型是否有默认构造函数 (类模板) | |
(C++11)(C++11)(C++11) | 检查类型是否能从右值引用构造 (类模板) |
(C++20) | 指定能复制构造和移动构造一个类型的对象 (概念) |