Last active
April 7, 2022 18:42
-
-
Save saxbophone/8402133499538f6a984957fe22ce01a8 to your computer and use it in GitHub Desktop.
Demo of constexpr vector usage and erroneous usage in C++20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://godbolt.org/z/vsacWP36z | |
// Note: Only works with x86_64 GCC (trunk) on Godbolt.org --must have a C++ stdlib that supports constexpr vector | |
#include <cstddef> | |
#include <vector> | |
class Storage { | |
private: | |
std::vector<int> foo; | |
public: | |
constexpr Storage() : foo(0) {} | |
constexpr Storage(std::size_t size) : foo(size) {} | |
}; | |
int main() { | |
constexpr Storage d; // OK! -std::vector(0) ctor will be used | |
// constexpr Storage f(52); ERROR! operator new used in constexpr! | |
constexpr Storage g(0); // OK! -std::vector(0) ctor will be used | |
Storage h; // OK, empty storage at runtime | |
Storage y(96); // OK, allocated storage at runtime | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment