【发布时间】:2013-11-16 23:52:59
【问题描述】:
- 返回一个右值——促进移动——如果移动构造函数是
noexcept或者如果没有复制构造函数(仅移动类型) - 返回左值 -- 强制复制 -- 否则
我发现这相当令人惊讶,因为具有 throwing move-ctor 的 move-only 类型仍将由使用 move_if_noexcept 的代码调用此 move-ctor。
是否对此给出了详尽的理由? (可能直接或者N2983的行之间?)
不编译代码而不是仍然不得不面对不可恢复的移动场景不是更好吗? N2983 中给出的vector 示例很好:
void reserve(size_type n)
{
... ...
new ((void*)(new_begin + i)) value_type( std::move_if_noexcept( (*this)[i]) ) );
}
catch(...)
{
while (i > 0) // clean up new elements
(new_begin + --i)->~value_type();
this->deallocate( new_begin ); // release storage
throw;
}
*!* // -------- irreversible mutation starts here -----------
this->deallocate( this->begin_ );
this->begin_ = new_begin;
... ...
标记行中给出的注释实际上是错误的 - 对于可以引发移动构造的仅移动类型,当我们将旧元素移动到它们的新位置时, - 可能失败 - 不可逆的突变实际上已经开始了。
简单地看一下,我会说只能投掷的类型不能放入向量中,但也许不应该?
【问题讨论】:
-
在向量修饰符中有一个用于只移动类型的特殊段落(不是擦除,而是例如
insert):“如果非@的移动构造函数抛出异常987654330@T,效果未指定。” 另请注意noexcept(false)不保证函数会抛出。
标签: c++ move-semantics noexcept