473,671 Members | 2,252 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How does vector construct/destruct objects?

I'm currently learning STL and I hate not knowing what is gooing on "inside"
STL... not because I really _need_ to know it to develop my game project,
but that's just my nature... like most of you at this grounp I suspect.

So the question is:

How does a std::vector construct and destruct the elements in it? I know it
has something to do with an allocator...

Suppose I wrote:
CMyClass *pDynArray = (CMyClass*)mall oc(sizeof(CMyCl ass)*100);

Would it then be posible to construct/destruct the elements one by one in
that array?
I know that this constructs 100 elements at once:
CMyClass *pArray = new CMyClass[100];

.... but acording to my tests std::vector doesn't seem to use that aproach.
--
Lasse
Jul 19 '05 #1
6 4647
"Lasse Skyum" <lskyum(AT)mail .dk> wrote:
I'm currently learning STL and I hate not knowing what is gooing on
"inside" STL... not because I really _need_ to know it to develop my
game project, but that's just my nature... like most of you at this
grounp I suspect.

So the question is:

How does a std::vector construct and destruct the elements in it? I
know it has something to do with an allocator...
Right. It uses the specified (or default) allocator to do it. And the
default one has to use placement new and pseudo destructor calls.
Suppose I wrote:
CMyClass *pDynArray = (CMyClass*)mall oc(sizeof(CMyCl ass)*100);

Would it then be posible to construct/destruct the elements one by one
in that array?
Yes. You can do:

#include <new>

// ...

for (int i = 0; i < 100; ++i)
{
new(pDynArray + i) CMyClass();
}

And later for destroying them:

for (int i = 0; i < 100; ++i)
{
pDynArray[i].~CMyClass();
}

Using an allocator, it looks like this:

std::allocator< CMyClass> a;

CMyClass* pDynArray = a.allocate(100) ;
CMyClass original;
for (int i = 0; i < 100; ++i)
a.construct(pDy nArray + i, original);

This will copy construct the array objects from the original. And for
deletion:

for (int i = 0; i < 100; ++i)
a.destroy(pDynA rray + i);
a.deallocate(pD ynArray, 100);

I know that this constructs 100 elements at once:
CMyClass *pArray = new CMyClass[100];

... but acording to my tests std::vector doesn't seem to use that
aproach.


Jul 19 '05 #2
Thanks a lot! I'm getting somewhere now :-)

--
Lasse
Right. It uses the specified (or default) allocator to do it. And the
default one has to use placement new and pseudo destructor calls.
Suppose I wrote:
CMyClass *pDynArray = (CMyClass*)mall oc(sizeof(CMyCl ass)*100);

Would it then be posible to construct/destruct the elements one by one
in that array?


Yes. You can do:

#include <new>

// ...

for (int i = 0; i < 100; ++i)
{
new(pDynArray + i) CMyClass();
}

And later for destroying them:

for (int i = 0; i < 100; ++i)
{
pDynArray[i].~CMyClass();
}

Using an allocator, it looks like this:

std::allocator< CMyClass> a;

CMyClass* pDynArray = a.allocate(100) ;
CMyClass original;
for (int i = 0; i < 100; ++i)
a.construct(pDy nArray + i, original);

This will copy construct the array objects from the original. And for
deletion:

for (int i = 0; i < 100; ++i)
a.destroy(pDynA rray + i);
a.deallocate(pD ynArray, 100);

I know that this constructs 100 elements at once:
CMyClass *pArray = new CMyClass[100];

... but acording to my tests std::vector doesn't seem to use that
aproach.

Jul 19 '05 #3
On Tue, 28 Oct 2003 10:12:00 -0000, "Lasse Skyum" <lskyum(AT)mail .dk>
wrote:
I'm currently learning STL and I hate not knowing what is gooing on "inside"
STL... not because I really _need_ to know it to develop my game project,
but that's just my nature... like most of you at this grounp I suspect.

So the question is:

How does a std::vector construct and destruct the elements in it? I know it
has something to do with an allocator...

Suppose I wrote:
CMyClass *pDynArray = (CMyClass*)mall oc(sizeof(CMyCl ass)*100);

Would it then be posible to construct/destruct the elements one by one in
that array?


Yes:

CMyClass initialValue(wh atever);
for (int i = 0; i < 100; ++i)
{
//placement new just constructs at the location passed.
//Here we are copying an initialValue, just as vector does.
new(pDynArray + i) CMyClass(initia lValue);
}

and destruction (order reversed for fun):

for (int i = 99; i >= 0; --i)
{
//direct destructor calls:
pDynArray[i].~CMyClass();
}

