2016-05-13 47 views
13

考慮下面的代碼片斷:現在允許爲std :: string分配一個數字?

#include <iostream> 
int main() { 
    std::string foo; 
    foo = -1; // why is the compiler not complaining about this? 
    std::cout << "1" << std::endl; 
    std::cout << foo << std::endl; 
    std::cout << "2" << std::endl; 
} 

實際輸出(二者ideone.com C++ 14模式和GCC 4.8.4):

<no output>

問題:

  1. 爲什麼代碼片段是否可以編譯?
  2. 註釋掉foo = -1,我得到正確的標準輸出(12)。編譯器編譯foo = -1;會導致後續的cout失敗?
+0

相關? http://stackoverflow.com/questions/32563648/stdstring-initialization-with-a-bool – CinCout

+0

因爲沒有構造函數接受字符串容器的整數。要麼你讓你的實現或使用字符串編號。 – Joel

+0

@Joel但爲什麼分配接受它? –

回答

11
foo = -1; 

解析爲std::string::operator=(char)因爲-1intint可以,在理論上,被轉換爲char

我不清楚標準說什麼時int不代表有效的char。它看起來像在你的實現中,程序崩潰。

更新

從C++ 11標準(重點煤礦):

3.9.1基本類型

聲明爲字符( char

1對象應大到足以存儲實現的基本字符集的任何成員。如果來自該組的字符存儲在字符對象中,則該字符 對象的整數值等於該字符的單個字符文字形式的值。 實現定義char對象是否可以保存負值。

看來,你必須諮詢你的編譯器的文檔,以瞭解是否允許char對象持有負值,如果是的話,它是如何看待這樣的對象。

+1

什麼是無效的'char'? –

+0

@BenjaminLindley,改寫了那部分。 –

+1

我猜想它將-1誤解爲EOF – Christophe

5

char是C++中的一個整型。 std::string限定一個賦值操作符:

std::string& operator=(char); 

由於int轉換到自由char在這種情況下,沒有診斷中給出。 (這很有趣,最好的意圖如何鋪平通向地獄的道路,是嗎?)

由於(char)-1可能不是一個有效的成員,如果你的平臺上設置的執行字符,流進入錯誤狀態,並會呆在那裏,輸出什麼,直到錯誤位被清除。

編輯這是一個ideone的bug。如果輸出流包含「非法」字符,則整個流不會顯示,即使是在壞字符之前生成並刷新的部分。使用其他在線編譯器進行檢查。

+0

因此'foo = -1;'將流設置爲錯誤狀態?異常是C++的一個組成部分,我不明白爲什麼它仍然使用無聲的「錯誤狀態」機制。 –

+0

@ZachSaw你可以設置iostreams來拋出異常,但它不是默認值。 –

+0

@ZachSaw [看這裏](http://stackoverflow.com/questions/3180268/why-are-c-stl-iostreams-not-exception-friendly)。 –

1

這些都是運營商= String類重載: -

basic_string& operator=(const basic_string& str); 
basic_string& operator=(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||  allocator_traits<Allocator>::is_always_equal::value); 
basic_string& operator=(const charT* s); 
basic_string& operator=(charT c); 
basic_string& operator=(initializer_list<charT>); 

希望是有道理爲什麼編譯罰款。

現在來談談爲什麼沒有輸出的問題。我已經調整了一些代碼: -

#include <iostream> 
int main() { 
    std::string foo; 
    foo = -1; // why is the compiler not complaining about this? 
    char ch = 65; 
    std::cout << "1" << std::endl; 
    std::cout << foo << std::endl; 
    std::cout << ch << std::endl; 
    //change ch to -1 ... ascii 
    ch = -1; 
    std::cout << ch << std::endl; 
    std::cout << "2" << std::endl; 
} 

你猜猜輸出是什麼嗎? Yup認爲按照ascii: -

1 
  
A 
  
2 

這就是爲什麼你沒有-1的輸出。

編譯器 - MinGW - std = C++ 14 - 不知道爲什麼IDEONE在你的情況下弄糟了整個輸出流。

相關問題