Calling a constructor
I have an instantiated class, with the initialization code in the constructor.I want to be able to call the constructor again (to reset object data) without moving the reference to the object. Is there an easy way to do this? I don't want to have to put data initialization into a separate function.
> > // Java ain't no C++
> void T::reinit() {
> delete this;
> *this = * ( new T());
> }
>
...and that ain't no C++ either ;-)
Sorry for the off-topic reply, but that code cannot stand uncorrected.delete this;
Only valid for heap-constructed objects, which you can't be sure of inside the function. Will crash otherwise.
If "this" was in fact on the heap, execution might indeed reach this line:
*this = * ( new T());
...only to crash there, since it's an illegal dereferencing of "this", which has just been deleted.
(Surviving the Access Violation, you'd then have a memory leak, since new T() will never be deleted.)
The correct C++ way of doing a re-initialization would make use of placement-new.
void T::reinit()
{
T::~T();
new(this) T();
}
Exception in thread "main" java.lang.VerifyError: (class: Reconstructor, method: reconstruct signature: (Ljava/lang/Object;)V) Expecting to find unitialized object on stack
Friggin' class verifier won't let me call <init>() to reconstruct :-)
You can reinitialize an object if you disable the class verifier and write a bit of Java bytecode assembly language to call <init>(). You may want to set all instance variables to zero/null first. No, I'm not seriously suggesting anyone should do this.
> I was sure it was possible somehow in C++! > Now we learned how, thanks for posting. > > Java still ain't no C++.True, but can you knock Java for trying? :P