When compiling a C++ project in release mode with Visual Studio 2022 version 17.6.4 with the ‘Inline function expansion’ option set to /Ob2, i have found out that the std::sort() function for std::deque returns incorrect results. I have tried with the current version of Visual Studio 2022 (version 17.9) and the problem still occurs.
The code to reproduce this problem is as following.
#include <iostream>
#include <algorithm>
#include <deque>
using namespace std;
int main()
{
const string data[] = {
"ElectronicDocument",
"Order",
"xs:string",
"an..10",
"DateTime",
"Date",
"DeliveryDateRequested",
"CurrencyCode",
"Party",
"BuyerParty",
"EAN - 13",
"xs:positiveInteger",
"xs:nonNegativeInteger",
"xs:integer",
"xs:decimal",
"GLN",
"Contact",
"an..35",
"EMail",
"TelephoneOrTelefaxNumber",
"Address",
"an..70",
"CityName",
"n5",
"xs:nonPositiveInteger",
"PostalCode",
"CountryCode",
"SellerParty",
"BankAccountIdentification",
"n..12",
"LineItem",
"n..5",
"GTIN",
"MonetaryAmount",
"Price",
"MonetaryAmountValue",
"Quantity",
"MeasureUnitCode",
"TotalAmount"
};
std::deque<std::unique_ptr<string>> tDeque;
for (auto iter = std::begin(data); iter < std::end(data); iter++)
{
tDeque.push_back(std::make_unique<string>(*iter));
}
std::sort(tDeque.begin(), tDeque.end(),
[](const std::unique_ptr<string>& l, const std::unique_ptr<string>& r) -> bool
{
return *l < *r;
});
for (auto iter = tDeque.begin(); iter < tDeque.end(); iter++)
{
cout << (*iter)->c_str() << "\r\n";
}
}
With the compiler option /Ob2 produces std::sort() function results that are in an incorrect order, as shown below.
Address
BankAccountIdentification
CityName
CountryCode
GTIN
LineItem
MeasureUnitCode
MonetaryAmount
MonetaryAmountValue
PostalCode
Price
Quantity
SellerParty
TelephoneOrTelefaxNumber
BuyerParty
Contact
CurrencyCode
Date
DateTime
DeliveryDateRequested
EAN - 13
EMail
ElectronicDocument
GLN
Order
Party
TotalAmount
an.. 10
an.. 35
an.. 70
n.. 12
n.. 5
n5
xs:decimal
xs:integer
xs:nonNegativeInteger
xs:nonPositiveInteger
xs:positiveInteger
xs:string
Without using /Ob2, returns the std::sort() function results in correct order. Using std::vector<std::unique_ptr<string>> or std::deque<string> instead of std::deque<std::unique_ptr<string>> does not lead to problem.
Can anyone confirm whether this is an error in the std library in Visual Studio? I have posted the problem in the Visual Studio Developer Community, but there has been no response.
Because of this error we can not update Visual Studio and its build tools to current version.