Unable to create constexpr std :: vector

I can create constexpr std :: array:

 constexpr std::array<int,5> values {1,2,3,4,5}; 

It works great. But I can not create constexpr vector:

 constexpr std::vector<int> vec = {1,2,3,4,5}; 

This gives me an error:

the type 'const std::vector<int>' of constexpr variable 'vec' is not literal constexpr std::vector<int> vec = {1,2,3,4,5};

+14
source share
3 answers

AFAIK Constructor initlializer_list std::vector<> not declared constexpr .

+12
source

std :: vector is not constexpr. There is a proposal to make std :: vector constexpr: https://github.com/ldionne/wg21/blob/master/generated/p1004r1.pdf

A whole conversation about the upcoming changes in C ++ 20/23: https://youtu.be/CRDNPwXDVp0?t=3080

So check again with C ++ 20.

[edit]: constexpr std :: vector was approved for C ++ 20! https://www.reddit.com/r/cpp/comments/au0c4x/201902_kona_iso_c_committee_trip_report_c20/

[edit 2019-10]: the gcc trunk (with the flag --std=c++2a ) began to implement constexpr new (precondition for constexpr vector ). See: https://youtu.be/FRTmkDiW5MM?t=372

+24
source

std::vector uses dynamic memory allocation. The new operator cannot be used in constexpr methods, so std::vector will never be constexpr , the constexpr constructor cannot be declared for it. std::array does not use dynamic memory allocation, it is allocated on the stack. It has no problems with the rules for creating constexpr objects and can be constexpr.

+22
source

All Articles