我的代码可以正常工作:
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;
}
};发布于 2013-05-31 22:55:53
通常,EscapedString es2 = es;将调用复制构造函数,但是您通过将复制构造函数设为explicit显式地告诉它不要这样做
explicit EscapedString(const EscapedString &strEscaped)标记为explicit的构造函数永远不能通过自动类型转换的方式调用。它只能叫做,嗯.显式地,您在这里已经做到了:
EscapedString es(EscapedString("Abc?def"));下面是编译器遇到EscapedString es2 = es;时会发生的事情。
首先,编译器查看它是否可以使用复制构造函数,并发现它不能使用,因为它被标记为explicit。所以它寻找另一个构造函数来调用。由于EscapedString是从std::string派生的,因此编译器能够将es转换为const std::string&并调用:
EscapedString &operator=(const std::string &strUnEscaped)https://stackoverflow.com/questions/16860070
复制相似问题