473,770 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this standard c++...

I am thinking about using this technique for all the "local" memory pools in
a paticular multi-threaded allocator algorithm I invented. Some more info on
that can be found here:

http://groups.google.com/group/comp....c40d42a04ee855

Anyway, here is the code snippet:

#include <cstdio>
#include <cstddef>
#include <new>
template<size_t T_sz>
class lmem {
unsigned char m_buf[T_sz];
public:
void* loadptr() {
return m_buf;
}
};
class foo {
public:
foo() { printf("(%p)foo ::~foo()", (void*)this); }
~foo() { printf("(%p)foo ::~foo()", (void*)this); }
};
int main(void) {
foo *f;
lmem<sizeof(*f) foomem;
f = new (foomem.loadptr ()) foo;
f->~foo();
return 0;
}

Feb 27 '07 #1
22 2300
Chris Thomasson wrote:
I am thinking about using this technique for all the "local" memory
pools in a paticular multi-threaded allocator algorithm I invented.
Some more info on that can be found here:

http://groups.google.com/group/comp....c40d42a04ee855

Anyway, here is the code snippet:

#include <cstdio>
#include <cstddef>
#include <new>
template<size_t T_sz>
class lmem {
unsigned char m_buf[T_sz];
public:
void* loadptr() {
return m_buf;
}
};
class foo {
public:
foo() { printf("(%p)foo ::~foo()", (void*)this); }
The string seems to be incorrect.
~foo() { printf("(%p)foo ::~foo()", (void*)this); }
};
int main(void) {
foo *f;
lmem<sizeof(*f) foomem;
f = new (foomem.loadptr ()) foo;
It's not "incorrect" , but I believe you may have a problem
with alignment. Only a memory block sized 'sizeof(foo)'
obtained from free store is aligned correctly to have a 'foo'
constructed in it like that.
f->~foo();
return 0;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Feb 27 '07 #2
Chris Thomasson wrote:
I am thinking about using this technique for all the "local" memory pools in
a paticular multi-threaded allocator algorithm I invented. Some more info on
that can be found here:

http://groups.google.com/group/comp....c40d42a04ee855

Anyway, here is the code snippet:

#include <cstdio>
#include <cstddef>
#include <new>
template<size_t T_sz>
class lmem {
unsigned char m_buf[T_sz];
You may run into alignment problems by using an array of unsigned char,
you should follow the same system specific alignment rules as malloc.
public:
void* loadptr() {
return m_buf;
}
};
class foo {
public:
foo() { printf("(%p)foo ::~foo()", (void*)this); }
~foo() { printf("(%p)foo ::~foo()", (void*)this); }
};
C++ purists avoid printf. Never mix it with iostreams.
>
int main(void) {
Just int main() is the norm in C++.

--
Ian Collins.
Feb 27 '07 #3
Ian Collins wrote:

C++ purists avoid printf. Never mix it with iostreams.
Bah. Pointlessly dogmatic. Sometimes it's the right thing.


Brian
Feb 28 '07 #4
Default User wrote:
Ian Collins wrote:
>>C++ purists avoid printf. Never mix it with iostreams.

Bah. Pointlessly dogmatic. Sometimes it's the right thing.
Care to cite an example?

--
Ian Collins.
Feb 28 '07 #5
On 27 Feb, 22:59, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Chris Thomasson wrote:
I am thinking about using this technique for all the "local" memory
pools in a paticular multi-threaded allocator algorithm I invented.
Some more info on that can be found here:
http://groups.google.com/group/comp....ead/24c40d42a0...
Anyway, here is the code snippet:
#include <cstdio>
#include <cstddef>
#include <new>
template<size_t T_sz>
class lmem {
unsigned char m_buf[T_sz];
public:
void* loadptr() {
return m_buf;
}
};
class foo {
public:
foo() { printf("(%p)foo ::~foo()", (void*)this); }

The string seems to be incorrect.
~foo() { printf("(%p)foo ::~foo()", (void*)this); }
};
int main(void) {
foo *f;
lmem<sizeof(*f) foomem;
f = new (foomem.loadptr ()) foo;

It's not "incorrect" , but I believe you may have a problem
with alignment. Only a memory block sized 'sizeof(foo)'
obtained from free store is aligned correctly to have a 'foo'
constructed in it like that.
IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue. However
It should be possible to check . (Not absolutely sure if this is the
correct solution but whatever ...

regards
Andy Little

#include <stdexcept>

// aka std::tr1::
template <typename T>
struct alignment_of{
#if defined _MSC_VER
static const unsigned int value = __alignof(T);
#elif defined __GNUC__
static const unsigned int value = __alignof__(T);
#else
#error need to define system dependent align_of
#endif
};
template<typena me T, size_t T_sz>
class lmem {

unsigned char m_buf[T_sz];
public:
void* loadptr() {
// check its aligned correctly
ptrdiff_t dummy = m_buf - static_cast<cha r*>(0);
ptrdiff_t offset = dummy % alignment_of<T> ::value;
if(!offset)
return m_buf;
throw std::logic_erro r("lmem memory doesnt satisfy alignment");
}
};
int main()
{
typedef double type;
lmem<type,sizeo f(type)x;
}

Feb 28 '07 #6
On 28 Feb, 01:25, "kwikius" <a...@servocomm .freeserve.co.u kwrote:
IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue.
Well I was wrong about that :.
(Back to the drawing board I guess)

But at least the code seems to detect the problem :

#include <stdexcept>

// aka std::tr1::
template <typename T>
struct alignment_of{
#if defined _MSC_VER
static const unsigned int value = __alignof (T);
#elif defined __GNUC__
static const unsigned int value = __alignof__(T);
#else
#error need to define system dependent align_of
#endif
};
template<typena me T, size_t T_sz>
class lmem {

unsigned char m_buf[T_sz];
public:
void* loadptr() {
// check its aligned correctly
ptrdiff_t dummy = m_buf - static_cast<uns igned char*>(0);
ptrdiff_t offset = dummy % alignment_of<T> ::value;
if(!offset)
return m_buf;
throw std::logic_erro r("lmem memory doesnt staisfy alignment");
}
};

#include <iostream>
int main()
{
try{
typedef double type;
char c;
lmem<type,sizeo f(type)x;
void * p = x.loadptr() ;
}
catch(std::exce ption & e)
{
std::cout << e.what() <<'\n';
}
}
/* output:
lmem memory doesnt staisfy alignment

*/
regards
Andy Little

Feb 28 '07 #7
kwikius wrote:
>
IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue. However
It should be possible to check . (Not absolutely sure if this is the
correct solution but whatever ...
No, the class may be aligned according to the alignment requirements of
its members, in this case unsigned char.

--
Ian Collins.
Feb 28 '07 #8
On 28 Feb, 02:47, Ian Collins <ian-n...@hotmail.co mwrote:
kwikius wrote:
IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue. However
It should be possible to check . (Not absolutely sure if this is the
correct solution but whatever ...

No, the class may be aligned according to the alignment requirements of
its members, in this case unsigned char.
Yep. I figured it out eventaully I think.
It seems to be possible but at the expense of always allocating your
char array oversize by alignment_of<T-1. Its not possible to know
where on the stack the lmem object will go.

Anyway the following seems to work :
template<typena me T, size_t T_sz>
class lmem {
// Don't think there is a way to avoid
// allocating extra stack space ...
unsigned char m_buf[T_sz + alignment_of<T> ::value -1];
public:
void* loadptr() {
// align memory to T
ptrdiff_t dummy = m_buf - static_cast<uns igned char*>(0);
ptrdiff_t offset = dummy % alignment_of<T> ::value;
ptrdiff_t result = offset == 0
? dummy
: dummy + alignment_of<T> ::value - offset;
// check this works
assert( result % alignment_of<T> ::value == 0);
return static_cast<uns igned char*>(0) + result;
}
};

struct my{
int x, y;
double z;
my(int xx, int yy, double zz): x(xx),y(yy),z(z z){}
};

#include <iostream>
int main()
{

// muck about with stack offsets
char c = '\n';
short n = 1;
lmem<double,siz eof(double)x;
double * pd = new (x.loadptr()) double(1234.567 89);
std::cout << *pd <<'\n';

lmem<my, sizeof(my)y;
my * pc = new (y.loadptr()) my(1,2,3);

std::cout << pc->x << ' ' << pc->y << ' ' << pc->z <<'\n';

}

regards
Andy Little

>
--
Ian Collins.

Feb 28 '07 #9
kwikius wrote:
On 28 Feb, 02:47, Ian Collins <ian-n...@hotmail.co mwrote:
>>kwikius wrote:

>>>IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue. However
It should be possible to check . (Not absolutely sure if this is the
correct solution but whatever ...

No, the class may be aligned according to the alignment requirements of
its members, in this case unsigned char.


Yep. I figured it out eventaully I think.
It seems to be possible but at the expense of always allocating your
char array oversize by alignment_of<T-1. Its not possible to know
where on the stack the lmem object will go.

Anyway the following seems to work :
template<typena me T, size_t T_sz>
class lmem {
// Don't think there is a way to avoid
// allocating extra stack space ...
unsigned char m_buf[T_sz + alignment_of<T> ::value -1];
public:
void* loadptr() {
// align memory to T
ptrdiff_t dummy = m_buf - static_cast<uns igned char*>(0);
ptrdiff_t offset = dummy % alignment_of<T> ::value;
ptrdiff_t result = offset == 0
? dummy
: dummy + alignment_of<T> ::value - offset;
// check this works
assert( result % alignment_of<T> ::value == 0);
return static_cast<uns igned char*>(0) + result;
}
};
Or even:

template <typename T>
class lmem {
T t;
public:
void* loadptr() {
return &t;
}
};

:)
--
Ian Collins.
Feb 28 '07 #10

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

Similar topics

25
3793
by: Magnus Lie Hetland | last post by:
Is there any interest in a (hypothetical) standard graph API (with 'graph' meaning a network, consisting of nodes and edges)? Yes, we have the standard ways of implementing graphs through (e.g.) dicts mapping nodes to neighbor-sets, but if one wants a graph that's implemented in some other way, this may not be the most convenient (or abstract) interface to emulate. It might be nice to have the kind of polymorphic freedom that one has with,...
6
8331
by: John Bentley | last post by:
John Bentley writes at this level: If we think about our savings accounts then division never comes in (as far as I can see). We deposit and withdraw exact amounts most of the time. Occasionaly we get an interest payment. Unless the bank is cruel to its developers the interest figure will be able to be exactly represented by a computer, something like 4.1% as opposed to 4 1/3 % 125.78 * ' Initial Balance 04.1% -------
29
2408
by: David Eng | last post by:
In replying to P.J. Plauger ( http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&threadm=1089204435.746211%40master.nyc.kbcfp.com&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.c%252B%252B.moderated ) who responded my post in comp.long.c++ moderated neww group regarding "C++ standard and C++/CLI" topic, I worte the following post which was sensor by comp.lang.c++.moderated: ...
43
5024
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own libraries. I'm not sure if that's a good thing or not. AFAIK, most of Qt is compatable with the Standard Library. That is, QLT can interoperate with STL, and you can convert back and forth between std::string and Qt::QString, etc. Are there any...
52
3789
by: lovecreatesbeauty | last post by:
Why the C standard committee doesn't provide a standard implementation including the C compiler and library when the language standard document is published? C works on the abstract model of low level machine. C stands for portability and platform and machine independent. If the C compiler and C standard library are written in C itself, is it possible that one "standard" C compiler plus library is enough? The standard implementation is...
24
2456
by: noridotjabi | last post by:
Why isn't there a Graphical User Interface standard? Think about it for a second. You may say, well evey systems API for GUIs is differnt, but do take into acound: every operating system requires differnt compilations and often totally differnt compiler code. For instance gcc on windows in not the same code as gcc on linux/unix but it produces the same programs when you use it to compile. Yes you can take something like: #include...
132
4653
by: Frederick Gotham | last post by:
If we look at a programming language such as C++: When an updated Standard comes out, everyone adopts it and abandons the previous one. It seems though that things aren't so clear-cut in the C community. It would seem that C99 is the most up-to-date Standard, but far more people seem to be working off the C89 Standard. Could someone please explain to me why this is so? --
1
3227
by: manish deshpande | last post by:
Hi, When i'm installing MySQL-server-standard-5.0.24a-0.rhel3.i386.rpm by the following command: rpm -i MySQL-server-standard-5.0.24a-0.rhel3.i386.rpm the following error is being shown: warning: MySQL-server-standard-5.0.24a-0.rhel3.i386.rpm: V3 DSA signature: NOKEY, key ID 5072e1f5 file /etc/my.cnf from install of MySQL-server-standard-5.0.24a-0.rhel3 conflicts with file from package mysql-3.23.58-1 file...
26
3826
by: Rick | last post by:
I'm told that "#pragma once" has made it into the ISO standard for either C or C++. I can't find any reference to that anywhere. If it's true, do any of you have a reference I can use? Thanks...
270
9544
by: jacob navia | last post by:
In my "Happy Christmas" message, I proposed a function to read a file into a RAM buffer and return that buffer or NULL if the file doesn't exist or some other error is found. It is interesting to see that the answers to that message prove that programming exclusively in standard C is completely impossible even for a small and ridiculously simple program like the one I proposed. 1 I read the file contents in binary mode, what should...
0
9617
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
9453
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,...
1
10036
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,...
0
9904
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
8929
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
7451
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
6710
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
5354
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...
3
2849
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.