I have tried to create a vector factory that creates a vector of 1 values of specified size s but is not working as expected.
template<size_t s>
constexpr std::vector<int>& vector_factory()
{
std::vector<int> v(s, 1);
return v;
}
int main(int argc, char* argv[])
{
constexpr size_t s = 10;
std::vector<int> v1 = vector_factory<s>();
std::vector<int> v2 = vector_factory<s>();
}
I get a runtime error due to the large allocation attempt. However, if I try to implement it like this it is working properly.
constexpr size_t s = 10;
std::vector<int> v1(s, 1);
std::vector<int> v2(s, 1);
What am I doing wrong?
The runtime error is not due to a large allocation attempt, but due to two dangling references. The function signature
constexpr std::vector<int>& vector_factory();
has two issues. First, it fails to compile because std::vector doesn't have a constexpr constructor. Second, you must return the object by value, not by reference. Compilers should even warn you about this problem. If you change the above to
std::vector<int> vector_factory() { /* As before... */ }
everything should work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With