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: -
vector<SomeClass> someVector;
-
for (int i=0; i<args.size(); i++){
-
someVector.push_back( SomeClass(args[i]) )
-
}
-
So instead, I used a temporary variable and stored pointers inside the vector instead: -
vector<SomeClass *> someVector;
-
for (int i=0; i<args.size(); i++){
-
SomeClass temp(args[i]);
-
someVector.push_back(&temp);
-
}
-
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!
4 26952 JosAH 11,448
Recognized Expert MVP -
vector<SomeClass *> someVector;
-
for (int i=0; i<args.size(); i++){
-
SomeClass temp(args[i]);
-
someVector.push_back(&temp);
-
}
-
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: -
vector<SomeClass *> someVector;
-
for (int i=0; i<args.size(); i++){
-
SomeClass* temp= new SomeClass(args[i]);
-
someVector.push_back(temp);
-
}
-
See the difference?
kind regards,
Jos
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: -
vector<SomeClass *> someVector;
-
for (int i=0; i<args.size(); i++){
-
SomeClass* temp= new SomeClass(args[i]);
-
someVector.push_back(temp);
-
}
-
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]))
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
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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)
===========================================
|
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
|
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++.
|
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.
| |
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:
|
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(
|
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...
|
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...
|
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
{
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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...
|
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
| |