加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 调用构造函数的次数?

发布时间:2020-12-16 09:44:13 所属栏目:百科 来源:网络整理
导读:我是C编程的初学者,我对C类构造函数有一个简单的问题. 为以下代码片段调用构造函数的次数是多少? std::string s = std::string("hello world"); 我想这是两个,对吗?第一个是string(const char * s),第二个是string(const string s).如果我错了,请纠正我.
我是C编程的初学者,我对C类构造函数有一个简单的问题.
为以下代码片段调用构造函数的次数是多少?

std::string s = std::string("hello world");

我想这是两个,对吗?第一个是string(const char * s),第二个是string(const string& s).如果我错了,请纠正我.

接下来的问题是,如果我在发布模式下编译代码,编译器会自动对其进行优化吗?例如把它当作std :: string s(“hello world”);不同的编译器表现不同吗?

解决方法

源类型与目标类型相同的复制初始化(使用=)的行为与直接初始化非常相似.所以初始化相当于:

std::string s(std::string("hello world"));

如果没有优化,将按照您的描述调用两个构造函数.在C 11中,移动构造函数将优先用于第二步(定义为string(string&&)),因为std :: string(“hello world”)是一个rvalue表达式.但是,该标准明确允许在某些情况下省略副本/移动,包括以下内容:

when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type,the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

因此,如果编译器选择,编译器可以优化掉副本.请注意,即使复制构造函数有一些奇怪的副作用,编译器也可能会这样做.也就是说,完全定义良好且有效的C程序可能具有多个可能的执行路径.通常,你想避免这种情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读