473,791 Members | 3,097 Online
Bytes | Software Development & Data Engineering Community
+ 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_p tr 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 26952
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<SomeClas s *> 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
2136
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 objects to hold data. This in itself isn't a problem however the java code makes heavy use of Vector.insertElementAt(). This method inserts into the vector container at a desired location and shifts the indexes of all the other items accordingly...
4
6208
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 (prerelease) ===========================================
1
19609
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 grow a vector it may copy all of its elements to different memory location to accomodate the new vector size. Is it possible that at some point an element of fixed array e.g. a_vStr gets invalid or
5
1519
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 supposed to search for some characters (2 or 1) and replace them with their equivalent Arabic characters from an array vector<string>. I have been debugging it on Linux for like 6 hours, and it's really boring that it works on vc++.
9
2403
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? Thanks your help.
6
2582
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 "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
14
500
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
1387
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 to implement 'operator()' s.t. I can treat parts of a vector in the same way as a normal vector: if v.foo(...) works, so should v(rng).foo(...), where rng is a range object. This should work even if 'foo' is a non-const method. I do this by...
167
8361
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 object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
4
1473
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
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5431
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4110
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 we have to send another system

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.