2017-07-18 90 views
4
cout << std::is_assignable<int*, std::nullptr_t>::value << endl; 
cout << std::is_assignable<int*&, std::nullptr_t>::value << endl; 

輸出是:C++ - 爲什麼nullptr_t不能分配給int *?

我不明白爲什麼第一個檢查返回

我可以nullptr分配給參考指針,但我無法將其分配給原始指針

這是相反的!

int* p = nullptr; 
int*& pref = nullptr; 

第二次分配,符合市場預期,標記錯誤:

error: cannot bind non-const lvalue reference of type int*& to an rvalue of type int*

有人可以解釋我是怎麼回事?

+2

這是因爲你正試圖初始化nullptr參考,不分配給它。不要讓'='迷惑你。 – VTT

+0

我在這裏看不到任何'int *'賦值,但是'int *&',這聽起來像是錯誤的。 – Fabien

+1

當然,你不能指定'int *'。否則像這樣的東西實際上會編譯'int a = 1; &a = nullptr;' –

回答

2

關於cppreference的文檔涵蓋了這一點。

std::is_assignable<int, int>是錯誤的,但std::is_assignable<int&, int>是正確的。

http://en.cppreference.com/w/cpp/types/is_assignable

+1

是的,請參閱[此問題](https://stackoverflow.com/questions/19920213/why-is-stdis-assignable-counter-intuitive),其中GSerg [提及的是重複的](https: //stackoverflow.com/questions/45177674/c-why-is-nullptr-t-not-assignable-to-int#comment77323990_45177674) –

相關問題