簡體   English   中英

將const和decltype與指針變量一起使用

[英]Using const and decltype with a pointer variable

以下代碼允許我更改* p2處的值,即使p2是用const聲明的。

int *p1;

const decltype(p1) p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl; // Outputs *p2: 200

但是,如果我使用“int *”而不是“decltype(p1)”,則編譯器會標記錯誤。

const int * p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl;

error: assignment of read-only location ‘* p2’
  *p2 = 200;
      ^

我正在使用g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2。

當應用於指針變量時,decltype是否忽略const說明符?

const decltype(p1) p2表示int* const p2

這意味着您無法更改p2 ,但您可以更改指向的內容。


const T總是適用於常量的所謂“頂級” T T是復合類型(即,從基本類型集構建的類型)時,如果要將const應用於較低級別,則必須跳過箍。

當T為int * ,添加頂級const將給出int * const *划分一個級別; 得到*以下的東西你必須手動刪除* ,應用const ,然后把*放回去。

可能的解決方案是:

const std::remove_pointer<decltype(p1)>::type *p2 = new int(100);

std::pointer_traits在這里會派上用場。 std::pointer_traits::element_typestd::pointer_traits::rebind允許你編寫一個通用表達式,它適用於任何類似指針的類型:

using element_type = std::pointer_traits<decltype(p1)>::element_type;
using pointer_like_to_const = std::pointer_traits<decltype(p1)>::rebind<std::add_const_t<element_type>>;
pointer_like_to_const p2 = new int(100);

請注意,即使p1shared_ptr<int>unique_ptr<int> ,此代碼也能正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM