我有一个A类的对象,我想在自定义堆栈对象上分配.为此,我只需将堆栈指针移动到对象大小的字节数并返回其先前的值:
class A : public B {}; //B is from a precompiled library class stack { public: stack(void): _top(&_storage[0]) {} templateinline T* push(void) { T* ptr = static_cast (_top); _top += sizeof(T); return ptr; } //... private: char _storage[1024]; char* _top; }; stack _stack; int main(int argc, char** argv) { A* a = _stack.push(); //ignore the lack of a constructor call return 0; }
Visual C++只是告诉我static_cast无法从char*转换为A*.常规的C样式转换不会给我这个错误,但我宁愿更明确并避免动态转换(A继承自另一个类,但没有贡献给它没有的vtable).在这种情况下,两者之间有什么区别吗?
按设计.
该static_cast
转换的目的不是给无关的指针类型之间的转换,对于需要使用reinterpret_cast
.如果你想明确你正在做的演员,那么使用正确的演员.reinterpret_cast
在这种情况下,C样式转换将执行.
你真的需要研究不同的演员操作,因为评论dynamic_cast
也没有多大意义.
正如其他人所说,解决方案是使用reinterpret_cast
,这意味着在不相关的指针类型之间进行转换时使用:
T* ptr = reinterpret_cast<T*>(_top);
如果使用placement new
相反,您不仅可以避免出现问题,还可以解决不为具有构造函数的类型调用构造函数的问题:
T* ptr = new(_top) T();