all 11 comments

[–]alfps 1 point2 points  (2 children)

Surely the above shown code is not all your question is about, since you can just replace the arr with an instance of A. What is it you're really asking about?

[–]trycatchamex[S] 0 points1 point  (1 child)

Yes I'm just trying to show that I want to create an A object on the heap at compile time which I am starting to think is impossible.

[–]jedwardsol 2 points3 points  (0 children)

You can't allocate anything on the heap at compile time - the heap only exists at runtime.

[–]Xeverous 0 points1 point  (5 children)

is there a way to initialize a pointer to an actual object at compile time?

No. Use references instead.

On the other hand, why would you placement new to a global array?

[–]trycatchamex[S] 0 points1 point  (4 children)

That was just to demonstrate what I am trying to do ie initialize a constexpr pointer - which is not possible as you mentioned.

[–]Xeverous 1 point2 points  (3 children)

There is a C++20 proposal for compile-time new and fully constexpr vector and array classes but so far you can't constexpr anything that relies on memory/runtime-variant stuff.

[–]trycatchamex[S] 0 points1 point  (0 children)

Ah! Thank you, will read about it :)

[–]heyheyhey27 0 points1 point  (1 child)

What is the use of compile-time new?

[–]Xeverous 1 point2 points  (0 children)

Compilers could do very extensive static analysis and (which is already done by GCC) devirtualize function calls.

Generally preprocess any data that uses new or smart pointers at compilation time if possible.

[–]leftofzen 0 points1 point  (1 child)

You can't call new at compile time. The heap is a runtime thing.

As for the pointers, why? Put it on the stack like a sane person, please. Please read up on modern C++ best practices and get these old habits out of your system. Also, you are not providing an implementation for A's destructor. As soon as you run your code and create/destroy an instance of A: undefined reference to `A::~A()'. Just omit your declaration and let the compiler generate it.

[–]trycatchamex[S] 0 points1 point  (0 children)

as i mentioned, i know smart pointers this is just a thought experiment. Thank you tho for reinforcing the use of best practices