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?

6
  • 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) Commented Oct 2, 2012 at 4:06
  • I was having weird results using the actual Foo objects Commented Oct 2, 2012 at 4:08
  • In that case, the answers down here should help Commented Oct 2, 2012 at 4: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. Commented Oct 2, 2012 at 4: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 Commented Oct 2, 2012 at 4:13

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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?

Comments

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.