473,588 Members | 2,544 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a refinement of STL??

when I studing the "stl_algobase.h " (SGI Imp. of STL), I find the following
defination of swap:
template <class _Tp>
inline void swap (_Tp& __a, _Tp& __b){
_Tp __tmp = __a;
__a = __b;
__b = __tmp;
}
Couples of assignment operator, copy constructor and destructor is called
which seens affecting the efficiency greatly. imagine how many calls to
swap() in a sorting algorithm. so I started to do the refinement (not
exactly the code I used, just to show the concept):

template <class Tp>_allocate (size_t _size =1); //malloc
template <class Tp> _deallocate (Tp*);
template <class Tp> _copy (Tp *_dest, const Tp&_src); //memcpy

template <class _Tp>
inline void swap (_Tp& __a, _Tp& __b){
_Tp *_tmp = _allocate<_Tp> (); //To allocate space for temp object.
_copy (_tmp , __a);
_copy (&__a, __b);
_copy (&__b, *_tmp);
_deallocate (_tmp); //reverse of _allocate
}

No constructor nor operator= called any more. I have done a simple test with
container like vector, and it works just as I expected. what I worry about
is that,
would there be any safety problem, such as memory alignment?
Is it portable? would it be as fine if I use it on another platform.

One potential danger I can see is for a class, which store the pointer
"this" for its internal use. but what is the practical use to store "this"
statically? so I finally ignore this case.

anyway, could anybody give me a suggestion??


Jul 19 '05 #1
1 2329
"alex leung" <al**@hitogo.co m> wrote in message news:<3f050099$ 1@shknews01>...
when I studing the "stl_algobase.h " (SGI Imp. of STL), I find the following
defination of swap:
template <class _Tp>
inline void swap (_Tp& __a, _Tp& __b){
_Tp __tmp = __a;
__a = __b;
__b = __tmp;
}
Couples of assignment operator, copy constructor and destructor is called
which seens affecting the efficiency greatly. imagine how many calls to
swap() in a sorting algorithm.
Watch it - this is the "base" version. For T's where a more efficient swap
can be done, a specialized version may exist. For UDT's these will not
even be part of the STL implementation delivered with your compiler,
but come with the UDT.
so I started to do the refinement (not
exactly the code I used, just to show the concept):

template <class Tp>_allocate (size_t _size =1); //malloc
template <class Tp> _deallocate (Tp*);
template <class Tp> _copy (Tp *_dest, const Tp&_src); //memcpy

template <class _Tp>
inline void swap (_Tp& __a, _Tp& __b){
_Tp *_tmp = _allocate<_Tp> (); //To allocate space for temp object.
_copy (_tmp , __a);
_copy (&__a, __b);
_copy (&__b, *_tmp);
_deallocate (_tmp); //reverse of _allocate
}
Undefined behavior if T is not a POD. Going to the heap is much
slower as simply defining char tmp[sizeof(T)];. This isn't portable
either, though.
No constructor nor operator= called any more. I have done a simple test with
container like vector, and it works just as I expected. what I worry about
is that, would there be any safety problem, such as memory alignment?
Is it portable? would it be as fine if I use it on another platform.
Nor portable, of course. It certainly won't work with many string
implementations that contain the small-string optimalization. Of course,
a STL implementaion isn't needed on recent compilers which have a proper
Standard Library in std::. On such implementations , you can't even
change it.
One potential danger I can see is for a class, which store the pointer
"this" for its internal use. but what is the practical use to store "this"
statically? so I finally ignore this case.
A common case is the small-string optimalization. For long strings, the
char* of a string will point to the heap, but for small strings the
char* points within the string object itself. This saves expensive
heap allocations, and improves locality of reference. In this case,
when you swap two strings the lengths will be swapped but the pointers
will still point to their original locations. This will be a disaster
if only one string is short enough to be located within the object,
else it will be just surprising. Sorting will obviously fail.
anyway, could anybody give me a suggestion??


Don't. On current std:: implementations , the compiler vendor can
use a non-portable hook to the compiler internals to look at each T.
It can then provide your swap implementation if that works, use the
char[sizeof(T)] trick if that makes sense, use a specialized swap
version or use the trivial version if and only if the other
approaches fail. That's the advantage of an integrated customized
Standard Library, it can use tricks internally you may not use.

For your own classes, provide your own
template< > std::swap( myUDT&, myUDT& );
specialization. It can of course do a C-style memcpy if myUDT is a
simple C-style struct.

Regards,
--
Michiel Salters
Jul 19 '05 #2

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

Similar topics

0
1397
by: avinash | last post by:
We apologize if this is a duplicate email. EIGHTEENTH INTERNATIONAL CONFERENCE ON SYSTEMS ENGINEERING (ICSEng05) LAS VEGAS, USA, AUGUST 16-18, 2005 (http://www.icseng.info) This series of International Conferences is jointly organized on a rotational basis among three institutions, University of Nevada, Las
125
7139
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
112
10291
by: Andy | last post by:
Hi All! We are doing new development for SQL Server 2000 and also moving from SQL 7.0 to SQL Server 2000. What are cons and pros for using IDENTITY property as PK in SQL SERVER 2000? Please, share your experience in using IDENTITY as PK .
1
505
by: hre1 | last post by:
hello stan, thank you very much for your fast replay! your solution will help to solve my problem. but i try to understand !why! sqc and xmlspy produce this messages: SQC means:TYPE REFINEMENT ERROR (content type incompatible with the content type of the basetype) and
2
1477
by: John Hoge | last post by:
I'm working on a product search page that will allow the user to refine their search results based on a few criteria. The user will do a text search, which returns a set of products, and then be presented with a series of checkboxes for product categories and price buckets. I have two options to do this: Option 1 is to build a new query and go back to the database again for
0
1210
by: Richard Rosser | last post by:
Greetings. Not being used to Access, I have built a search form using the wizard but am not getting the desired results. Have tried both the 'and' and the 'or' operator but neither help. What I would like the customer to be able do is to use none, one or more of the fields available for the search, depending on how strictly they want to define the search criteria. i.e. Three search fields titled 'City' 'Age' 'Height' - for instance.....
1
2814
by: None | last post by:
Hi, I have developed webshop application using asp.net 1.1. I'm using DataGrid in one of the pages of my site. During the page load the DataGrid will be binded by around 7500 products(rows). At the same time i'm storing the DataSet object in the Session Variable for later refinement. I'm using StateServer mode for storeing the session values. But in my server the W3wp.exe is taking 90 - 100 % CPU
10
4712
by: Alan Johnson | last post by:
24.1.1.3 says about InputIterators: Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms. In 24.3.4.4 summarizes the effects of std::distance as: Effects: Returns the number of increments or decrements needed to get from first to last. The wording of the latter seems somewhat ambiguous. Does it mean that it actually performs the necessary increments or...
14
9700
by: khaichiew85 | last post by:
i am trying to write a C code which request input from user and store them in array.Number of inputs is determined by the user and it is limited to 100 inputs.Then I need to pass the array to recursive function to sum all odd values in the array.Finally,return the sum of all odd numbers to the user. However, i got the error which stated that the system cannot find the file specified. So I am not sure if my code is correct. I am using Visual...
0
7860
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
8354
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
8223
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
6634
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
5726
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
3847
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
2371
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
1
1458
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1195
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.