長的故事:安全使用無效*指針對象
目前,我分配了需要被更新到新的相機設備集成了傳統的C項目的工作。從設備製造商的API很簡單,我需要的是包括自己的頭文件和庫到類與設備的工作,例如這裏是一個代碼示例代碼段:
MyClass.h
#include <XFactory.h>
...
public:
XFactory::device myDevice;
XFactory::xSmartPtr myPtr;
與設備集成:
MyClass.cpp
#include "MyClass.h"
...
myDevice.GetInfo();
myPtr.GetFrame();
..ect.
但生活總是給你檸檬。每當我#include MyClass.h
到主項目。類似這樣的編譯錯誤拋出:
...
/usr/include/c++/4.8/bits/stl_algobase.h:193:5: note: template<class _Tp> const _Tp& std::min(const _Tp&, const _Tp&)
...
做了一些研究,我認爲#include <XFactory.h>
調用一些C++頭是與衝突在我的項目的一些類定義的宏(如最小/最大...)。我不能修復這些代碼,這不是我的,所以這裏是我的醜陋的解決方法我的課:
短篇小說:
MyClass.h
typedef void* DeviceHandle_t;
typedef void* FrameHandle_t;
public:
DeviceHandle_t myDevice;
FrameHandle_t myPtr;
MyClass的.cpp
#include <XFactory.h> //to avoid main project include this header
MyClass::MyClass(){
myDevice = new XFactory::device();
myPtr = new XFactory::xSmartPtr();
}
MyClass::~MyClass(){
if (myDevice != NULL){
delete (XFactory::device*)myDevice; //this will call class's destructor, won't it?
myDevice = NULL;
}
if (myDevice != NULL){
delete (XFactory::xSmartPtr*)myPtr ; //this will call class's destructor, won't it?
myPtr = NULL;
}
}
要與dev冰:
((XFactory::device*)myDevice)->GetInfo();
((XFactory::xSmartPtr*)myPtr)->GetFrame();
是的,我無法使用智能指針,因爲我的項目是C99,和我幾乎都在用C/C++指針的工作經驗,是我的解決方法安全?是否有任何其他解決方案不使用原始指針?
您的代碼似乎是C++,並且不合法C.另外,您的變量定義應該位於.cpp中,而不是頭文件中。也不應該myDevice和myPtr是成員變量而不是全局? –
您關心哪些安全特性?通過使用void指針簡單地泄漏內存或類型安全的投降?至於是否調用析構函數,你不能自己測試嗎? –
也許你正在使用''而忘記定義'NOMINMAX'。總是這樣做。 –