Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error while trying to compile .data() from std::array as a constexpr function in c++20

I was trying to compute an array in compilation time to speed up some functions while i encountered an error which I was unable to resolve with the help of cppreference.

The code boils down to this:

#include <cstddef>
#include <array>

template<typename T, size_t size>
constexpr auto giveArray()
{
    std::array<T, size> arr;
    for(size_t i = 0; i < size; ++i)
        arr[i] = 0;
    return arr;
}

constexpr auto arr = giveArray<int,10>().data();

While compiling with: "$ g++ -std=c++20 code.cpp" on ubuntu i get the error that .data() is not a constexpr function while it definitely is. Why am i getting this error and how it can be fixed while still running this function in compilation time and storing only a pointer, not the std::array object?

like image 736
jabluko Avatar asked Feb 21 '26 12:02

jabluko


1 Answers

storing only a pointer, not the std::array object?

You can't.

The rules of C++ are not suspended just because your code executes at compile time (indeed, not suspending those rules is half the point of constexpr code). The array needs to exist in order for a pointer to it to be meaningful. That means the array object needs to continue to be around when someone uses that pointer.

Getting a pointer to a temporary that gets destroyed will leave that pointer pointing to a destroyed object. This is just as true in compile-time code as runtime code. And using that pointer is just as non-functional at compile-time as it would be at runtime. Indeed, it's less functional, as UB (which is what accessing that pointer will provoke) at compile-time must be diagnosed and turned into a compile error.

like image 167
Nicol Bolas Avatar answered Feb 24 '26 03:02

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!