473,466 Members | 1,376 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C++ Vector of objects

1 New Member
Hello,

I'm just starting to learn C++, coming from a Java / bit of C background. I have some questions about how vectors of objects and pointers work in C++.

Say I want to create a vector of SomeClass objects, and the SomeClass constructor takes one argument. However, SomeClass is not copyable, so I can't do something like:
Expand|Select|Wrap|Line Numbers
  1. vector<SomeClass> someVector;
  2. for (int i=0; i<args.size(); i++){
  3.     someVector.push_back( SomeClass(args[i]) )
  4. }
  5.  
So instead, I used a temporary variable and stored pointers inside the vector instead:
Expand|Select|Wrap|Line Numbers
  1. vector<SomeClass *> someVector;
  2. for (int i=0; i<args.size(); i++){
  3.     SomeClass temp(args[i]);
  4.     someVector.push_back(&temp);
  5. }
  6.  
However, all the pointers in someVector ended up pointing to temp(args[args.size()-1]). I've resolved this by using boost::shared_ptr instead, but I wanted to understand why the above code didn't work as expected. I thought that in each iteration of the for loop, a new temp will get created, and a reference to it will be stored in someVector (so that it won't garbage collected or w/e since there's still a reference to it). The same thing also seems to happen when I make a vector of a struct...

From general Googling, I get the feeling that in general, it's probably a good idea to get into the habit of storing pointers instead of actual objects and structs in vectors - so I should probably get used to using vectors of shared_ptr?

Also, any other general comments, tips, common gotchas, etc. will be greatly appreciated (trying to learn all I can!).

Thanks!
Aug 11 '07 #1
4 26935
JosAH
11,448 Recognized Expert MVP
Expand|Select|Wrap|Line Numbers
  1. vector<SomeClass *> someVector;
  2. for (int i=0; i<args.size(); i++){
  3.     SomeClass temp(args[i]);
  4.     someVector.push_back(&temp);
  5. }
  6.  
However, all the pointers in someVector ended up pointing to temp(args[args.size()-1]).
Yep, 'temp' is just a local variable and no matter how many times your evaluate
'&temp' it'll always be the address of that same local variable. Do this instead:

Expand|Select|Wrap|Line Numbers
  1. vector<SomeClass *> someVector;
  2. for (int i=0; i<args.size(); i++){
  3.     SomeClass* temp= new SomeClass(args[i]);
  4.     someVector.push_back(temp);
  5. }
  6.  
See the difference?

kind regards,

Jos
Aug 11 '07 #2
Darryl
86 New Member
Yep, 'temp' is just a local variable and no matter how many times your evaluate
'&temp' it'll always be the address of that same local variable. Do this instead:

Expand|Select|Wrap|Line Numbers
  1. vector<SomeClass *> someVector;
  2. for (int i=0; i<args.size(); i++){
  3.     SomeClass* temp= new SomeClass(args[i]);
  4.     someVector.push_back(temp);
  5. }
  6.  
See the difference?

kind regards,

Jos
and since now you are using new, you can drop the temp and go back to your original design someVector.push_back(new SomeClass(args[i]))
Aug 11 '07 #3
oscarin43
1 New Member
Hi. Respect to the example. Could you please tell me the right way to delete all the memory allocated from this piece of code.

i believe that i have to do something like this.

vector<SomeClass *> someVector;

for (int i=0; i<args.size(); i++){
SomeClass* temp= new SomeClass(args[i]);
someVector.push_back(temp);

delete temp; // Is necessary??
}

//and next;

int VecSize = someVector.size();
for (int i=0; i<VecSize; i++)
{
delete someVector[i]; //Is correct?
}

thanks for your help
Feb 28 '12 #4
abcde456
1 New Member
don't delete temp within assignment for loop

//do all the work you wanted to do with someVector
// then delete like you showed in the last forloop, before you go out of scope
Mar 5 '13 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: William Krick | last post by:
I've been given the task of converting some existing java code to PHP so we can integrate it into our web based product. The problem I'm facing is that the java code makes heavy use of Vector...
4
by: Alex Vinokur | last post by:
Is it possible to use vector<ostringstream> ? Here is what I have got. =========================================== Windows 2000 CYGWIN_NT-5.0 1.3.22(0.78/3/2) GNU gcc version 3.2 20020927...
1
by: TF | last post by:
I have a fixed array of vectors like: vector<string> a_vStr; Then I grow each vector item and use it later. Everything works fine but I am curious about following potential problem. When we...
5
by: Ahmad | last post by:
Hi all, I have written a simple c++ app, as I'm still learning c++. The thing works flawlessly on VC++6, but just doesn't work on g++. The transliterate function which causes the problem is...
9
by: cylin | last post by:
Dear all, Using sizeof(vector<TYPE>) will always return 16 bytes. If I have N elements ( integer ), the total memory is sizeof(vector<int>)+sizeof(int)*N, or sizeof(vector<int>)*N, or others?...
6
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a...
14
by: Christian Christmann | last post by:
Hi, what is the most efficient way to insert a new element into an STL vector before a given element? My idea was: vector< Objects myVector; myVector.push_back( ... myVector.insert(
0
by: mseeger | last post by:
My concrete problem is this (it is a bit special, but there may be other instances of it): I'd like to create a class for vectors (say: Vector), exporting math. methods, say v.foo(...). I'd like...
167
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an...
4
by: alexjcollins | last post by:
The following program demonstrates the problem: #include <vector> #include <iostream> #include <tvmet/Vector.h> typedef tvmet::Vector<double, 3Vector3d; class Mesh {
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.