【发布时间】:2020-06-09 19:55:34
【问题描述】:
我有这个代码:
#include <string>
class A {
public:
// A(A const &) = delete; // Code fails if this is uncommented.
explicit A(int);
explicit A(::std::string const &);
private:
::std::string myname_;
int foo_;
};
static constexpr bool which = false;
A test(::std::string const &s, int a)
{
if constexpr (which) {
A x{a};
return x;
} else {
A y{s};
return y;
}
}
如果A 具有已删除的复制构造函数,则此代码将失败。但是,考虑到带有if constexpr 的函数的返回类型规则,编译器似乎应该在这里应用RVO。
除了它是语言规范中被忽视的情况之外,还有其他原因吗?
【问题讨论】:
-
在什么编译器上这个“失败”?
-
@aschepler - 如果您取消注释删除移动构造函数,它将失败。它适用于 gcc 和 clang。
-
if constexpr仅丢弃模板实例化中的代码。在非模板代码中,两个分支都被保留。请参阅此related question 或此one。 -
@1201ProgramAlarm - 这很有趣。谢谢。