[英]“Move or throw” using the ternary operator
從C ++ 11開始,我一直使用三元運算符根據某些條件移動或拋出,但是最新的GCC(9.1和trunk)不再工作了。
我已將問題減少到此示例( Wandbox永久鏈接 ):
#include <iostream>
#include <memory>
int main()
{
auto p = std::make_unique<int>();
std::cout << "p.get(): " << p.get() << std::endl;
{
std::cout << "Move p into q" << std::endl;
auto q = p ? std::move(p) : throw std::invalid_argument{"null ptr"};
std::cout << "q.get(): " << q.get() << std::endl;
}
std::cout << "p.get(): " << p.get() << std::endl;
return 0;
}
它適用於GCC 8.3及更早版本,以及每個Clang版本; 和p
被移動:
p.get(): 0xde5c20
Move p into q
q.get(): 0xde5c20
p.get(): 0
但現在使用GCC 9.1及更高版本它不起作用:
p.get(): 0x1d89150
Move p into q
q.get(): 0x1d89150
p.get(): 0x1d89150
然后該程序由於雙重免費而崩潰。
這是GCC 9.1 / trunk中的錯誤嗎? 或者最新的GCC是唯一一個做正確的事情而且這不是有效的C ++?
這必須是一個錯誤。
移動將是一個移動,或者由於嘗試復制unique_ptr
而導致編譯失敗(或者發生throw
,在這種情況下無關緊要)。
q.get() == p.get()
確實表明內部已經崩潰,因為這是不可能的。
我同意cpplearner這是錯誤90393 (及其所有欺騙),據報道已經在GCC 9.1中引入。
要么降級,等待升級,要么將代碼改為好的if
/ else
。 😊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.