Hello all C++ expert programmer,
i have wrote partial general allocator for my container.
After reading standard C++ library and code guru article, i have
several questions.
1. Why allocator write forward declaration then allocation for void*
rather than directly wrote allocator first ? -
namespace std {
-
template <class Tclass allocator;
-
-
// specialize for void:
-
template <class allocator<void{
-
public:
-
typedef void* pointer;
-
typedef const void* const_pointer;
-
// reference to void members are impossible.
-
typedef void value_type;
-
template <class Ustruct rebind { typedef allocator<U>
-
other; };
-
};
-
-
template <class Tclass allocator {
-
public:
-
typedef size_t size_type;
-
typedef ptrdiff_t difference_type;
-
typedef T* pointer;
-
typedef const T* const_pointer;
-
typedef T& reference;
-
typedef const T& const_reference;
-
typedef T value_type;
-
template <class Ustruct rebind { typedef allocator<U>
-
other; };
-
-
allocator() throw();
-
allocator(const allocator&) throw();
-
template <class Uallocator(const allocator<U>&) throw();
-
~allocator() throw();
-
-
pointer address(reference x) const;
-
const_pointer address(const_reference x) const;
-
-
pointer allocate(size_type,
-
allocator<void>::const_pointer hint = 0);
-
void deallocate(pointer p, size_type n);
-
size_type max_size() const throw();
-
-
void construct(pointer p, const T& val);
-
void destroy(pointer p);
-
};
-
}
-
-
-
2. What is the use/purpose of type definition ?
1. A couple of type definitions. These ensure that the allocators'
client (for instance, 'std::vector') is able to use some relevant
types by known names. For example, consider that you write an
allocator, that is able to allocate memory in a far area, that cannot
be reached by normal pointers (let your imagination wander). Now, the
'allocator' will use some pointer-like construct. The allocators'
client has, of course, no idea of such a thing. When a client needs to
pass such a pointer it will use the
typedef T* pointer;
and if it needs to suptract such pointers, the result will have the
type 'difference_typ e', whatever that internally means for the
allocator.
What i understand from here is because different container needs
different pointer construct memory, therefore, there are different
member data in list and vector. So, allocator need to match back its
member data with vector for example.
typedef T* pointer; ----------- Allocator
Vector
typedef A allocator_type; typedef typename A::pointer pointer;
Although, i not able to understand what this does
vector
typedef A allocator_type; typedef typename A::pointer pointer;
3. How allocator know when it need rebind for its allocator
client(vector, list, map, set) ?
This is the magic required for std::list to work properly,
since given std::list<int( allocator<int>( ) ), std::list actually
needs to allocate memory for Node<int>, and not int.
Thus, they need to rebind to allocator<int>( )::rebind<Node< int
:ther instead. -
template <class U>
-
struct rebind
-
{
-
typedef allocator<Uother;
-
};
-
-
list<int>;
-
-
interprete by compiler as list<int, allocator<int;
-
-
This code template <class T>
-
class allocator; is replace with allocator<int;
-
-
In other words, T(represent generic types) = int;
-
-
Then allocator class receive integer as argument
-
-
How compiler interpreter
-
template <class U>
-
struct rebind
-
{
-
typedef allocato<Uother;
-
}
-
-
How list is pass U ?
-
Thanks for your help.
Please help me.
I really appreciated any help. 16 2681
This is current work. -
-
-
/*
-
Two steps define custom allocators
-
-
1. Design a memory management mechanism/model
-
2. Create standard-like allocators
-
-
-
*/
-
-
-
-
// ================================================
-
-
#ifndef _Custom_Allocator_
-
#define _Custom_Allocator_
-
-
#include <memory>
-
-
using std::allocator;
-
-
-
// ================================================
-
-
template <class T>
-
class MyAlloc
-
{
-
-
// Two Constructos which did nothing
-
public:
-
-
-
// Type Definitions
-
-
// Pointer to element type used in memory model
-
typedef T* pointer;
-
// Const Pointer to element type used in memory model
-
typedef const T* const_pointer;
-
-
// Reference to element type used in memory model
-
typedef T& reference;
-
typedef const T& const_reference;
-
-
// Type of the element that is being used in the memory model
-
typedef T value_type;
-
-
// Rpresent largest object in allocator memory model
-
typedef size_t size_type; // Unsigned
-
-
// Represent two pointer in two allocator model
-
typedef ptrdiff_t difference_type; // Signed
-
-
-
// =================================================
-
-
-
// Member Function
-
/*
-
No throw is allowed for constructor
-
and destructor
-
-
C && D is trivial(Not important)
-
-
-
*/
-
MyAlloc();
-
/*
-
Copy C is need because exception
-
specification stated that constructor
-
is not allow to throw.
-
-
Does require operator= because
-
if (this != rhs) then code will not
-
be executed and Two MyAlloc object must
-
same which form by C++ standard allocator
-
-
*/
-
MyAlloc(const MyAlloc<T&);
-
~MyAlloc();
-
-
/*
-
Require rebind because list(nodes), vector
-
(contigious)
-
-
Rebind is a structure that enables
-
an allocator for objects of one type
-
interpret as to allocate storage for
-
objects of another type.
-
-
To allocate objects of
-
different types than its
-
template parameter
-
-
The rebind member allows a container
-
to construct an allocator for some
-
arbitrary type out of the allocator type
-
provided as a template parameter.
-
-
This is the magic required
-
for std::list to work properly,
-
since given std::list<int>
-
( allocator<int>() ),
-
std::list actually needs to allocate memory
-
for Node<int>, and not int.
-
Thus, they need to rebind to
-
-
-
allocator<int>()::rebind<Node<int
-
::other instead.
-
-
-
For instance, the list container gets an
-
allocator<Tby default, but a list may
-
well need to allocate list_nodes as well
-
as T's. The container can construct an
-
allocator for list_nodes out of the
-
allocator for T's
-
(the template parameter,
-
Allocator, in this case) as follows:
-
-
Allocator::rebind<list_node>
-
::other list_node_allocator;
-
-
*/
-
-
/*
-
Explicit call by compiler is
-
allocator<T>::rebind<U>::other;
-
-
Here allocator client(vector, list)
-
request allocator type from allocator
-
-
Therefore, allocator using rebind to
-
preseve the old state type and duplicate
-
a same/new state type to pass to
-
allocator client.
-
-
Then, continue to class to rework a new
-
type which is
-
listAllocator < node<int and
-
not allocator<int>.
-
-
-
*/
-
template <class U>
-
struct rebind
-
{
-
typedef allocator<Uother;
-
}
-
-
-
-
// Return address of given object
-
pointer address(reference x) const;
-
const_pointer address(const_reference x) const;
-
-
// Returns the largest value which can be passed to the 'allocate()'
-
function.
-
size_type MaxMemory();
-
-
/*
-
Returns storage for n elements of
-
the element type being used
-
in the memory model.
-
-
Elements will not be c
-
onstructed/initialized.
-
-
*/
-
pointer allocate(size_type);
-
/*
-
Deallocate element type used in
-
memory model begin at position p
-
-
Storage must be allocate by same allocator
-
-
Size must same in allocate()
-
p must not be 0.
-
Elements must have been destroyed before.
-
*/
-
void deallocate(pointer, size_type);
-
-
/*
-
Allocate must call before construct
-
This is a call to placement new
-
value is U
-
new((void*)p) T(u);
-
*/
-
void construct(pointer, const_reference);
-
/*
-
Destrory call ahead of (prior to) deallocate
-
new((void*)p) T(u);
-
*/
-
void destrory(pointer);
-
};
-
-
/*
-
No refernce type to void* -That's why need
-
specialization for void.
-
*/
-
-
// ================================================
-
-
template<class T1, class T2>
-
bool operator==(MyAlloc<T1>, MyAlloc<T2>) const
-
{
-
return MyAlloc<T1== MyAlloc<T2>;
-
}
-
-
template<class T1, class T2>
-
bool operator!=(MyAlloc<T1>, MyAlloc<T2>) const
-
{
-
return MyAlloc<T1!= MyAlloc<T2>;
-
}
-
-
// ================================================
-
-
-
-
#endif
-
-
/*
-
-
allocate and deallocate function are
-
low level memory management which
-
doesn't participate in
-
object construction and destruction.
-
-
The purpose of the allocator is to allocate
-
raw memory without construction of objects,
-
as well as simply deallocate memory
-
without the need to destroy them.
-
-
Usage of ::operator new and ::operator delete
-
is preferred over keywords new and delete.
-
-
A* a = new A;
-
delete a;
-
-
Intepreted by compiler as below:
-
-
// assuming new throws std::bad_alloc upon failure
-
-
Allocate then construct
-
A* a = ::operator new(sizeof(A));
-
a->A::A();
-
-
if ( a != 0 )
-
{ // a check is necessary for delete
-
-
a->~A();
-
::operator delete(a);
-
-
Destroyed(Destruct) first
-
before deallocate
-
}
-
-
-
Every C++ standard like allocator must provide
-
these global operator== and operator!=
-
-
Memory Model are shared model, grabage collection,
-
segregrated model.
-
-
Why write custom allocators ?
-
1. To trace the memory operations of
-
your application to a file
-
2. Speed
-
-
-
-
Sample Override New and delete Code
-
-
void* operator new(size_t,void* anAddress)
-
{
-
return anAddress;
-
}
-
void* operator new(size_t size)
-
{
-
return Standard::Allocate(size);
-
}
-
void operator delete(void *anAddress)
-
{
-
if (anAddress)
-
Standard::Free((Standard_Address&)anAddress);
-
}
-
-
The first new operator overload is for the
-
new with placement syntax, instead of
-
creating instances on the free store it
-
will use the address you provided.
-
-
This is useful for using preallocated memory (e.g. a buffer)
-
to store your objects and still have the
-
construtors and destructors called for these
-
objects.
-
-
Apparently this first overload is just the
-
default one that would be generated by
-
the compiler anyway.
-
-
-
The second new and the delete operator overload are apparently
-
defined because the coder wanted to use a custom allocator.
-
If the first new overload seems useless but is still present it may
-
be that the compiler is requiring it if you overload the new(size_t)
-
one ( just a guess), try removing the new(size_t, void*) definition
-
and see if the code still compiles and link.
-
-
-
No reference to object which allocated on the stack
-
This is make sense since stack unwinding
-
will get clean up and you will use danling
-
reference
-
-
Never pass auto_ptrs by value
-
if a function can throw
-
-
-
BTW, returning auto_ptrs by value is a
-
good idea for factory and
-
clone like functions.
-
*/
-
-
-
-
-
-
-
-
// Sketch version of list
-
-
/*
-
template <typename T, typename A>
-
class node
-
{
-
typedfed node list_nodes;
-
-
typename A::rebind<list_nodes>::others listNodeAllocator;
-
// Actually declare listNodeAllocator < list_nodes<T;
-
-
};
-
-
*/
-
Thanks for your correction.
You can not change or add code to std namespace because it is
undefined behaviour.
I didn't add to code to namespace standard.
I create my custom allocator with my own namespace.
Please behave in C++ usenet community.
Thanks.
This is all my code.
What should i do for next steps ?
Thanks for your help.
I have corrected my code.
Now my problem is this:
Error 1 error C2440: 'default argument' : cannot convert from
'MyAllocator<T> ' to 'MyAllocator<T> ' c:\program files\microsoft visual
studio 8\vc\include\li st 83
Please help me. Pe********@gmai l.com wrote:
[...]
template <class T>
class MyAllocator
{
public:
// Type Definitions
typedef T value_type;
[...more types...]
>
// Member Function
MyAllocator(){}
template <class U>
MyAllocator(con st MyAllocator<T&r hs){}
^^^
The template parameter U is not used. Do you mean this instead?
template <class U>
MyAllocator(con st MyAllocator<U&r hs){}
[...]
// ============== Global Functions ===============
// Non member function cannot declare as constant
You cannot declare the functions as constant, but the parameter:
template<class T1, class T2>
bool operator==(MyAl locator<T1>& first, MyAllocator<T2> & second)
bool operator==(cons t MyAllocator<T1> & first, const MyAllocator<T2> & second)
{
return first == second;
What function should be called here? The function will call itself. This
is infinite recursion.
}
template<class T1, class T2>
bool operator!=(MyAl locator<T1>& first, MyAllocator<T2> & second)
{
return first!=second;
}
Same as above.
--
Thomas This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Orjan Westin |
last post by:
Hi,
I have an interesting (read frustrating) problem. I'm writing a
generic container class, which holds data as well as links to other
instances of itself, like this:
template<class T>
class node
{
public:
|
by: John Harrison |
last post by:
If you specify an allocator in an STL container is it a requirement that
the allocator allocates object of the right type, or can you assume that
the container will rebind the allocator to the correct type?
For example I tried the following code which uses a 'wrong' allocator and
was slightly surrised to find it compiles on the three...
|
by: Joshua Kolden |
last post by:
STL allocators are templates so that when you write one you are obliged
to make it work with any type. However, the Intel IPP library that we
use has memory aligned allocators for each of 15 different types. For
example an 8 bit unsigned array is allocated with ippsMalloc_8u(size).
So I want to create memory aligned allocators for use with...
|
by: Grahamo |
last post by:
Hi,
can anybody tell me where I can get the boiler plate code for
std::allocator. I need to have my version of new and delete called and
want to get reference code. My compilers headers are all over the place
with #ifdefs and what not, I'd like a clean copy.
thanks much
|
by: Mr Newbie |
last post by:
I am often in the situation where I want to act on the result of a function,
but a simple boolean is not enough. For example, I may have a function
called
isAuthorised ( User, Action ) as ?????
OK, this function may return a boolean, and if this is true, then no message
back is really required, but if it fails then some supporting message...
| |
by: sharmadeep1980 |
last post by:
Hi All,
I am facing a very unique problem while compling my project in
"Release" build.
The project is building in DEBUG mode but giving linking error on
Release build.
Here is the error:
Creating library Release/fnimqcmd.lib and object
Release/fnimqcmd.exp
CoIMQCmd.obj : error LNK2001: unresolved external symbol
|
by: OuaisBla |
last post by:
Although STL container can't support object by reference as a template argument. To make thing worse, allocator can't support stack based allocation.
So:
std::deque<std::string const &>
is impossible to declare.
But, it is also more than impossible to find a workaroung using a custom STL allocator because of the ugly and not object...
|
by: Chris Thomasson |
last post by:
I found some time to work a little more on my C++ allocator project. Here is
some of the basic alignment code that I am thinking about using:
----------------
#include <cstdio>
#include <cstring>
#include <cassert>
// attempts to extract the alignemnt of a type T
|
by: Phil Bouchard |
last post by:
I am currently writting a smart pointer which is reasonnably stable and I
decided supporting allocators for completion because of its increase in
efficiency when the same pool used by containers is shared. I was told the
new standards are being finalized and I am hoping minor but important
changes could be applied before anything else.
To...
|
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...
|
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...
| |
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. ...
|
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...
|
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...
|
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...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |