Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered good style to dereference `new` pointer?

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;
like image 221
mchen Avatar asked May 13 '13 17:05

mchen


People also ask

Can you dereference a pointer?

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.

Is pointer dereferencing expensive?

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.

When would you use a deference operator?

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.

Which is better pointer or reference?

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.


2 Answers

This is not just poor practice, but:

  1. Leaking memory (most likely, unless you are using some pattern that is not visible from the code you provided), since 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;
  2. Most importantly, undefined behavior, since you are passing to 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.

like image 99
Andy Prowl Avatar answered Oct 05 '22 07:10

Andy Prowl


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).

like image 34
Luchian Grigore Avatar answered Oct 05 '22 07:10

Luchian Grigore