c++ - 为什么调用了错误的 ctor?

标签 c++ constructor explicit

我有按预期工作的代码:

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

以及未按预期工作的代码:

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

在第二种情况下,即使 es 是 EscapedString,也会调用 CTOR2 而不是 CTOR3。

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

做正确的事,但我似乎无法在 CTOR3 上设置断点,所以我不确定它是否正常工作,或者代码已被优化掉或意外工作。

类(class)如下:

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 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++ - 为什么调用了错误的 ctor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860070/

相关文章:

c++ - 明确论证?

Python,无法将 input() 转换为 int()

c++ - C++ 中的 Cplex : cannot open this source file

c++ - 如何强制使用本地共享库而不是系统库?

c++ - 如何查看共享指针是否彼此相等

javascript - 如何对对象的所有属性调用函数?

c++ - 为什么类中不允许函数模板特化?

c++ - C++17中不定参数函数的错误

java - 了解Java父类(super class)和子类构造函数和方法之间的关系

c++ - 当参数在初始化列表时不可用时如何初始化成员对象?