On Fri, 29 Apr 2011 11:08:24 -0400 (EDT) dnovi...@google.com (Diego Novillo) wrote:
> This patch from Le-Chun Wu adds support to check whether a nonnull > attribute is applied to 'this' pointer for non-static methods. This bring me to a question. Does the C++ standard imply that this is never a null pointer? (Last time I looked into a C++ standard, I was not able to give a firm answer). In other words, with class Myclass { int x; public: Myclass(int z=0): x(z) {}; int get(void) const { if (this) return x; else return 0; }; ~Myclass() { }; }; can a C++ standard conforming compiler optimize the get () member function to inline int Myclass::get(void) { return x; }; (I tend to believe that such an optimization is incorrect, but I am not sure). can a C++ program call Myclass *t = null_ptr; return t->get(); (I might believe this is not conforming to standards) I feel that testing that this is not null is occasionnally useful. For instance, if I coded a trivial interpreter (e.g. of a Lua or Python or Lisp-like language) I would be tempted, if that language has a nil value, to implement values as pointers to objects and to represent nil as a C++ null_ptr. So I might even want to code something like // my abstract top superclass for values class Value { virtual ~Value() {}; Value () {}; virtual void do_print(void) const = 0; public: void print(void) const { if (this) this->do_print(); }; }; class IntegerValue : public Value { int x; public: IntegerValue (int z) : Value(), x(z) {}: virtual void do_print (void) { cout << x; }; }; But I am not sure that such code is standard C++. However, GCC seems to compile it as I expect! At least I still hope that future versions of GCC would accept it (perhaps in some permissive mode, or with warnings) Regards. PS: By standard C++, I mean some recent or future C++ ISO standard (eg C++1x or C++0x). -- Basile STARYNKEVITCH http://starynkevitch.net/Basile/ email: basile<at>starynkevitch<dot>net mobile: +33 6 8501 2359 8, rue de la Faiencerie, 92340 Bourg La Reine, France *** opinions {are only mine, sont seulement les miennes} ***