在S s = S()是否保证不会创建临时? [英] In S s = S() is it guaranteed that no temporary will be created?
问题描述
在下面的代码中, pS
和 s.pS
保证在最后一行相等?换句话说,在语句 S s = S();
中,我可以确定临时 S
不建构?
In the following code, are pS
and s.pS
guaranteed to be equal in the final line? In other words, in the statement S s = S();
, can I be sure that a temporary S
will not be constructed?
#include <iostream>
using namespace std;
struct S
{
S() { pS = this; }
S* pS;
};
int main()
{
S s = S();
S* pS = &s;
cout << pS << " " << s.pS << endl;
}
在每个编译器中,我都在 pS == s.pS
,但我不太熟悉标准,以便能够满足自己,这是保证。
In every compiler I've tested this in pS == s.pS
, but I'm not sufficiently familiar with the standard to be able to satisfy myself that this is guaranteed.
推荐答案
否
编译器不是该标准简单地指定了[class.copy]:
The compiler isn't obligated to do copy elision. The standard simply specifies that, [class.copy]:
当满足某些标准时,允许< ...>
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]
我可以通过<$ c $禁用复制elision c> -fno-elide-constructors ,然后两个指针肯定会不同。例如:
I can disable copy elision via -fno-elide-constructors
, and then the two pointers will definitely be different. For example:
$g++ -std=c++11 -Wall -pedantic -fno-elide-constructors -Wall -Wextra main.cpp && ./a.out
0x7fff5a598920 0x7fff5a598930
在一般情况下, code> S(S&&)= delete ,那么上面的代码甚至不会编译。
And in the general case, if we add S(S&& ) = delete
, then the above code wouldn't even compile.
这篇关于在S s = S()是否保证不会创建临时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!