2020年3月3日 星期二

莫名其妙的問題

以下程式使用 MinGW 8.1.0 64位元版(x86_64-posix-seh) 編譯

採用 Release 和 Debug 兩種模式編譯的執行結果不一樣(另人傻眼)

本來想說是不是編譯器的 bug,但有以下的訊息:
the compiler can assume that the address of 'p' will never be NULL [-Waddress]

更另人傻眼了

#include <iostream>using namespace std;void f(const char &p = *(char*)nullptr)
{
   
if (&p == nullptr)
     
cout << "p YES" << endl;
   
else
     
cout << "p NO" << endl;
}
int main()
{
 
f();

 
cout << "Hello world!" << endl;
 
return 0;
}


解決辦法只有如下例子,要知道  reference 在哪造成 null  reference,還是得有原始碼才能做 Debug 追蹤,依 C++ 標準及新版編譯器的意圖,也只能強迫使用端做好自家管理

#include <assert.h> /* assert */
#include <iostream>

using namespace std;

void A(const string &Obj)
{
  // gcc 8.1 的 release 模式永遠認定不會是 null
  // 只有 debug 模式才能作比較
  assert(&Obj != nullptr);

  // 做想做的事
  cout << "not null" << endl;
}

void B(const string *pObj)
{
  A(*pObj);
}

int main()
{
  B((string *)nullptr); // 故意給個 null
  cout << "Hello world!" << endl;
  return 0;
}



沒有留言:

張貼留言