簡體   English   中英

C ++字符串-使用初始化列表構造函數時的奇怪行為

[英]C++ string - strange behaviour when using initialization list constructor

我知道我可以使用字符數組和初始化列表來填充字符串。

看起來編譯器對int進行了一些隱式提升,使其從initializer_list或allocator提升。 但是我不知道為什么它不給我任何警告,為什么它使它隱含。

您能告訴我字符串s4和s5會發生什么嗎?

http://ideone.com/5Agc2T

#include <iostream>
#include <string>
using namespace std;

class A{
};

int main() {

    // string::string(charT const* s)
    string s1("12345");
    // 5 - because constructor takes into account null-terminated character
    cout << s1.size() << endl;      

    // string(std::initializer_list<charT> ilist)
    string s2({'1','2','3','4','5'});   
    // 5 - because string is built from the contents of the initializer list init.  
    cout << s2.size()<<endl;

    // string::string(charT const* s, size_type count)
    string s3("12345",3);
    // 3 -  Constructs the string with the first count characters of character string pointed to by s
    cout << s3.size() << endl;

    // basic_string( std::initializer_list<CharT> init,const Allocator& alloc = Allocator() ); - ?
    string s4({'1','2','3','4','5'},3);
    // 2 - why this compiles (with no warning) and what this result means?
    cout << s4.size() << endl;



    string s5({'1','2','3','4','5'},5);
    // 0 - why this compiles (with no warning) and what this result means?
    cout << s5.size() << endl;

    // basic_string( std::initializer_list<CharT> init,const Allocator& alloc = Allocator() );
    // doesn't compile, no known conversion for argument 2 from 'A' to 'const std::allocator<char>&'
    //string s6({'1','2','3','4','5'},A());
    //cout << s6.size() << endl;

    return 0;
}
string s6({'1','2','3','4','5'},3);
string s7({'1','2','3','4','5'},5);

實際上,這些初始化不只是調用std::initializer_list構造函數。 第二個參數不能隱式轉換為std::allocator ,因此考慮其他構造函數。 調用的構造函數是具有以下簽名的構造函數:

basic_string( const basic_string& other, 
              size_type pos, 
              size_type count = std::basic_string::npos,
              const Allocator& alloc = Allocator() );

std::initializer_list構造函數用於從括號初始列表創建臨時std::string ,以作為other參數傳遞給上述構造函數。 臨時可以綁定到該對象,因為它是對const的引用。 因此,第二個參數是pos參數,它用作子字符串副本構造的起點。

因此s6是間隔[3, 5)的字符(即"45" ),而s7是間隔[5,5)的字符(即"" )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM