gpt4 book ai didi

c++ - 用检查复制/移动省略

转载 作者:行者123 更新时间:2023-12-01 14:47:37 24 4
gpt4 key购买 nike

考虑this .有一个不可复制、不可移动的类,并且为它定义了一些谓词:

struct AA
{
AA(AA const& otehr) = delete;
AA(AA && otehr) = delete;
AA& operator = (AA const& otehr) = delete;
AA& operator = (AA && otehr) = delete;

AA(int something) { }

bool good() const { return false; }
};

因为保证 copy/move-elision在 C++17 中,我们可以有:
auto getA() { return AA(10); }

问题是:如何定义 getGoodA , 这将转发 getA如果它返回 good否则会抛出异常?有可能吗?
auto getGoodA()
{
auto got = getA();
if (got.good()) return got; // FAILS! Move is needed.
throw std::runtime_error("BAD");
}

最佳答案

如果我们在 C++20 中进行了契约(Contract)检查,您将能够编写如下内容:

auto getGoodA(int i) [[post aa: aa.good()]] {
return getA(i);
}

(至少我是这么认为的——我对 aa 返回伪变量的类型并不完全清楚;它需要是对其返回位置中返回对象的引用。)不幸的是合约是 removed from C++20所以我们还需要一段时间才能写出这篇文章。

假设您无法修改 getA ,目前唯一的方法是从 getGoodA 返回一个包装类.显而易见的解决方案是 unique_ptr ,但我们实际上并不需要执行堆分配;延迟构造的包装器将 do just as well :
#include <cstddef>
#include <new>
struct BB {
alignas(AA) std::byte buf[sizeof(AA)];
template<class F, class G> BB(F f, G g) { g(*new (buf) AA{f()}); }
BB(BB&&) = delete;
~BB() { reinterpret_cast<AA&>(buf).~AA(); }
operator AA&() { return reinterpret_cast<AA&>(buf); }
operator AA const&() const { return reinterpret_cast<AA const&>(buf); }
};
auto getGoodA(int i) {
return BB{
[&] { return getA(i); },
[&](AA& aa) { if (!aa.good()) throw (struct bad**){}; }};
}

这里我给了 BB一个引用风格的界面,让你写 AA& aa = getGoodA(i) , 但你同样可以给它一个指针样式的接口(interface)( operator*operator-> ),甚至复制 AA 的接口(interface).

关于c++ - 用检查复制/移动省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334793/

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