Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active April 7, 2022 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/8402133499538f6a984957fe22ce01a8 to your computer and use it in GitHub Desktop.
Save saxbophone/8402133499538f6a984957fe22ce01a8 to your computer and use it in GitHub Desktop.
Demo of constexpr vector usage and erroneous usage in C++20
// 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