Search code examples
c++referenceallocation

c++ allocate *new Object() to reference


I have a question about allocating in c++. I have this code:

vector<unsigned char> &v = *new vector<unsigned char>();

Now the question is, is it generally a good idea to dereference the object and assigning it directly to a reference?

In my opinion, that makes it easier to use the object, because now you can just do:

v.push_back('a');
v[0];

instead of

v->push_back('a');
(*v)[0];

finally, I can do

delete &v;

to free my heap

Just because of the amount of (same) nice answers: I know I can just use a stack-variable but in my case, I need it on the heap! But the question of using a heap or stack-variable is another one.

So I kept this example simple and especially did not asked if I should allocate the variable at all.


Solution

  • It's purely a stylistic issue. None of the places I've worked have used this convention, so it might deroute new people in your organization, but it is a valid convention.

    It should be part of a larger definition of when you use pointers, and when you use references. (And you'll find a lot of variation in this; I've used at least three different conventions in different firms.)