www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Seems like compiler could detect use of object that hasn't been "new'ed"

<alert comment="newbie">

Sorry if this has been brought up before.

This C++ programmer was having trouble figuring out why OutBuffer wasn't
working for me. Based on familiarity with that language's constructors, I
expected an object declared locally to be ok.

#import std.outbuffer;
#void main (char[][] args)
#{
#  OutBuffer myBadBuf;   // left off = new OutBuffer;
#  myBadBuf.write("Test myBadBuf"); // access exception
#}

Ouch. With some head scratching, it was yet another "forehead, meet palm"
experience for this newbie.

Obviously easier said than done, but it does seem like the compiler could be
smart enough to detect that I was attempting to use an object that had not
been "new'ed". This might preclude lots of confusion from people with C++
experience. (an aside: does Java have default constructors for local objects
... it has been a while since I programmed in Java)

Even more convenient: it would seem like a default constructor could be
auto-magically invoked in the situation above by the compiler. If not, could
the error message be expanded to inquire if the object was "new'ed"? Could
the automatic initialization of an object be something like 0xcdcdcdcd so
that it would be more obvious what had happened?

Yes, I realize that D is not C++.

Here is MyOutBufferProxyTest.cpp
#class OutBuffer {
#public:
#  void SayHello(void) { printf("Hello from LocalObject\n"); }
#};
#void main(void)
#{
#  printf("Hello from main\n");
#  OutBuffer myOkBuf;
#  myOkBuf.SayHello();
#}

</alert>
Sep 14 2004