这串构造函数被调用?

问题描述 投票:-5回答:1

我知道这是初始化,但我很困惑,其中2个构造函数时一个字符串文字在每种情况下,使用被调用。难道他们都拷贝构造函数?

string::string(const string& strString)
string::string(const char *szCString)

情况1:

string sSource("my string");

案例2:

const char *szSource("my string");
c++ constructor initialization stdstring string-literals
1个回答
2
投票

你可以check what the compiler does(GodBolt.org):

对于第一种情况,都会调用构造函数是:

std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string<std::allocator<char> >(char const*, std::allocator<char> const&)

或者,换句话说,如果我们忽略了分配基准参数的默认值,它是:

std::string::string(char const*)

至于第二种情况,没有字符串构造函数被调用。你只得到:

    mov     QWORD PTR [rbp-8], OFFSET FLAT:.LC0

这使一个指针到原始字符的位置。

现在,我想你感到困惑的是字符串文本的语义。字符串文字不std::strings!请记住,C ++作为语言不具有固有的字符串类型; std::string是从标准库。

那么,什么是字符串常量的类型?这是一个字符数组。 See for yourself(Coliru.com;该示例具有代码,用于获得类型名作为字符串)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.