【发布时间】:2020-10-01 17:04:12
【问题描述】:
考虑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; }
};
由于在 C++17 中保证 copy/move-elision,我们可以拥有:
auto getA() { return AA(10); }
问题是:如何定义getGoodA,如果它返回good,它将转发getA,否则会抛出异常?有可能吗?
auto getGoodA()
{
auto got = getA();
if (got.good()) return got; // FAILS! Move is needed.
throw std::runtime_error("BAD");
}
【问题讨论】:
-
如果您反转支票会发生什么?
if (!got.good()) throw std::runtime_error("BAD"); return got;? -
其实没什么。仍然需要移动构造函数。
-
@Vahagn 希望这个问题在 C++23 中会消失:wg21.link/p2025
标签: c++ c++17 copy-elision noncopyable