c++ - constexpr if 和返回值优化
问题描述
我有这个代码:
#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。
除了它是语言规范中被忽视的情况之外,是否还有其他原因?
解决方案
这无关if constexpr
简单地说,这段代码是不允许编译的:
class A {
public:
A(A const &) = delete;
explicit A(int);
};
A test(int a)
{
A x{a};
return x; // <-- error call to a deleted constructor `A(A const &) = delete;`
}
您正在考虑的 C++17 中的更改与临时实现有关,并且不适用于 NRVO,因为x
它不是纯右值。
例如,这段代码在 C++17 之前是非法的,现在是允许的:
A test(int a)
{
return A{a}; // legal since C++17
}
推荐阅读
- javascript - HTMLButtonElement.onclick 处未捕获的 ReferenceError
- triggers - 用户 mariadb 的特定主机
- python - 在 Azure DevOps 中使用 POS 标记器
- python - 使用转换器 BertModel 和 BertTokenizer 的向量表示不一致
- python - 在 '\n' 之后在 QLabel 中使用 HTML将不起作用
- php - 当网站被 iframe 调用时,会话不起作用
- javascript - 在平面列表中的项目旁边对齐标题?
- kubernetes - Airflow - 异步 pod lauch
- postgresql - 使用 psql 和 typeorm 过滤
- r - 使用 restrserve 记录错误