NULL

C++ のコードをいじっててなんとなく気になった。 実体の無いオブジェクトのメンバ関数は呼べるのか。とりあえずものは試しということで。

#include <iostream>
#include <string>
using namespace std;

class test {
private:
  string name;

public:
  test(string name);
  void hello(void);
};

test::test(string name)
  : name(name) {}

void test::hello(void) {
  cout << "Hello, I am "
       << (this
    ? name
    : "null")
       << endl;
}

int main(void) {
  test* a=new test("SAITO");
  test* b=NULL;
  a->hello();
  b->hello();

  return 0;
}

実行結果はこうなる。

Hello, I am SAITO
Hello, I am null

gccでは一応は期待通りに動く。 C の価値観で見るなら、メンバ変数にアクセスしようとしない限りは問題無いと思うのだが、 C++ で合法なのか疑問。

Document ID: daa8aae8a4399b8a248e0d3c7b6b7b77

時刻:
ラベル:

0 件のコメント:

コメントを投稿