![](/img/trans.png)
[英]How are temporary objects created and what's the actual operations that takes place?
[英]In S s = S() is it guaranteed that no temporary will be created?
在下面的代碼中, pS
和s.pS
在最后一行中是否保證相等? 換句話說,在聲明S s = S();
,我可以確定不會構建臨時S
嗎?
#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
對此進行了測試,但我對標准不夠熟悉,以確保能夠保證這一點。
沒有
編譯器沒有義務進行復制省略。 標准只是指定,[class.copy]:
當滿足某些條件時, 允許實現省略類對象的復制/移動構造[...]
我可以通過-fno-elide-constructors
elide -fno-elide-constructors
禁用copy elision,然后兩個指針肯定會有所不同。 例如:
$g++ -std=c++11 -Wall -pedantic -fno-elide-constructors -Wall -Wextra main.cpp && ./a.out
0x7fff5a598920 0x7fff5a598930
在一般情況下,如果我們添加S(S&& ) = delete
,那么上面的代碼甚至都不會編譯。
無法保證不會有臨時性。 但三巨頭編譯器將優化它(即使使用-O0
開關)。
為了保證沒有臨時性,只需寫:
int main()
{
// ...
S s{};
// ...
}
或者只是S s;
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.