gpt4 book ai didi

c++ - 为什么允许此举?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:01 24 4
gpt4 key购买 nike

vector 在调整大小时将尝试使用 move 语义将对象从旧数组 move 到新数组。但是如果 vector 中的模板化对象不支持不抛出 noexcept move 构造函数然后它将恢复使用复制构造,以便 strong exception guarantee被保留下来。

但是当我尝试这样做时:

#include <vector>

class X
{
public:
// Needs default constructor
X() {}

// Copy operations disabled.
X(X const&) = delete;
X& operator=(X const&) = delete;

X(X&&) // throwable move constructor
{}
X& operator=(X&&) // throwable move assignment.
{return *this;}
};

int main()
{
// Vector of Size zero
std::vector<X> data;

// Vector of Size ten.
// Since the move constructor can potentially throw
// We have to copy elements when we do a resize
//
// But X has a disabled copy semantics
// Thus I would expect a compile time error here.
data.resize(10);
}

此编译没有错误或警告:

> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
> g++ -std=c++11 test.cpp
>

最佳答案

没有为具有抛出 move 构造函数的不可复制元素提供强异常安全保证。

[vector.capacity]/p12-14(强调我的):

void resize(size_type sz); 

12 Effects: If sz <= size(), equivalent to calling pop_back() size() - sz times. If size() < sz, appends sz - size() default-inserted elements to the sequence.

13 Requires: T shall be MoveInsertable and DefaultInsertable into *this.

14 Remarks: If an exception is thrown other than by the move constructor of a non-CopyInsertable T there are no effects.

请注意,这不需要 T成为CopyInsertable .

在内部,实现可能使用 std::move_if_noexcept ,尽管名称如此,但实际上是“如果没有异常(exception)或如果不可复制则 move ”。

关于c++ - 为什么允许此举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28227959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com