Flynn
Flynn

Reputation: 6181

C++ Vector of pointers, add referenced variable

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?

Upvotes: 0

Views: 111

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254431

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.

Upvotes: 4

Sion Sheevok
Sion Sheevok

Reputation: 4217

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

Upvotes: 0

jmurrayufo
jmurrayufo

Reputation: 499

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?

Upvotes: 0

Qaz
Qaz

Reputation: 61900

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.

Upvotes: 1

Related Questions