复制初始化与直接初始化 [英] Copy initialization vs direct initialization
问题描述
我是 浏览页面
复制与直接初始化
I was going through the page
Copy vs direct intialization
在该页面中有一个示例,如下所示
In that page there is one example, as below
#include <iostream>
struct B;
struct A {
operator B();
};
struct B {
B() { }
B(A const&) { std::cout << "<direct> "; }
};
A::operator B() { std::cout << "<copy> "; return B(); }
int main() {
A a;
B b1(a); // 1)
B b2 = a; // 2)
}
// output: <direct> <copy>
在VS2015编译器上编译时,输出为< copy> <复印>但在其他编译器上它是< direct> < copy>。
When compiled on VS2015 compiler it is giving output as <copy> <copy> but on other compilers it is <direct> <copy>.
直接和复制初始化是编译器相关的吗?
Is direct and copy initialization is compiler dependent thing ?
请告诉我。
谢谢,
Jafar
谢谢,Jafar
推荐答案
嗯,首先,Visual Studio 2017输出< direct> <复印取代。这似乎与其他编译器一致。
Well, for a start, Visual Studio 2017 outputs <direct> <copy>. This seems to agree with other compilers.
但无论如何。如果你写的内容对于这个确切的代码是真的那么如果它确实试图复制第一个代码我会感到惊讶。语法:
But anyway. If what you wrote is true for this exact code then I would be surprised if it does try to copy the first one. The syntax of:
B b1(a);
基本上是调用构造函数,所以重载解析应该更喜欢B(const A&)与B(const B&)和运算符B(),(或B()和运算符B()的复制省略直接匹配。
Is basically calling the constructor, so overload resolution should prefer the direct match of B(const A &) over B(const B&) and operator B(), (or B() and operator B() with copy elision).
对于第二个,我不记得标准上说的是什么。但有趣的是A ::运算符B只是因为常数或缺乏而赢得胜利。这实际上使它更好地匹配,因为从A ::运算符B()返回的非const
B :: B()构造B是一个更好的匹配。
For the second one, I can't remember what the standard says on this. But the interesting thing is that A::operator B is only winning out because of the constness, or lack thereof. This actually makes it a better match because constructing B with a non const B::B() returned from A::operator B() is a better match.
有趣的是,如果你做了两件事之一,编译器实际上开始抛出编译器错误。
Interestingly, if you do one of two things, the compiler actually starts throwing compiler errors.
例如,如果你将B :: B(const A&)改为B :: B(A& amp; ;)然后这将评估与A ::运算符B()相同,并且将发现复制初始化不明确。如果你按原样保留B :: B(const A&)并将A :: operator B()
改为A :: operator B()const,也是如此。
For example, if you change B::B(const A&) to B::B(A&) then this will evaluate to the same as A::operator B() and will be found ambiguous for copy initialisation. The same is true if you leave B::B(const A&) as it is and change A::operator B() to A::operator B() const.
所以不,这不是编译器相关的东西,重载决策应该是非常一致的。但也许是因为Visual Studio 2017具有更多可用的C ++ 17功能,因此它可以提供与其他功能相同的输出。因为你b $ b尝试的其他人是Clang,可能是5或6,而GCC,可能是6或7对吗?它们具有一些较新的C ++ 17功能,比Visual C ++更长。
So no, this isn't a compiler dependent thing, overload resolution should be pretty consistent. But maybe because Visual Studio 2017 has more C++ 17 features available that it is coming up with the same output as others. Because the others that you tried were Clang, probably 5 or 6, and GCC, probably 6 or 7 right? These have had some of the newer C++ 17 features in for longer than Visual C++.
这篇关于复制初始化与直接初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!