To avoid keep having to use ->
and instead work directly with the object, is it acceptable practice to do:
obj x = *(new obj(...));
...
delete &obj;
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
The dereferencing of a pointer shouldn't be much more than copying an address to a (address)register. Thats all. Dereferencing usually means reading from that address as well. Which may vary in cost depending on cache, locality and such.
Essentially, the dereference operator is used when you want to deal with what the pointer is actually pointing to (i.e the thing that is actually at the end of the pointer). So for example, if I have a char *cp = get_string(); , then cp is a pointer that is pointing to the first character in an array of characters.
References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
This is not just poor practice, but:
obj
will store a copy of the original object created by the new
expression, and the pointer to that object returned by new
is lost;delete
a pointer to an object that was not allocated with new
. Per paragraph 5.3.5/2 of the C++11 Standard:[...] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.
No, and in fact this leads to a leak. x
is copy initialized, so the original object pointed to by new obj
is lost.
Just use
obj x(...);
No need for dynamic allocation. Or
obj x = obj(...);
if you must (doubt it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With