c – 这两行之间有什么不同吗?

前端之家收集整理的这篇文章主要介绍了c – 这两行之间有什么不同吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们可以用两种方式创建一个对象:
myClass myObject = myClass(123);
//or
myClass myObject(123);

这两者之间的背景有什么不同吗?我想使用第一个,但似乎结合这两行:

myClass myObject;
myObject= myClass(123);

第二个也做同样的事情吗?

解决方法

myClass myVariable = myClass(123);

copy initialization.

myClass myVariable(123);

direct initialization.

myClass myVariable;
myVariable = myClass(123);

default initialization,然后是copy (or move) assignment.

通常,前两个是相同的,因为copy elision.相关规则可以在[class.copy] / 31(N4140,C 14草案标准)中找到:

When certain criteria are met,an implementation is allowed to omit
the copy/move construction of a class object […]:

— 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

原文链接:https://www.f2er.com/c/116487.html

猜你在找的C&C++相关文章