我在 Visual Studio v143 工具 std:c 上發現了一些東西,它是 bug 還是什么
std::unordered_map<std::string, std::string> map;
std::string test_str = "1234567890123456789012345678901234567890123456789012345";//55 LEN String
map["test_len"] = test_str.length();
std::cout << map["test_len"]; // 7 on 55 len string
編輯:所有數字都相同,即使 Content-Lenght 無效,Chrome 也可以作業
uj5u.com熱心網友回復:
在宣告中
map["test_len"] = test_str.length();
std::unordered_map::operator[]default-constructs a newstd::string并回傳對它的參考,然后將其分配給 type 的值size_type。此賦值呼叫std::string::operator=(char)將整數值解釋55為 ascii 字符7。
這是std::string界面中長期存在的可用性錯誤。錯誤示例:
std::string s = test_str.length(); // Compiler error.
std::string s2;
s2 = test_str.length(); // Compiles successfully, std::string interface bug.
s2 = true; // Compiles successfully, std::string interface bug.
s2 = std::ios_base::failbit; // Compiles successfully, std::string and std::ios_base interface bugs.
std::string s3{std::ios_base::failbit, 55, true, 'a'}; // Compiles successfully, std::string interface bug.
std::string s3 = {std::ios_base::failbit, 55, true, 'a'}; // Compiles successfully, std::string interface bug.
將值插入或分配到關聯容器的 C 17 型別安全方法是:
map.insert_or_assign("test_len", test_str.length()); // Compiler error.
map.insert_or_assign("test_len", {std::ios_base::failbit, 55, true, 'a'}); // Compiler error.
map.insert_or_assign("test_len", std::to_string(test_str.length())); // Success.
std::unordered_map::insert_or_assign當值型別賦值運算子與其建構式具有不同的語意時,總是使用映射值的直接初始化來精確避免這種無聲的意外型別轉換錯誤,這違反了最小意外的工程原則。
uj5u.com熱心網友回復:
您嘗試放入length()- string>string地圖。你需要的是把to_string()它:
#include <unordered_map>
#include <string>
#include <iostream>
int main() {
std::unordered_map<std::string, std::string> map;
std::string test_str = "1234567890123456789012345678901234567890123456789012345";//55 LEN String
map["test_len"] = std::to_string(test_str.length());
std::cout << map["test_len"];
}
請注意,它std::string確實有一個 char 的 ctor,如 Maxim 的回答中那樣,因此您的代碼不是錯誤,只是不是您期望的那樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/511319.html
標籤:C 视觉-C
