在编译时填充 std::array 和 const_cast 可能的未定义行为

Filling a std::array at compile time and possible undefined behaviour with const_cast

已知 std::array::operator[] 因为 C++14 是 constexpr,请参见下面的声明:

constexpr const_reference operator[]( size_type pos ) const; 

不过,也是const合格的。如果您想使用 std::array 的下标运算符以便在编译时为数组赋值,这会产生影响。例如考虑以下用户文字:

template<typename T, int N>
struct FooLiteral {
  std::array<T, N> arr;
  constexpr FooLiteral() : arr {} { for(int i(0); i < N; ++i) arr[i] = T{42 + i}; }
};

如果您尝试声明 FooLiteral 类型的 constexpr 变量,上述代码将无法编译。这是因为重载解析规则将数组下标运算符的非 const 限定、非 constexpr 重载限定为更好的匹配。因此,编译器会抱怨调用非 constexpr 函数。

Live Demo

我无法弄清楚委员会将此重载声明为 const 符合 C++14 资格的原因是什么,但似乎人们注意到了其中的含义,并且还有一项提案 p0107R0 在即将到来的 C++17 中解决这个问题。

对于 C++14,我很自然地要克服这个问题,以某种方式破解表达式,以唤起正确的下标运算符。我所做的是:

template<typename T, int N>
struct FooLiteral {
  std::array<T, N> arr;
  constexpr FooLiteral() : arr {} { 
    for(int i(0); i < N; ++i) {
      const_cast<T&>(static_cast<const std::array<T, N>&>(arr)[i]) = T{42 + i};
    }
  }
};

Live Demo

也就是说,我将数组转换为 const 引用以引发正确的下标运算符重载,然后我 const_cast 将重载下标运算符的返回对象 T& 以移除它的常量性并能够分配给它。

这很好用,但我知道 const_cast 应该谨慎使用,坦率地说,我对这个 hack 是否会导致未定义的行为有重新考虑。

直觉上,我不认为有问题,因为这个 const_cast 发生在编译时初始化因此,我想不出在这个状态下可能出现的含义。

但是是这样吗,或者我错了,这将 UB 引入程序?

问:

有人可以证明这是不是 UB 吗?

这里没有 UB,你的成员 arr 不是常量,你可以 "play" 随意 const(好吧,你明白我的意思)

如果您的成员 常量表达式,那么您将拥有 UB,因为您已经在初始化器列表中进行了初始化并且 post 创建了您不允许假设它具有可变值。在初始化列表中做任何你想做的元编程。

据我所知,这不是未定义的行为。提案 that added constexpr to operator[] happened before the changes that removed the implicit const from constexpr member functions。所以看起来他们只是添加了 constexpr 而没有考虑是否需要保留 const.

我们可以从 Relaxing constraints on constexpr functions 的早期版本中看到,它说明了以下关于在常量表达式中改变文字的内容:

Objects created within a constant expression can be modified within the evalution of that constant expression (including the evaluation of any constexpr function calls it makes), until the evaluation of that constant expression ends, or the lifetime of the object ends, whichever happens sooner. They cannot be modified by later constant expression evaluations. [...]

This approach allows arbitrary variable mutations within an evaluation, while still preserving the essential property that constant expression evaluation is independent of the mutable global state of the program. Thus a constant expression evaluates to the same value no matter when it is evaluated, excepting when the value is unspecified (for instance, floating-point calculations can give different results and, with these changes, differing orders of evaluation can also give different results).

我们可以看到我引用的早期提案指出了 const_cast 黑客攻击,它说:

In C++11, constexpr member functions are implicitly const. This creates problems for literal class types which desire to be usable both within constant expressions and outside them:

[...]

Several alternatives have been suggested to resolve this problem:

  • Accept the status quo, and require users to work around this minor embarrassment with const_cast.

不是问题的直接答案,但希望有用。

std::array 困扰了一段时间后,我决定看看是否可以仅使用用户代码来做得更好。

事实证明可以:

#include <iostream>
#include <utility>
#include <cassert>
#include <string>
#include <vector>
#include <iomanip>

// a fully constexpr version of array that allows incomplete
// construction
template<size_t N, class T>
struct better_array
{
    // public constructor defers to internal one for
    // conditional handling of missing arguments
    constexpr better_array(std::initializer_list<T> list)
    : better_array(list, std::make_index_sequence<N>())
    {

    }

    constexpr T& operator[](size_t i) noexcept {
        assert(i < N);
        return _data[i];
    }

    constexpr const T& operator[](size_t i) const noexcept {
        assert(i < N);
        return _data[i];
    }

    constexpr T* begin() {
        return std::addressof(_data[0]);
    }

    constexpr const T* begin() const {
        return std::addressof(_data[0]);
    }

    constexpr T* end() {
        // todo: maybe use std::addressof and disable compiler warnings
        // about array bounds that result
        return &_data[N];
    }

    constexpr const T* end() const {
        return &_data[N];
    }

    constexpr size_t size() const {
        return N;
    }

private:

    T _data[N];

private:

    // construct each element from the initialiser list if present
    // if not, default-construct
    template<size_t...Is>
    constexpr better_array(std::initializer_list<T> list, std::integer_sequence<size_t, Is...>)
    : _data {
        (
         Is >= list.size()
         ?
         T()
         :
         std::move(*(std::next(list.begin(), Is)))
         )...
    }
    {

    }
};

// compute a simple factorial as a constexpr
constexpr long factorial(long x)
{
    if (x <= 0) return 0;

    long result = 1;
    for (long i = 2 ; i <= x ; result *= i)
        ++i;
    return result;
}

// compute an array of factorials - deliberately mutating a default-
// constructed array
template<size_t N>
constexpr better_array<N, long> factorials()
{
    better_array<N, long> result({});
    for (long i = 0 ; i < N ; ++i)
    {
        result[i] = factorial(i);
    }
    return result;
}

// convenience printer
template<size_t N, class T>
inline std::ostream& operator<<(std::ostream& os, const better_array<N, T>& a)
{
    os << "[";
    auto sep = " ";
    for (const auto& i : a) {
        os << sep << i;
        sep = ", ";
    }
    return os << " ]";
}

// for testing non-integrals
struct big_object
{
    std::string s = "defaulted";
    std::vector<std::string> v = { "defaulted1", "defaulted2" };
};

inline std::ostream& operator<<(std::ostream& os, const big_object& a)
{
    os << "{ s=" << quoted(a.s);
    os << ", v = [";
    auto sep = " ";
    for (const auto& s : a.v) {
        os << sep << quoted(s);
        sep = ", ";
    }
    return os << " ] }";
}

// test various uses of our new array
auto main() -> int
{
    using namespace std;

    // quick test
    better_array<3, int> x { 0, 3, 2 };
    cout << x << endl;

    // test that incomplete initialiser list results in a default-constructed object
    better_array<2, big_object> y { big_object { "a", { "b", "c" } } };
    cout << y << endl;

    // test constexpr construction using mutable array
    // question: how good is this optimiser anyway?
    cout << factorials<10>()[5] << endl;

    // answer: with apple clang7, -O3 the above line
    // compiles to:
    //  movq    __ZNSt3__14coutE@GOTPCREL(%rip), %rdi
    //  movl    0, %esi              ## imm = 0x168
    //  callq   __ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEElsEl
    // so that's pretty good!


    return 0;
}