https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107862

            Bug ID: 107862
           Summary: Returning an std::vector from a lambda fails to be
                    constexpr, while a custom class with allocated storage
                    works
           Product: gcc
           Version: 12.2.0
               URL: https://godbolt.org/z/dve3Yx8ax
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: milasudril at gmail dot com
  Target Milestone: ---
              Host: x86-64_linux_gnu
            Target: x86-64_linux_gnu

Minimal working example:


#include <array>
#include <algorithm>
#include <vector>

struct Test {
    using value_type = int;
    constexpr Test(){ data = new value_type(0); }
    constexpr ~Test(){ delete data; }

    constexpr unsigned size() const { return 1; }
    constexpr auto begin() const { return data; }
    constexpr auto end() const { return data + 1; }

  private:
    value_type* data;
};

consteval auto dynamic_data_to_array(auto generator) {
    auto test = generator();
    using VT = typename decltype(test)::value_type;

    std::array<VT, test.size()> data;
    std::copy(test.begin(), test.end(), data.begin());
    return data;
}

constexpr Test get_test() { return Test(); }

int main()
{
// Does not work  constexpr auto data0 = dynamic_data_to_array([] { return
std::vector<int>{0};});
    constexpr auto data1 = dynamic_data_to_array([] { return Test{};});

    return data1[0];
}


It works to return a Test object here, but not an std::vector. Compiler output:

<source>:22:29:   in 'constexpr' expansion of 'test.std::vector<int>::size()'
<source>:22:33: error: the value of 'test' is not usable in a constant
expression
   22 |     std::array<VT, test.size()> data;
      |                                 ^~~~
<source>:19:10: note: 'test' was not declared 'constexpr'
   19 |     auto test = generator();
      |          ^~~~
<source>:22:29: note: in template argument for type 'long unsigned int'
   22 |     std::array<VT, test.size()> data;
      |                    ~~~~~~~~~^~
<source>:22:29:   in 'constexpr' expansion of 'test.std::vector<int>::size()'
<source>:22:33: error: the value of 'test' is not usable in a constant
expression
   22 |     std::array<VT, test.size()> data;
      |                                 ^~~~
<source>:19:10: note: 'test' was not declared 'constexpr'
   19 |     auto test = generator();
      |          ^~~~
<source>:22:29: note: in template argument for type 'long unsigned int'
   22 |     std::array<VT, test.size()> data;

I am not sure if this is by the standard, or if this is related to some missing
implementation details in the standard library. Note: clang doesn't like it
either.

Reply via email to