在 class 的 const 方法中将 char 数组分配给 T* 的 C++ 方法

C++ way to assign an array of char to a T* in a const method of a class

我想在堆栈上使用一些内存来存储一些对象(它出现在一个小型向量优化库中)。因此,我的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_);
}

不幸的是,它不起作用。 Clang 版本

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++ 中是否有 "correct way" 来执行此操作?

错误消息表明问题发生在 const 成员函数内部。在这种情况下,this 被认为指向一个常量对象,因此 data_small_ 的类型为 const char[N]

一个简单的解决方法是写:

return begin_ == reinterpret_cast<T const *>(data_small_); 

另一个是:

return reinterpret_cast<char const *>(begin_) == data_small_;

C 风格的强制转换之所以有效,是因为该强制转换可以一起执行 reinterpret_castconst_cast,而 reinterpret_cast 本身不能丢弃 const