C ++中的字符串初始化有什么区别? [英] What are the differences in string initialization in C++?

查看:142
本文介绍了C ++中的字符串初始化有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::string s1("foo");

std::string s2 = "foo";

推荐答案

是和否。

第一个是显式初始化,第二个是复制初始化。标准允许用第一个替换第二个。在实践中,生成的代码是相同的。

The first is initialized explicitly, and the second is copy initialized. The standards permits to replace the second with the first. In practice, the produced code is the same.

这是一个简单的例子:

std::string s1("foo");

以下形式的字符串构造函数:

The string constructor of the form:

string ( const char * s );

调用 s1

在第二种情况下。创建一个临时,并为该临时调用所提到的earler构造函数。然后,调用复制构造函数。例如:

In the second case. A temporary is created, and the mentioned earler constructor is called for that temporary. Then, the copy constructor is invoked. e.g:

string s1 = string("foo");

在实践中,第二种形式被优化,以第一种形式。我没有看到一个编译器不优化第二种情况。

In practice, the second form is optimized, to be of the form of the first. I haven't seen a compiler that doesn't optimize the second case.

这篇关于C ++中的字符串初始化有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