std::vector::reserve() contains a suboptimal check against max_size - by Dmitry Me

Status : 

  Fixed<br /><br />
		This item has been fixed in the current or upcoming version of this product.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 694704 Comments
Status Closed Workarounds
Type Bug Repros 0
Opened 10/13/2011 5:35:32 AM
Access Restriction Public


As of version 10.0.40219.1 SP1Rel std::vector::reserve() code goes like this:

void reserve(size_type _Count)
{	// determine new minimum length of allocated storage
if (max_size() < _Count)
_Xlen();	// result too long
else if (capacity() < _Count)
{	// not enough room, reallocate
        // skipped

Now capacity() <= max_size() at all times. Which means that if _Count <= capacity() then automatically _Count <= max_size(). Which means that whenever I try to reserve() less bytes than capacity() the first check is redundant.

reserve() should be redesigned like this:

void reserve(size_type _Count)
{	// determine new minimum length of allocated storage
if (capacity() < _Count) {
    if(max_size() < _Count)
        _Xlen();	// result too long
    // not enough room, reallocate
    // skipped

so that the check is done only if there's a need for allocation in the first place.
Sign in to post a comment.
Posted by Microsoft on 11/4/2011 at 9:16 PM

Thanks for suggesting this micro-optimization. We've implemented it, "flipping" the _Xlen() check, and it will be available in VC11.

All of _Insert(), _Insert_n(), _Reserve(), and reserve() have been changed. I hope you don't mind if I copy and paste this response for your four bugs - in the future, please consider filing a single bug when a single issue appears in multiple places.

If you have any further questions, feel free to E-mail me at .

Stephan T. Lavavej
Visual C++ Libraries Developer
Posted by EricLeong [Feedback Moderator] on 10/13/2011 at 7:12 PM
Thank you for submitting feedback on Visual Studio 2010 and .NET Framework. Your issue has been routed to the appropriate VS development team for review. We will contact you if we require any additional information.
Posted by MS-Moderator01 on 10/13/2011 at 5:46 AM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(