473,881 Members | 1,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Containers & Allocators

Hello,

I am trying to create a container the stl way, and I have a couple of
questions. The code of the container in question can be found at

http://www.cs.kuleuven.ac.be/~ares/tmp/array_2_hpp.html

It is a 2d array that dynamically allocates its storage. It cannot be
resized. It offers element access methods for both sequential access and 2d
element access.

It allocates one big chunk of memory.
To avoid computing 1D indices from 2D indices like:

T* elements
elements = new T[rows * cols]
....
return elements[i + (j * cols)]

it then allocates an array of row pointers, that point in this big chunk of
memory:

T** elements
elements = new T*[...] // row pointers
elements[0] = new T[rows * cols] // actual storage
// set row pointers
....
return elements[i][j]

On the systems I tested, this made a lot of difference.

I have the following questions / thoughts on which I would appreciate
comments.

1) I need two kinds allocators (one for T's and one for T*'s). The exception
safe constructors seem overly complicated. For array_3 I would need an
additional allocator for T**'s, and almost 10 try/catch constructs.

2) Can allocator::deal locate() throw ? I had expected a no throw
declaration.

3) Whats the deal with the allocators ? Do they have instace variables or
not ? Do I need to store them or not ?

4) The std::uninitiali zed* functions seem to be unusable in this context ?

5) Have a look on how the begin() and end() are implemented. If the size of
the array is 0, then they both return the 0 pointer. Is this OK ?

6) In swap, do the allocators also need to be swapped?

7) std::swap is very important, but it cannot be partially specialized, and
you cannot define an overload in the std namespace ? How do I handle that ?

best regards,
Ares Lagae
Jul 23 '05 #1
6 1520
Sorry for not responding for your questions but why do you force in the
"opened door" ? ;)

--
the code is my strength
SirMike
Jul 23 '05 #2
SirMike wrote:
Sorry for not responding for your questions but why do you force in the
"opened door" ? ;)


I hope you are not suggesting to use a std::vector< std::vector<T> >, which
is quite a different beast than a 2D array according to me.

The question is not how to get a 2d array in C++, rather how to create an
array_2 class "the stl way", but you do have a point.

Ares
Jul 23 '05 #3
In article <11************ ***@seven.kulne t.kuleuven.ac.b e>,
Ares Lagae <ar********@cs. kuleuven.ac.be> wrote:
I have the following questions / thoughts on which I would appreciate
comments.
Apologies in advance for not studying your code (though I did glance at
it). But I felt I might be able to give a helpful response anyway.
1) I need two kinds allocators (one for T's and one for T*'s). The exception
safe constructors seem overly complicated. For array_3 I would need an
additional allocator for T**'s, and almost 10 try/catch constructs.
I find the easiest way to write code like this is to separate the class
into a private base class that implements everything but resource
acquiring constructors, and a derived class that implements the resource
acquiring constructors. Bjarne's Appendix E may help illustrate:

http://www.research.att.com/~bs/3rd_safe0.html

If a (derived) resource acquiring constructor throws an exception, the
base class will (should) clean up all resources already acquired.

It is possible that this idiom will be obsoleted in C++0X if we get
"Delegating Constructors":
http://www.open-std.org/jtc1/sc22/wg...2004/n1618.pdf .
2) Can allocator::deal locate() throw ? I had expected a no throw
declaration.
No, throwing in deallocate is forbidden by 20.1.5p2 (in the C++
standard).
3) Whats the deal with the allocators ? Do they have instace variables or
not ? Do I need to store them or not ?
They usually don't have instance variables, but they can. Imho, the
highest quality solution is to store them using boost::compress ed_pair:

http://www.boost.org/libs/utility/compressed_pair.htm

This is a pair-like utility that will optimize away the space for a
member that is "empty". By pairing an allocator with some member that
you know not to be empty (like size or whatever), you can effectively
compute at compile time whether you need to allocate space for your
allocator(s).
4) The std::uninitiali zed* functions seem to be unusable in this context ?
Imho yes. Although it is fuzzy whether it is required to use the
allocator's construct function (is allocator::cons truct a customization
point, or merely a convenience function for placement new?).
5) Have a look on how the begin() and end() are implemented. If the size of
the array is 0, then they both return the 0 pointer. Is this OK ?
Without studying your specific implementation, in general yes, it is ok.
6) In swap, do the allocators also need to be swapped?
The standard does not specify what should happen with unequal allocators
(those that can not deallocate each other's pointers). Therefore there
is no need to swap allocators if they are all equal. However, what to
do with unequal allocators is currently a controversial point. There is
a defect report on it here:

http://www.open-std.org/jtc1/sc22/wg...ctive.html#431

And my (strongly held) opinion is here:

http://www.open-std.org/jtc1/sc22/wg...004/n1599.html
7) std::swap is very important, but it cannot be partially specialized, and
you cannot define an overload in the std namespace ? How do I handle that ?


