我们可以用两种方式创建一个对象:
myClass myObject = myClass(123); //or myClass myObject(123);
这两者之间的背景有什么不同吗?我想使用第一个,但似乎结合这两行:
myClass myObject; myObject= myClass(123);
第二个也做同样的事情吗?
解决方法
myClass myVariable = myClass(123);
myClass myVariable(123);
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