Is there any significant difference between the two statements below?
MyClass &ref = *(new MyClass);
MyClass *ptr = (new MyClass);
Is there any significant difference between the two statements below?
MyClass &ref = *(new MyClass);
MyClass *ptr = (new MyClass);
First is a reference, second is a pointer. Reference cannot be changed.
Overall avoid handrolled memory management (this means not writing new/delete at all)
While pointers can be changed, and references cannot, I would still advise against manually manipulating pointers.
A destructor/constructor based memory management can solve so much headache down the line.
I would also consider using smart pointers.
Speaking technically, not hugely.
I mean, you can't rebind ref
to some other thing later, in the same way that you can make ptr
point to something else (though that's arguably a good thing).
The big issue is in expressing intent. We're all conditioned to see a pointer and think "aha, this may be dynamically allocated, and if nothing else I need to be aware of this object's lifetime and ownership semantics to see whether it must be delete
d" (and, if you don't, it's leaked). This is practically never the case with a reference, which we generally take to mean either of:
You're just supposed to use the value and leave it at that.
So, the biggest problem is in clarity of code via conventional coding styles.
But if you were some sort of practical joker you could write the following and it would be perfectly "valid":
int main()
{
int& ref = *(new int);
delete &ref;
}
Just remember to use the address-of operator, to get a pointer again for delete
!
Expression Type Indirection
∧
&&expr T**** |
&expr T*** |
expr T** |
*expr T* |
**expr T |
∨