Newbie question on vectors of pointers

K

kelvSYC

My mind seems to be having a brain freeze. Anyways, here goes:

I have a function that constructs an A from some other data, like so:

A foo();

and I would like to add something returned from it into a
std::vector<A*> elsewhere in my code. To do so, do I just do so, like

std::vector<A*> list;
list.push_back(&foo());

Or do I have to change foo() so that it returns a pointer? If so, (and
here's where my knowledge of C++ is shaky), can I only return something
that's allocated using new? If so, will that item be automatically
deleted once the vector is deallocated (or would I have to write
something extra?
 
A

Axter

kelvSYC said:
My mind seems to be having a brain freeze. Anyways, here goes:

I have a function that constructs an A from some other data, like so:

A foo();

and I would like to add something returned from it into a
std::vector<A*> elsewhere in my code. To do so, do I just do so, like

std::vector<A*> list;
list.push_back(&foo());

Or do I have to change foo() so that it returns a pointer? If so, (and
here's where my knowledge of C++ is shaky), can I only return something
that's allocated using new? If so, will that item be automatically
deleted once the vector is deallocated (or would I have to write
something extra?

foo() should be returning something that will exist outside the scope
of foo().
More then likely it would need to be something created via new
operator.
And you would then have to delete this before clearing your vector.

You haven't stated why you're using a vector of pointers.
You probably don't need it to be pointers, and instead you should have
a vector of concrete type.
std::vector<A> Myvect;
Then you can leave foo as is.
Myvect.push_back(foo());
I also recommend not naming your objects by the same name as other
objects in the STL, like list.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top