首页 > 解决方案 > 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。

除了它是语言规范中被忽视的情况之外,是否还有其他原因?

标签: c++c++17rvo

解决方案


这无关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
}

推荐阅读