3
我正在計劃最近這是這樣的: -檢查使用常量性type_traits
#include <iostream>
#include <memory>
#include <type_traits>
#include <typeinfo>
using namespace std;
int main()
{
shared_ptr<int> sp1 = make_shared<int>(5);
shared_ptr<const int> sp2 (sp1);
const int x = 8;
// *sp2 = 7; // error: assignment of read-only location 'sp2.std::shared_ptr<const int>::<anonymous>.std::__shared_ptr<_Tp, _Lp>::operator*<const int, (__gnu_cxx::_Lock_policy)2u>()'
auto p = sp2.get();
cout << typeid(x).name() << '\t' << typeid(*p).name() << '\n';
cout << boolalpha;
cout << is_const<decltype(*p)>::value << '\n' << is_same<const int, decltype(*p)>::value;
return 0;
}
這個程序的輸出是: -
i i
false
false
至於清晰可見,typeid
規定*p
& x
是相同類型&即使使用*sp2 = 7
也會產生錯誤。那爲什麼std::is_same
& std::is_const
有什麼不同呢?
nvm,混淆'p' /'sp'。雖然在這種情況下我會去'remove_pointer'(或者通過'pointer_traits :: element_type',雖然這可能是過度的 - 它確實有處理普通指針和智能指針的好處)。 –
@ T.C。好吧,這很有道理,編輯回答 –
很酷,謝謝! – Anwesha