Put swap in the same namespace as array_2. See lwg defect reports 225,
226 and 229, and the proposed resolution here:

http://www.open-std.org/jtc1/sc22/wg...2003/n1523.htm

-Howard
Jul 23 '05 #4

"Ares Lagae" <ar********@cs. kuleuven.ac.be> wrote in message
news:11******** *******@seven.k ulnet.kuleuven. ac.be...
Hello,

I am trying to create a container the stl way, and I have a couple of
questions. The code of the container in question can be found at

http://www.cs.kuleuven.ac.be/~ares/tmp/array_2_hpp.html

It is a 2d array that dynamically allocates its storage. It cannot be
resized. It offers element access methods for both sequential access and 2d element access.

[snip]

Looks like you may be re-inventing the wheel here ... if you are doing it to
better understand the inner workings, then go for it, and more power to you.
But if you just want a well-designed, performance-tuned Matrix class, then
have a look at the options at the Object Oriented Numerics site:

http://www.oonumerics.org/oon/

HTH,

Dave Moore
Jul 23 '05 #5

"Ares Lagae" <ar********@cs. kuleuven.ac.be> wrote in message
news:11******** *******@seven.k ulnet.kuleuven. ac.be...
Hello,

I am trying to create a container the stl way, and I have a couple of
questions. The code of the container in question can be found at

http://www.cs.kuleuven.ac.be/~ares/tmp/array_2_hpp.html

It is a 2d array that dynamically allocates its storage. It cannot be
resized. It offers element access methods for both sequential access and 2d element access.

It allocates one big chunk of memory.
To avoid computing 1D indices from 2D indices like:

T* elements
elements = new T[rows * cols]
...
return elements[i + (j * cols)]

it then allocates an array of row pointers, that point in this big chunk of memory:

T** elements
elements = new T*[...] // row pointers
elements[0] = new T[rows * cols] // actual storage
// set row pointers
return elements[i][j]

On the systems I tested, this made a lot of difference.

Are you sure? Integer arithmetic for array addressing has never
significantly affected the performance of any numerical code I have used.
After all, in C++, a[9] is equivalent to *(a+9), so the integer arithmetic
is implied anyway.
I have the following questions / thoughts on which I would appreciate
comments.

1) I need two kinds allocators (one for T's and one for T*'s). The exception safe constructors seem overly complicated. For array_3 I would need an
additional allocator for T**'s, and almost 10 try/catch constructs.
Well, as I said, I think you are doing things in an unnecessarily
complicated fashion. I cannot see the need for 2-D data *allocation* as you
are currently doing ... that is only needed if the rows of the matrix can
have different lengths, which is not the case in your design. Why not
simply use 1-D allocation a-la vector<T> (or maybe valarray<T>) as the
underlying implementation? This gets rid of the need for the elaborate
allocation of pointers-to-pointers as you are currently doing. At the very
least you should use a T* (and not a T**) to point to the allocated data,
and you won't need all of that try .. catch stuff that currently makes your
constructor definitions virtually impenetrable.
How you do the addressing of such data is an implementation detail. You
could do address arithmetic, or store your "rows" using a vector<T*>, or
even a T** (but only with "first-level" allocation). Using 1D-data storage
also greatly reduces the difficulty associated with adding additional
dimensions to the array.

2) Can allocator::deal locate() throw ? I had expected a no throw
declaration.
Depends which allocator .. I think the ones in std cannot. Of course you
could write your own that can throw.
3) Whats the deal with the allocators ? Do they have instace variables or
not ? Do I need to store them or not ?


I don't really know ... I haven't found the need to "roll my own" container
types since before C++ was standardized. I use the STL containers, or one
of the libraries available at http://www.oonumerics.org/oon/.

[snip]

