我有以下類:爲什麼從一個std initilizer列表填充一個std ::矢量::字符串不會調用的std :: string構造
class StringContainer {
public:
StringContainer(const std::string& s1, const std::string& s2) {
string_array_ = {s1, s2};
}
std::vector<std::string> string_array_;
};
,然後我從這個結構創建一個對象像這樣:
StringContainer con(s1, s2);
其中s1和s2是非const const std :: string變量在本地定義的。 我注意到,從初始化列表中分配string_array_不會至少調用std :: string的構造函數一次。 (不適用於初始化程序列表中的臨時對象或插入到向量中的對象)。我已經讀過這對於可以構造的類是可能的,但trivially構造函數的要求之一是具有隱式的默認構造函數/拷貝構造函數。然而,std :: string(std :: basic_string)已經定義。我在這裏錯過了什麼? 如果我想編寫一個可以利用這種優化的字符串類,我該怎麼做?
你正在檢查的重載std :: string構造函數中的哪一個是否調用? –
我不知道你怎麼知道'std :: string'的構造函數沒有被調用。我告訴你,向量中的每個元素都會調用構造函數。複製構造函數在您的示例 – bolov
中調用,我逐步調試調試器到最後,它永遠不會被調用。如果我要用用戶定義的字符串替換std :: string,那麼我清楚地看到構造函數在構造初始化程序列表時以及何時向該向量添加項目時被調用。 – user3612009