为什么叫错了医生
Why is the wrong ctor being called?
我的代码按预期工作:
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;
}
};
通常情况下,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)
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 如何正确使用 >=?(a+f()+c)>=0 错了吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 指针相关的UE4崩溃.我的指针哪里错了?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 为什么叫错了医生