All the rest of your questions kind of disappear if you use a std::vector<T>
for your implementation, which is a(nother) strong argument in favor IMHO.
I would recommend trying such an implementation (it doesn't take much work)
and measuring its performance against your hand-rolled one in a *real* test.
IOW, one that does some real work with the elements, and doesn't just assign
them and pass them around. I have been misled by "lightweigh t" performance
analyses in the past, only to find out that the results were irrelevant in
"real code", because the work done elsewhere completely overwhelmed the
performance differences between storage class implementations .

Like I said in my earlier mail, if you are doing this for a challenge, or
for your own edification, then great. I will try to continue to help if I
can.

Dave Moore
Jul 23 '05 #6
Dave Moore wrote:

Are you sure? Integer arithmetic for array addressing has never
significantly affected the performance of any numerical code I have used.
After all, in C++, a[9] is equivalent to *(a+9), so the integer arithmetic
is implied anyway.
I'm referring to the difference between

a[i + (j * rows)]

and

a[i][j]

or, for array_3

a[i + (j * rows) + (k * rows * cols)]

and

a[i][j][k]
Well, as I said, I think you are doing things in an unnecessarily
complicated fashion. I cannot see the need for 2-D data *allocation* as
you are currently doing ... that is only needed if the rows of the matrix
can
have different lengths, which is not the case in your design. Why not
simply use 1-D allocation a-la vector<T> (or maybe valarray<T>) as the
underlying implementation? This gets rid of the need for the elaborate
allocation of pointers-to-pointers as you are currently doing. At the
very least you should use a T* (and not a T**) to point to the allocated
data, and you won't need all of that try .. catch stuff that currently
makes your constructor definitions virtually impenetrable.
I am using an 1-D allocation a-la vector<T>. However, I also allocate an
additional array of pointers, pointing to row starts in that big chunk. I
do not allocate rows independent.
How you do the addressing of such data is an implementation detail.
You


No.
The adressing scheme I describe allows for a[i][j], and this requires a
slightly different allocation scheme as a[i + (j * rows)] adressing.

Ares Lagae
Jul 23 '05 #7

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

Similar topics

4
2826
by: Tomasz Grobelny | last post by:
Is it possible to create for example stl queue in previously allocated memory buffer (memory shared between two processes)? I thought of sth like that: queue<int>* q=new(buffer) queue<int>; but won't integer variables (and possible others needed by queue object) be allocated using default allocator outside the buffer? How to force allocation in specified buffer? Access to shared memory is protected by semaphores so the should be no...
6
2381
by: Mark | last post by:
If you have STL containers (like list, vector,...) in functions as automatic variables, do the nodes that are put on the containers get buffered so they can be reused by later container operations? For example, if I have 10 member methods, and lots of them have a list <Foo*> when that list is cleared or goes out of scope, the nodes are deleted (don't worry about deleting the Foo* themselves, they are just extra pointers to classes in...
14
8239
by: phil_gg04 | last post by:
Dear C++ Experts, Over the last couple of months I have been writing my first program using shared memory. It has been something of an "in-at-the-deep-end" experience, to say the least. At present the shared memory contains a few fixed-size structs, but I really need to be able to store more complex variable-sized data in there. So the next task is to work out how to store C++ objects, and if possible STL containers, in this shared...
4
1852
by: Andy Venikov | last post by:
Is there a way to change standard containers' behavior to expect a 0 when allocation fails (same way you can change operator new's behavior to return null by passing std::nothrow) ? In my environment I can't use exceptions. I can't use standard allocators either (embedded, you get the picture). I recompiled STLPort with _no_exceptions, but when my allocator failed (returned 0) the whole thing crashed. My guess is that recompiling with...
2
1605
by: bob | last post by:
Hi, Given: 1) Custom containers that have nothing to do with vector, deque, list, map etc, 2) a custom version of new and delete defined for these containers, customNew and customDelete, say. When an item is to be inserted/removed into/from these custom containers, customNew and customDelete is called.
8
1623
by: ALiX | last post by:
Hi all, In my code I use different vectors of the same size to hold some data. At some point I need to iterate through all vectors at the same time. Now, the question is what type should the index variable have? size_t? vector<X>::size_type? vector<Y>::size_type? Example code: -------------------- vector<X> xv; vector<Y> yv;
10
2534
by: Alex Vinokur | last post by:
The memory allocation issue in embedded systems is usually critical.. How can one manage that? 1. Via 'new' char* p = new (nothrow) char ; if (p == 0) { // He we know that it is impossible to allocate the requested memory // We can do something relevant.
13
3641
by: Chris Thomasson | last post by:
Here is some info on a C++ allocator prototype I am working on: http://groups.google.com/group/comp.lang.c++/browse_frm/thread/beeee1f61fdbb52c Any tried-and-true techniques for calculating the correct alignment of any C++ type the user can throw at it? For the initial code, I was assuming that the alignment(T) == sizeof(T)... Now that I am so close to being able to release this thing, I wanted to be able to stitch up this loose end. ...
3
3559
by: DaveJ | last post by:
Hi, This is quite a simple question (hopefully). If I create a vector (on any container) on the heap e.g. std::vector<std::string* m_VectorOfStrings = new vector<std::string>; I know that the vector itself will be placed on the heap, but if I just add strings to it such as:
0
9776
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
11100
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
10718
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...
1
10816
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7953
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
7110
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
5781
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
4597
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
3
3225
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.