2015-12-19 30 views
0

我有以下類:爲什麼從一個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)已經定義。我在這裏錯過了什麼? 如果我想編寫一個可以利用這種優化的字符串類,我該怎麼做?

+3

你正在檢查的重載std :: string構造函數中的哪一個是否調用? –

+6

我不知道你怎麼知道'std :: string'的構造函數沒有被調用。我告訴你,向量中的每個元素都會調用構造函數。複製構造函數在您的示例 – bolov

+0

中調用,我逐步調試調試器到最後,它永遠不會被調用。如果我要用用戶定義的字符串替換std :: string,那麼我清楚地看到構造函數在構造初始化程序列表時以及何時向該向量添加項目時被調用。 – user3612009

回答

1

我的調試器確信構造函數已被調用,但如果我不能使用調試器,我決定做一些小實驗來獲取證明。你也可以自己嘗試。

創建的std :: string的子類,由字符串2取代的std :: string在你的代碼,添加一些打印輸出,並獲得視覺證明,構造函數被調用:

class string2 : public string 
{ 
public: 
    string2(std::string s) : std::string(s) 
    { 
     std::cout << "string2 constructor" << std::endl; 
    } 
    string2(const string2& s) : std::string(s) 
    { 
     std::cout << "string2 copy constructor" << std::endl; 
    } 
}; 
0

但願這是因爲牛?

參見:

從報價有報價:

* This approach has the enormous advantage that a string object 
* requires only one allocation. All the ugliness is confined 
* within a single %pair of inline functions, which each compile to 
* a single @a add instruction: _Rep::_M_data(), and 
* string::_M_rep(); and the allocation function which gets a 
* block of raw bytes and with room enough and constructs a _Rep 
* object at the front. 

參見:

相關問題