2013-05-31 52 views
4

我的代碼如預期那樣工作:爲什麼錯誤的ctor被調用?

EscapedString es("Abc&def"); 
EscapedString es2(""); 
es2 = es;  // es2 == Abc%26def 

和代碼不能按預期工作:

EscapedString es("Abc&def"); 
EscapedString es2 = es; // es == Abc%2526def 

在第二種情況下,CTOR2被調用,而不是CTOR3即使es是EscapedString。

EscapedString es(EscapedString("Abc?def")); 

做正確的事,但我似乎無法設置CTOR3一個斷點,所以我不知道它是否正常工作,或代碼已被優化掉,或者意外的工作。

類是下面:

class EscapedString : public std::string { 
public: 
    EscapedString(const char *szUnEscaped) { // CTOR1 
     *this = szUnEscaped; 
    } 

    EscapedString(const std::string &strUnEscaped) { // CTOR2 
     *this = strUnEscaped; 
    } 

    explicit EscapedString(const EscapedString &strEscaped) { // CTOR3 
     *this = strEscaped; // Can't set breakpoint here 
    } 

    EscapedString &operator=(const std::string &strUnEscaped) { 
     char *szEscaped = curl_easy_escape(NULL, strUnEscaped.c_str(), strUnEscaped.length()); 
     this->assign(szEscaped); 
     curl_free(szEscaped); 
     return *this; 
    } 
    EscapedString &operator=(const char *szUnEscaped) { 
     char *szEscaped = curl_easy_escape(NULL, szUnEscaped, strlen(szUnEscaped)); 
     this->assign(szEscaped); 
     curl_free(szEscaped); 
     return *this; 
    } 
    EscapedString &operator=(const EscapedString &strEscaped) { 
     // Don't re-escape the escaped value 
     this->assign(static_cast<const std::string &>(strEscaped)); 
     return *this; 
    } 
}; 
+0

我認爲這與你的操作符重載做。 –

+7

可能是因爲你使你的拷貝構造函數是顯式的? – juanchopanza

回答

10

通常情況下,EscapedString es2 = es;會調用拷貝構造函數,但是你明確地通過使拷貝構造函數explicit告訴它不要:

explicit EscapedString(const EscapedString &strEscaped) 

一個構造標記explicit永遠不能通過自動類型轉換來調用。它只能叫,嗯......明確,你在這裏做:

EscapedString es(EscapedString("Abc?def")); 

下面是當編譯器遇到EscapedString es2 = es;會發生什麼。

首先,編譯器看到它是否可以使用複製構造函數,並發現它不能,因爲它被標記爲explicit。所以它尋找另一個構造函數來調用。由於EscapedStringstd::string導出,編譯器能夠施展esconst std::string&,並呼籲:

EscapedString &operator=(const std::string &strUnEscaped) 
相關問題