2

I have a vector of pointers to Machines: That is,

vector<Machines*> m; 

I populate the vector with pointers and I know the number of machines that exist. If I created a pointer to a pointer of Machines to the start of the vector:

Machines** m2; m2 = & m[0]; 

would I be accessing the vector members as I increment that '0'?

m2[0]->dostuff; m2[1]->dostuff; ... 

It seems doable to me but I'm not sure if that's allowed. :)

Thank you in advance!

2
  • It's certainly legal, but seems a bit odd when you have a vector already there - side question: why a vector of pointers? Why not just a vector of Machines? Commented Jul 24, 2012 at 0:49
  • 2
    @John3136 probably Machine is a base class, in which case you need pointers to prevent slicing. Commented Jul 24, 2012 at 0:50

3 Answers 3

2

It's allowed, but do you realize you can do the following and there is no reason to use Machines** m2;?

vector<Machines*> m; // Fill vector here m[0]->dostuff(); // I assumed dostuff was a function m[1]->dostuff(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes I know, I was simply wondering if the above would work. I am not coding that way by any means. Thanks a lot for your answer! :)
2

If reallocation of vector memory happens, the pointer in your code will be invalid.

It may happens when pushing elements to vector.

Comments

1

Since vector is guaranteed to allocate continuous memory, this seems correct. But why would you? You have all this functionality directly in vector.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.