移动std :: runtime_error的构造函数 [英] move constructor for std::runtime_error
问题描述
为什么 std :: runtime_error
不提供接受 std :: string&&
的构造函数?查看 std :: string
,它有一个移动构造函数,但 noexcept
规范仅适用于C ++ 14,而不是C ++ 11。
显式的runtime_error()是一个错误, string&&&&;);
<$ p
<$> $ b
事实证明,符合C ++ 11的 runtime_error
不会在内部存储 std :: string
。原因是 runtime_error
的副本成员不能抛出异常。否则,当编译器在抛出异常对象的过程中复制异常对象时,错误的异常可能会被抛出。
这意味着 runtime_error
需要存储一个不可变引用计数字符串。但是C ++ 11违反了 std :: string
的COW实现。 std :: string
的实现已移至短字符串优化,如果字符串的长度超出短限制,则必须在复制构造上分配。并且用于构造 runtime_error
的字符串的长度没有限制。
有效的C ++ 11 (和forward)包含两个字符串实现:
-
std :: string $ c $
-
std :: runtime_error
:这是(或持有)不可变引用计数字符串。
和
显式runtime_error(string&&&);
type 1字符串到type 2字符串。
Why does std::runtime_error
not provide a constructor accepting an std::string&&
? Looking at the constructors for std::string
, it has a move constructor, but the noexcept
specification is only there for C++14, not C++11. Was this a mistake, a deadline that was missed or am I missing something?
explicit runtime_error(string&&);
does not exist simply because it would not provide any optimization.
As it turns out, a C++11-conforming runtime_error
does not internally store a std::string
. The reason is that the copy members of runtime_error
must not throw exceptions. Otherwise the wrong exception could get thrown when the compiler copies the exception object in the process of throwing it.
This implies that runtime_error
needs to store a non-mutable reference counted string. However C++11 outlaws the COW-implementation for std::string
. Implementations of std::string
have moved to a "short-string-optimization" which must allocate on copy construction if the length of the string is beyond the "short limit". And there is no limit on the length of strings used to construct a runtime_error
.
So effectively C++11 (and forward) contains two implementations of strings:
std::string
: This is typically a short-string-optimized type with a copy constructor and copy assignment that is capable of throwing exceptions.std::runtime_error
: This is (or holds) an immutable reference-counted string. This will never throw on copy construction or copy assignment.
And
explicit runtime_error(string&&);
can never (efficiently) transfer resources from the "type 1" string to the "type 2" string.
这篇关于移动std :: runtime_error的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!