Des*_*tor 1 c++ string parameters stdstring copy-constructor
我正在阅读为什么复制构造函数有多个参数?.
接受的答案说:
旧std::basic_string的确有一个:
basic_string(const basic_string& s,
size_type pos = 0, size_type n = npos)
Run Code Online (Sandbox Code Playgroud)
但是http://www.cplusplus.com/reference/string/basic_string/basic_string/说:
basic_string (const basic_string& str, size_type pos, size_type len = npos,
const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)
上面不是复制构造函数,而是子串构造函数,它复制str从字符位置开始pos并跨越len字符的部分.
C++标准部分说:
如果X类的第一个参数是X&,const X&,volatile X&或const volatile X&,并且没有其他参数或者所有其他参数都有默认参数,则X类的非模板构造函数是一个复制构造函数
那么,该链接的接受答案是否不正确?这是子串的真正basic_string类构造函数吗?我已经在链接上检查了C++ 98,C++ 11和C++ 14规范中的原型并显示了相同的内容.
basic_string(以前的)C++ 11国际标准[basic.string] p5中的类模板的规范包含以下两个构造函数(以及其他):
Run Code Online (Sandbox Code Playgroud)basic_string(const basic_string& str); // ... basic_string(const basic_string& str, size_type pos, size_type n = npos, const Allocator& a = Allocator());
第一个显然是复制构造函数,第二个是没有复制构造函数.请注意,规范中没有构造函数,其中pos有一个默认参数.
C++ 03,C++ 14和C++ 1z中的情况基本相同.在C++ 98中,这两个构造函数确实只有一个:
basic_string(const basic_string& str, size_type pos = 0, size_type n = npos,
// ~~~~
const Allocator& a = Allocator());
Run Code Online (Sandbox Code Playgroud)
但是由于LWG 42,这已经改为现有版本,有两个独立的构造函数.
据我所知,允许C++标准库的实现将这两个构造函数合并为一个,然后成为一个复制构造函数:
basic_string(const basic_string& str, size_type pos = 0, size_type n = npos,
// ~~~~
const Allocator& a = Allocator());
Run Code Online (Sandbox Code Playgroud)
这有不同的行为.正如LWG 42(参见Shafik Yaghmour的 回答)中所解释的那样,实际的复制文件basic_string获取了一个str分配器的副本,而"substring"构造函数默认使用一个值初始化的新对象.
感谢Sebastian Redl指出这一点.