C++ and Java CNI: Check Java references

Mike Harrold mharrold@cas.org
Wed Apr 25 11:48:00 GMT 2001


> 
> >>>>> "Tom" == Tom Tromey <tromey@redhat.com> writes:
> 
>     Tom> * Is there a performance impact for using references instead
>     Tom> of pointers as arguments to methods?  It's hard to believe
>     Tom> there would be one, but I don't know for certain.
> 
> No.  In fact, some things should theoretically go better: the compiler
> knows that references are never NULL.

This isn't true.

#include <iostream>

class MyClass
{
private:
  int x;
public:
  MyClass(int a) : x(a) { }
  int get_x() const { return x; }
};

void bar(MyClass& o)
{
  cout << o.get_x();
}

void foo(MyClass* pointer)
{
  bar(*pointer);
}

int main()
{
  MyClass* test = 0;
  foo(test);
}

The above code compiles just fine. Obviously it segfaults at run-time.
Since gcc essentially treats references and pointers the same way in
the generated assembly code, the "bug" isn't caught by the compiler.

As long as your code NEVER uses pointers anywhere, the above shouldn't
happen, and yes, the compiler knows references are never NULL. However,
as is illustrated above, in reality the only thing the compiler knows
is that references SHOULD never be NULL.

Regards,

/Mike

> 
>     Tom> I think this approach does handle the nonvirtual method call
>     Tom> problem, because operator-> must still be used to compute
>     Tom> `this'.
> 
> I didn't understand this problem, I guess.
> 
> --
> Mark Mitchell                   mark@codesourcery.com
> CodeSourcery, LLC               http://www.codesourcery.com
> 



More information about the Java mailing list