2009-10-07 64 views
3

我初始化一個auto_ptr爲NULL,後來在遊戲中我需要知道它是否有NULL或不返回它或新副本。三元運算符對auto_ptr內容不起作用

我已經試過這

auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext(); 

和其他一些類似的東西,鑄造等,但G ++試圖調用auto_ptr對象不存在操作? (三元運算符),而不是使用RequestContext *進行三元比較。

即使我施放它也行不通。

任何提示?

編輯的相等非等

+0

你說的「不工作」是什麼意思?您是否收到編譯錯誤消息,或者運行時行爲錯誤(您獲取的行爲是什麼)?爲什麼只有當它返回NULL時才返回mReqContext? – dave4420 2009-10-07 13:53:09

+0

你是什麼意思,「g ++試圖調用auto_ptrs不存在的操作符?」 ? – 2009-10-07 13:53:35

+0

顯然假設有過載(但?:不可重載) – MSalters 2009-10-07 14:24:38

回答

20

我假設的情況是類似以下內容:

#include <iostream> 
#include <memory> 

int main() 
{ 
    std::auto_ptr<int> a(new int(10)); 
    std::auto_ptr<int> b = a.get() ? a : new int(10); 
} 

這裏還有科莫的很有啓發性的錯誤信息:

"ComeauTest.c", line 7: error: operand types are incompatible ("std::auto_ptr<int>" 
      and "int *") 
     std::auto_ptr<int> b = a.get() ? a : new int(10); 
             ^

三元運營商需要兼容類型的兩個結果,你不能有它在一種情況下返回用戶定義的對象,在另一種情況下返回一個裸指針。 NB!std::auto_ptr發生在一個明確構造函數的指針,這意味着三元運算符不能隱式轉換的第二個參數std::auto_ptr

和可能的解決方案:

std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10)); 
+0

是不是有關auto_ptr的顯式構造函數而不是關於三元運算符的問題? – Chubsdad 2010-11-25 13:10:54

1

嘗試

auto_ptr<RequestContext> ret; 
ret.reset(new stuff here); 
+0

這是一樣的,分配的右側是問題,而不是左側。 – 2009-10-07 13:43:04

0

你嘗試,打破了成兩行呢?

RequestContext *p = (mReqContext.get() == 0) ? mReqContext : new RequestContext(); 
auto_ptr<RequestContext> ret = p; 
0

你試過把它全部放進大括號?

auto_ptr<RequestContext> ret = 
    (mReqContext.get() == 0) ? (mReqContext) : (new RequestContext()); 
+0

大括號不是問題,它是兩側的不同類型: – sbk 2009-10-07 14:05:08

+0

是的,自從UncleBens的回答以後,我也知道這一點。我只是在猜測像其他人一樣... – foraidt 2009-10-07 14:31:26

0

確保你沒有指定指向auto_ptr的指針,這是行不通的。 然而,所有這些片斷編譯就好:

#include <memory> 
#include <string> 

using namespace std; 
int main(int argc, char * argv[]) 
{ 
    auto_ptr<int> pX; 
    pX.reset(pX.get() ? new int(1) : new int(2)); 
    pX = auto_ptr<int>(pX.get() ? new int(1) : new int(2)); 
    pX = auto_ptr<int>((pX.get()==NULL) ? new int(1) : new int(2)); 

    return 0; 
} 
2

mReqContextauto_ptr<RequestContext>型的,對不對?然後,問題可能是:兩邊的不兼容類型,因爲new RequestContext()產生一個RequestContext *,但兩者必須具有三態運算符可用的通用類型。

可能的解決方案:要麼使用

auto_ptr<RequestContext>(new RequestContext) 

:的右側或使用

mReqContext.get() 

:的左側。

在這兩種情況下:小心與auto_ptr指針所有權問題! auto_ptr中的(原始)指針只能由一個auto_ptr對象擁有,所以我的兩個「簡單」解決方案可能都不是您想要的(第一個非零時清除mReqContext,第二個不但可能導致重複刪除mReqContext)。