2012-01-30 30 views
2

有沒有辦法檢測p和d指向的對象是不同類型的? (p指向int和d點整數數組):檢測我指的是什麼

int* p = new int(); 
int* d = new int[20]; 
+0

你爲什麼要檢測呢?這是無法做到的。 – 2012-01-30 17:44:41

+0

是的,在聲明之後用方括號(OK,這是一個愚蠢的評論) – 2012-01-30 17:46:11

+0

這不完全是你問的,但它是相關的。編譯器可能爲了優化目的跟蹤類似的詳細類型信息。 http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule – 2012-01-30 17:52:59

回答

6

...對象由p和d指出不同類型的? (p指向int和d指向int整數):

那麼,首先,這是不正確的。是的,d指向一個數組的開始,但是它們都指向完全相同的東西;一個int。您是否可以安全地對指針執行算術運算並對其進行解引用是另一個問題。

當您解除引用它們時,機器會簡單地返回一個適當大小的內存塊並將其解釋爲int。

C++並不完全是元編程的goto語言,如果你在處理指針,它究竟有什麼關係嗎?我從來沒有發現需要這樣做。你知道你有一個指針,你(應該)知道它是指向一個int還是一堆int s,因此你究竟是在試圖解決什麼問題?

+0

#編輯「問題」是,我希望能夠寫delete_(p),並根據「類型「它會調用delete p或delete [] p; – smallB 2012-01-31 17:33:06

+0

@smallB:你只需要知道你開始分配什麼。爲什麼這很難?而不是要求一個沒有任何意義的解決方案,只要告訴我們你實際上想要解決什麼問題。我從不需要在運行時確定*刪除哪個版本。 – 2012-01-31 17:36:11

+0

#Ed我沒有說我需要在運行時檢測它。我只是想要「智能」刪除,這將使我無法檢查要刪除的內容,數組或不是。而已。現在它更有意義嗎? – smallB 2012-01-31 17:40:59

0

我會說沒有。 p和d都是指向int的指針,d是指向數組頭的指針 - 頭是int。整數的

數組不是d的類型 - 它是一個指針到int

-1
#include <iostream> 
#include <typeinfo> 

using namespace std; 

int main() 
{ 
    int* p = new int(); 
    int* d = new int[20]; 
    float* f = new float(); 

    if (typeid(p) == typeid(d)) 
      cout << "equal" << endl; 
    else 
      cout << "not equal" << endl; 

    if (typeid(p) == typeid(f)) 
      cout << "equal" << endl; 
    else 
      cout << "not equal" << endl; 

} 

輸出:

equal 
not equal 

有一種方法來檢測,如果由p和d指出對象是不同的類型?

你的假設是錯誤的。 p和q都指向相同的類型,int。

+0

-1它們都是指向int的指針......即使是'typeid(* p)'(對於'q'也是一樣)只是'int'。 – 2012-01-30 17:48:48

+0

*是的,你可以,但你的例子是指向相同的類型。* - 所以答案是......不,你不能。 – 2012-01-30 17:54:38

-1

如果您實現自己的newnew[]你可以,但這裏的龍會吃你還活着:

void * operator new(size_t size) 
{ 
    size_t * allocation = (size_t *)malloc(size+sizeof(size_t)); 
    *allocation = size; 
    return allocation + 1; 
} 

void * operator new[](size_t size) 
{ 
    size_t * allocation = (size_t *)malloc(size+sizeof(size_t)); 
    *allocation = size; 
    return allocation + 1; 
} 

template<typename T> size_t allocationCount(T*memory) 
{ 
    size_t * allocation = reinterpret_cast<size_t*>(memory) - 1; 
    return *allocation/sizeof(T); 
} 

int main() 
{ 
    int * fred = new int; 
    int * nurk = new int[30]; 
    cout << allocationCount(fred) << endl; 
    cout << allocationCount(nurk) << endl; 
} 

輸出:

1 
30 
+0

呃!真?這種不可能實現的不足和不可用的方法。你有沒有考慮過'new int [1]'?一旦你處理了這個問題,你就可以轉移到其他幾十個人面前,試圖讓這個工作起作用。 – 2012-01-30 19:24:18

+0

很高興你喜歡它! – Slagh 2012-01-30 20:19:32