//and of course (unless you want to reuse the memory)
free(pDynArray) ;

std::allocator uses operator new and operator delete rather than
malloc and free.

That's essentially what goes on inside std::vector, although it
sometimes delegates to the functions allocator::cons truct (which does
placement new with a copy as above) and allocator::dest roy (which just
calls the destructor as above). There is also the algorithm
uninitialized_f ill, which essentially performs the loop above on an
iterator range.

Tom
Jul 19 '05 #4
Thanks Tom,

Just one thing left I don't understand then (about this subject, that is)
.... what happens then, when you use the basic types int,float,doubl e,...
they don't have constructors/destructors(rig ht?) so why don't vector<int>
make compile errors?.

--
Lasse
Jul 19 '05 #5
"Lasse Skyum" <lskyum(AT)mail .dk> wrote:
Thanks Tom,

Just one thing left I don't understand then (about this subject, that
is) ... what happens then, when you use the basic types
int,float,doubl e,... they don't have constructors/destructors(rig ht?)
so why don't vector<int> make compile errors?.


The compiler knows what to do to initialize the memory, since you gave
it the type. If the type is a class type, it means calling the
constructor, and for builtin types, it means just writing a value to
it. After all, you can write:

MyClass a(something);
int i(3);

even though int doesn't have a constructor. It just will initialize i
with the value 3. Doing that with dynamically allocated memory isn't
different:

MyClass* a = new MyClass(soemthi ng);
int* i = new int(3);

well, and with placement new, it's is of course also the same.

Jul 19 '05 #6
Damn I learning stuff today, thanks again!

I've been programming C++ for (say) 5 years now always using my custom
containers and making quite advanced 3D games... seems like I don't even
know the language I've been using! :-o

--
Lasse
The compiler knows what to do to initialize the memory, since you gave
it the type. If the type is a class type, it means calling the
constructor, and for builtin types, it means just writing a value to
it. After all, you can write:

MyClass a(something);
int i(3);

even though int doesn't have a constructor. It just will initialize i
with the value 3. Doing that with dynamically allocated memory isn't
different:

MyClass* a = new MyClass(soemthi ng);
int* i = new int(3);

well, and with placement new, it's is of course also the same.

Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6746
by: john smith | last post by:
Hi, when there is a vector<> of pointers to some objects, does calling resize cause vector to call delete on each object, or is there a memory leak problem? for example: struct base {//some vars; ~base();}; vector<base*> vb; vb.push_back(new base); vb.push_back(new base);
35
3335
by: Ram Laxman | last post by:
I have used vector in the VC++ compiler. I have included #include <string> #include <algorithm> #include <vector> std::vector<int> field; std::vector <int>::size_type i;
0
1742
by: Eric Lilja | last post by:
Hello, I have a text file that contains a number of entries describing a recipe. Each entry consists of a number of strings. Here's an example file with only one entry (recipe): Name=Maple Quill Process=Interim Level=10 Technique=Fletching Knowledge=Woodworking Device=Sawhorse Primary components=Refined Maple
10
2288
by: gogogo_1001 | last post by:
Dear all, I don't understand why "delete" works well on destructing a object, but fails to destruct a vector of it. Any of your comment is highly appreciated! Following is the program that represent this problem:
6
6807
by: zl2k | last post by:
hi, there I am using a big, sparse binary array (size of 256^3). The size may be changed in run time. I first thought about using the bitset but found its size is unchangeable. If I use the vector<bool>, does each element takes 4 bytes instead of 1 bit? I am using gcc3.4.4. There is a bit_vector which is kind of old so I wont use that. Any other choices? Thanks ahead. zl2k
6
1820
by: alan.patterson5 | last post by:
I have a vector of N values and a vector of N functors. I want to apply each functor to its corresponding value. What would be the 'correct' STL way to do this. for_each takes on functor and applies it to every element. So presumably transform is a better option but it also takes one functor. This is obviously easily solved by a variety of methods but I am interested in how the STL would best solve this problem. e.g.
2
2142
by: Jajjo | last post by:
Hey all, First time posting here and just a simple question to begin with. I'm trying to create an iterator for a vector of POINT objects and for some reason, I'm getting this error: error C2275: 'POINT' : illegal use of this type as an expression 1> c:\program files (x86)\microsoft visual studio 8\vc\platformsdk\include\windef.h(331) : see declaration of 'POINT'
0
8476
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
8917
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
8821
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
8670
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
7437
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...
0
5696
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4225
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
2812
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
2
1809
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.