0

I have a vector of pointers to an object:

vector<Foo*> bar;

In a method, I am given an Foo object and need to add it to the vector. This is my current attempt:

void push(const Foo &a){
bar.insert(bar.begin(), a);
}

I know this doesnt work because a was passed as a reference, but I can't seem to get the pointer for a to add to bar.

How can I add a to the vector bar?

Flynn
  • 5,903
  • 7
  • 38
  • 55
  • I don't understand the reason why you pass in a reference `const Foo &a`, why don't just pass in the pointer `void push(Foo *a)` – Krypton Oct 02 '12 at 04:06
  • I was having weird results using the actual Foo objects – Flynn Oct 02 '12 at 04:08
  • In that case, the answers down here should help – Krypton Oct 02 '12 at 04:10
  • It would be a bad idea to merely pass the `Foo` by value, because you would then be adding the address of a local `Foo` object that is destroyed/dellocated when the function leaves. – Sion Sheevok Oct 02 '12 at 04:10
  • @chris `Foo` just contains two private strings and a private int. I was given the header for the method, and have to fill the rest in – Flynn Oct 02 '12 at 04:13
  • @Flynn, Yes, I realized from the other comment that it was probably trying to store the copy that did it. – chris Oct 02 '12 at 04:14

4 Answers4

4

You can't put an object in a container of pointers.

If you want to put an object in, then you'll need a container of objects:

vector<Foo> bar;

In that case, all the objects must be of the same type; if Foo is actually a base class, and you want to store a variety of different derived types, then you'll need to store pointers.

If you want a container of pointers, then you'll need to put a pointer in it:

bar.insert(bar.begin(), &a);

In that case, you need to take care with the object's lifetime, and make sure you don't use the pointer after the object is destroyed. Smart pointers might be helpful.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Add the address of a. Pointers store addresses, which is how they point to something.

bar.insert(bar.begin(), &a);

I'm presuming you have a good reason for using pointers, but make sure the a being passed in isn't temporary and that the object you pass in outlives the vector so that you don't end up with a dangling pointer.

chris
  • 60,560
  • 13
  • 143
  • 205
0

Correct me if I am wrong, but a is not a pointer in that code, even though it is passed by reference. You should be able to use & on it to gets it's address, correct?

jmurrayufo
  • 379
  • 2
  • 5
  • 14
0

Just take the address of a. The reference really is just that, a reference, so taking the address of it actually yields the address of what it refers to.

void push(const Foo& a)
{
    bar.insert(bar.begin(), &(a));
}
Sion Sheevok
  • 4,057
  • 2
  • 21
  • 37