我基本上想知道后者是否更有效/优化,因为它没有创建 string 的副本?
我想使用像 string str(str1,3,5) 这样的构造函数来创建一个字符串;
我想使用像 string str(str1,3,5) 这样的构造函数来创建一个字符串;
如果我们在这里查看相应的std::string
构造函数,我们会看到它有签名
basic_string( const basic_string& other,
size_type pos,
size_type count,
const Allocator& alloc = Allocator() );
请注意const basic_string& other
部分:字符串通过常量引用传递,不涉及临时副本。因此,std::string str(str1, 3, 5)
尽可能高效,而这样做std::string str((std::string &)str1, 3, 5)
只会混淆代码:它包含一个(通常被认为是坏的)C 风格的强制转换,它假装引用是非常量的,并且它为读者增加了认知工作而没有获得任何事物。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句