July 11th, 2023

Why does the compiler complain about a missing constructor when I’m just resizing my std::vector to a smaller size?

So you’ve got a std::vector of things.

std::vector<Thing> things;

And then you learn that only the first n of them are any good, so you use resize() to throw away the extras.

things.resize(n); // keep only the first n

But this doesn’t work because the compiler complains about a missing constructor for Thing. “Why is it trying to construct new Things when I’m just shrinking?”

Because the compiler doesn’t know that you’re just shrinking.

The resize() is used for both growing and shrinking, so the compiler has to generate code that is prepared to do either. And growing the vector requires default-constructing the new Thing objects.

You might choose to appease the compiler by giving it a pre-made Thing object to use as the fill value, even though you know it won’t be used.

// pass dummy object to keep compiler happy
things.resize(n, dummy_thing); // keep only the first n

A less clunky solution is to use the erase method, which is used only for shrinking.

things.erase(things.begin() + n, things.end());

Mind you, this is still rather clunky, but at least it’s less clunky.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.