A
alex leung
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??
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??