爲什麼這個代碼產生看似隨意的行爲,不可預知的布爾比較C++
std::cout << (thePointerIsGood = (NULL != (aPointer = aFunctionThatReturnsAPointer(args))));
時做同樣的事情這個多層線路版的作品就好了?
aPointer = aFunctionThatReturnsAPointer(args);
thePointerIsGood = (NULL != aPointer);
std::cout << thePointerIsGood;
我捕捉aPointer
和thePointerIsGood
因爲我在後面的代碼上使用它們。
更新
以上實際工作就好了。但是我能夠重現這一程序的一些奇怪的行爲,我已經打上發生錯誤:
// Compiled with:
// gcc test.cpp -c -o test.o; gcc -lstdc++ test.o -o test
#include <iostream>
#include <cstdlib>
class
AClass
{ public
: // Operators ///////////////////////////////////////
; const bool operator== ( const int rhs ) ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
;
class
AHelperClass
{ public
: // Functions //////////////////////////////////////////////////////
; static AClass* AFunctionThatReturnsAPointer ( int arg ) ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
;
const
bool
AClass::
operator==
( const int rhs )
{ return (rhs == 222); }
AClass*
AHelperClass::
AFunctionThatReturnsAPointer
( int arg )
{ return ((arg == 777)
? new AClass
: NULL
)
;
}
int
main
( int argc
, char** argv
)
{ // Variables //////////////////
; AClass* aPointer ;
; bool thePointerIsGood ;
; bool theValueMatches ;
; int i ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
for (i = 0
; i < 10
; i++
)
{ // First a good pointer
std::cout << ((thePointerIsGood = (NULL != (aPointer = AHelperClass::AFunctionThatReturnsAPointer(777))))
? "Y "
: "N "
)
<< ((thePointerIsGood == true)
? "expected "
: "unexpected "
)
;
if (!thePointerIsGood)
{ std::cout << std::endl; }
else
{ // This is where the error is, thanks to Peter for pointing it out
std::cout << ((theValueMatches = ((*aPointer) == 222))
? "Y "
: "N "
)
<< ((theValueMatches == true)
? "expected"
: "unexpected"
)
<< std::endl
;
}
delete aPointer;
// Now a NULL pointer
std::cout << ((thePointerIsGood = (NULL != (aPointer = AHelperClass::AFunctionThatReturnsAPointer(877))))
? "Y "
: "N "
)
<< ((thePointerIsGood == false)
? "expected "
: "unexpected "
)
;
if (!thePointerIsGood)
{ std::cout << std::endl; }
else
{ std::cout << ((theValueMatches = ((*aPointer) == 222))
? "Y "
: "N "
)
<< ((theValueMatches == true)
? "expected"
: "unexpected"
)
<< std::endl
;
}
delete aPointer;
}
return 0;
}
這對我來說將產生以下輸出(一切應該說預期)
Y expected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
Y unexpected Y expected
N unexpected
我建議你不要做,在一個行多任務。但問題很有趣。 – heinrich5991 2012-03-18 19:41:16
'args'是否以任何方式引用'aPointer'和/或'thePointerIsGood'? 'aFunctionThatReturnsAPointer'? – ruakh 2012-03-18 19:43:48
請讓我們看看實際的代碼 – Philipp 2012-03-18 19:43:56