I am trying to write a factory function that creates a constexpr object that uses new. Is this even possible?
The following code does not compile:
aa.cpp: In function ‘int main()’: aa.cpp:23:39: in ‘constexpr’ expansion of ‘((Buffer*)(& b))->Buffer::~Buffer()’ aa.cpp:10:36: error: deallocation of already deallocated storage 10 |
constexpr ~Buffer() { delete[] data; }
#include <random>
struct Buffer {
int size;
int* data;
constexpr Buffer(int n) : size(n), data(new int[n])
{
for (int i = 0; i < n; ++i) data[i] = i;
}
constexpr ~Buffer() { delete[] data; }
constexpr int get(int i) const { return data[i]; }
static constexpr Buffer Create(int n)
{
Buffer buf(n);
// ...
return buf;
}
};
constexpr void test(int d)
{
Buffer b2(d);
}
int main() {
constexpr Buffer b = Buffer::Create(4);
constexpr Buffer b2(43); // also does not compile: error: ‘Buffer(43)’ is not a constant expression because it refers to a result of ‘operator new’
test(rand()); // This is Ok
}
std::vector, right? It has the same limitations as your class.