2013-04-21 47 views
-1

我不明白爲什麼會發生這種情況。在複合語句中不能分配字符串

我有一個聲明是這樣一些功能:

std::string unmaskString(std::string &oValue); 

在我這樣做的代碼:

v = unmaskString(line.substr(eq+1)); 

,我得到一個編譯錯誤說:

error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >' 

當我把它放在兩個單獨的聲明中:

v = line.substr(eq+1); 
v = unmaskString(v); 

第一行返回一個字符串對象,甚至沒有引用,所以我不太瞭解錯誤。

更改功能

std::string unmaskString(std::string oValue); 

也給出了錯誤。

UPDATE:

更改maskString到unmaskString,因爲這是一個錯誤,但問題仍然aplies作爲masString具有相同的簽名。

+2

誰在乎'maskString'如果你的問題是'unmaskString'? – 2013-04-21 12:04:25

+0

問題是一樣的。這不是關於臨時對象的函數名稱。這是一個錯字,並且不相關,因爲錯誤信息不是「未定義的函數」。 – Devolus 2013-04-21 12:29:19

+0

但是你已經智取你自己。通過將參數更改爲非參考,您提出的修復方法確實有效,但由於您對修改哪項功能並不在意,因此您沒有注意到這一點。無論如何,請儘量縮短問題的相關時間。我們不需要知道代碼中沒有連接到問題的所有其他部分。 – 2013-04-21 12:35:28

回答

7

的結果:

line.substr(eq+1) 

std::string類型的臨時對象。臨時是右值,並且左值引用不能綁定到右值。

注意,如果你的maskString()功能並不需要修改其參數(爲什麼會返回一個std::string否則?),沒有理由爲它接受它的參數作爲參考,以非const

的可能的解決方案是(按優先順序排列):

  • maskString()採取其輸入由值,使得輸入參數將是複製如果它是一個左值和感動如果它是一個右值:

    std::string maskString(std::string oValue); 
    //      ^^^^^^^^^^^ 
    { 
        // Whatever is going on... 
        return oValue; // This will be MOVED into the object that stores 
            // the value returned by this function 
    } 
    
  • maskString()通過lval中完成輸入請參考const(這種方式valueoValue初始化將始終導致副本,即使參數是臨時的),然後將其複製到臨時變量中,最終將返回並移出。這是因爲左值引用工作const可以綁定到右值(並因此臨時量):

    std::string maskString(std::string const& oValue); 
    //         ^^^^^ 
    { 
        std::string value = oValue; 
    
        // Whatever is going on... 
        return value; // This will be MOVED into the object that stores 
            // the value returned by this function 
    } 
    
  • 做你所做的:存儲由substr在名爲對象返回的對象,該對象傳遞給unmaskString()

+0

爲什麼不通過右值引用一個選項在這裏? – 0x499602D2 2013-04-21 12:26:07

+0

@ 0x499602D2:好吧,單獨使用右值引用*不是一個選項,因爲右值引用不能綁定到左值。 OP將必須爲rvalue引用引入一個重載,該重載基本上會創建一個傳遞的右值的副本並將其轉發給'maskString'的左值引用版本。但是這是無用的工作,只需按值取值並讓編譯器完成這項工作 – 2013-04-21 12:28:09

+0

請注意,這些規則不是任意的,它們用於保護您:如果函數接受非const引用,則假定它將修改以有用的方式進行論證,如果你通過一個臨時的話,那麼這個修改就會丟失。這很可能是程序員錯誤。 – rodrigo 2013-04-21 12:28:32