El Hocko
El Hocko

Reputation: 2606

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.

Upvotes: 0

Views: 377

Answers (4)

James Kanze
James Kanze

Reputation: 153909

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

Upvotes: 2

lucasmrod
lucasmrod

Reputation: 260

You could just do:

...
{
    vector<unsigned char> v; // this allocates the vector in the stack
    v.push_back('a');
    v[0];
} 
...

As far as I can see there is no need to allocate the vector in the heap.

You should read about heap and stack memory:

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

Is it generally a good idea to dereference the object and assigning it directly to a reference?

No, not at all.

If you don't need dynamic allocation, because the object only needs to last as long as the current scope, then make an automatic variable instead:

vector<unsigned char> v;

If you do need a dynamic object, then trying to disguise it is a good way to forget that it needs deleting. The best thing is to use a smart pointer so you don't need to remember to delete it at all; failing that, use a pointer.

Upvotes: 5

Martin v. L&#246;wis
Martin v. L&#246;wis

Reputation: 127447

It's not a good idea to store a heap object primarily in a reference variable, for the reason Joachim Pileborg gives in his comment. You ultimately need to delete the object, and that is best done through a pointer variable (in a reference, people will always wonder whether the actual object lives elsewhere).

Upvotes: 0

Related Questions