[英]C++ way to assign an array of char to a T* in a const method of a class
我想在堆棧上使用一些內存來存儲一些對象(它出現在一個小的向量優化庫中)。 所以我的課是
template <typename T, int n>
class SmallVector {
private:
T* begin_;
T* end_;
T* capacity_;
alignas(T) char data_small_[n * sizeof(T)];
public:
...
}
要檢查是否使用了small_data_緩沖區,我定義了該函數
bool is_data_small_used() const {
return begin_ == reinterpret_cast<T*>(data_small_);
}
不幸的是,它不起作用。 lang版
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix
給我以下錯誤信息:
./il/container/SmallVector.h:44:25: error: reinterpret_cast from 'const char *' to 'il::Vector<double> *' casts away qualifiers
return begin_ == reinterpret_cast<T*>(data_small_);
英特爾編譯器也是如此。 我發現的唯一解決方案是做
begin_ == (T*) data_small_
這不是C ++。 在C ++中是否有“正確的方法”做到這一點?
該錯誤消息表明該問題正在const
成員函數內部發生。 在那種情況下, this
被認為指向const對象,因此data_small_
將具有const char[N]
類型。
一個簡單的解決方法是編寫:
return begin_ == reinterpret_cast<T const *>(data_small_);
另一個是:
return reinterpret_cast<char const *>(begin_) == data_small_;
C樣式const_cast
之所以起作用,是因為該const_cast
一起執行reinterpret_cast
和const_cast
,而reinterpret_cast
本身不能const_cast
const
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.