Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector<int> factory with initialization is not working

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?

like image 776
Radim Bača Avatar asked Mar 12 '26 03:03

Radim Bača


1 Answers

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.

like image 132
lubgr Avatar answered Mar 14 '26 15:03

lubgr