473,657 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In-memory construction of variant types/subclasses?

Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.

Now what I used to do is have a struct, set its type and union member,
and return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to me).

I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects
with constructors or destructors inside a union.

Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB ; or something like that)? In C I didn't need malloc()
in this case; I don't see why I should need new() now.
Jul 2 '06 #1
9 2144
Could you please give some supporting code?
I'm afraid I couldn't follow what you're saying (starting from
the 2nd paragraph), even though I read the thing at least 3
times ;-)

Ulrich Hobelmann wrote:
Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.

Now what I used to do is have a struct, set its type and union member,
and return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to me).

I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects
with constructors or destructors inside a union.

Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB ; or something like that)? In C I didn't need malloc()
in this case; I don't see why I should need new() now.
Jul 2 '06 #2
In article <4g************ *@individual.ne t>, u.*********@web .de
says...

[ ... ]
Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB ; or something like that)? In C I didn't need malloc()
in this case; I don't see why I should need new() now.
Yes -- it's called placement new. You do something like:

static char buffer[4096]; // assume that's big enough...

your_class *object = new(buffer) your_class;

When you're done with this object, you don't delete it -- instead,
you call its dtor directly:

object->~your_class( );

As far as being anything like malloc goes: no, it's not. malloc does
one thing: allocates raw memory. The usual use of new does two
things: allocates some memory (about like malloc), and then creates
an object in that memory.

Placement new does only the _second_ part of that. It doesn't
allocate any memory -- it just creates an object in the memory you
designate. You're still creating a new object, so (at least to me) it
makes perfect sense to use the "new" keyword, even though you're not
doing anything that corresponds to what malloc does.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 2 '06 #3
Hi,

Yes, look up 'in place new' on parashift.

Here is a piece of my Variant type code:

// in the header
union {
Int8 Char;
Int64 Long;
UInt8 UChar;
UInt64 ULong;
double Double;
bool Bool;
char String [ sizeof( std::string ) ];
char Map [ sizeof( std::map<UVar*, UVar*, UFindVar) ];
char SRefPtr[ sizeof( MSRefPtr<ISeria lize) ];
char WRefPtr[ sizeof( MWRefPtr<ISeria lize) ];
char KeyStroke[ sizeof( MKey ) ];
};

And then in the implementation if the variant is for instance string: (from
a piece of the copy constructor passed variable Var)

case eString:
new( this->String ) string( *reinterpret_ca st<string const *const>(
Var.String ) );
break;

--
Make sure to set the alignment options for your compiler otherwise maybe
stuff could get misaligned i.e. on char istead of four byte boundary.

Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Ulrich Hobelmann" <u.*********@we b.dewrote in message
news:4g******** *****@individua l.net...
Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant types)
as a class + subclasses. Switching functions are replaced by virtual
functions. So far so good.

Now what I used to do is have a struct, set its type and union member, and
return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to
me).

I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects with
constructors or destructors inside a union.

Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB ; or something like that)? In C I didn't need malloc() in
this case; I don't see why I should need new() now.

Jul 2 '06 #4
Jerry Coffin posted:

static char buffer[4096]; // assume that's big enough...

That's not guaranteed to be suitably aligned.

--

Frederick Gotham
Jul 2 '06 #5
st************@ gmail.com wrote:
Could you please give some supporting code?
I have a function that will return one of many subclasses of a base
class (so it can't be call-by-value, because the subclasses can have
different sizes). I don't want to use new(), because the object is only
used for a very short time. In C I simply had a union of appropriate
types, initialized one of them, and returned a pointer. In C++ I'd like
to return a reference (ok, doesn't matter really), but the union can't
contain a list of my subclasses, due to init/destruction issues it seems.

Jerry and Moonlit, thanks for the pointers. I could use placement new
(though it remains open how best to declare the memory area; A union
would free me from the chore of having to determine how big my objects
actually are), but I was completely ignoring that objects could have
destructors (ok, these don't, but still the idea seems a bit ugly).

I guess I'll just continue to go with new/delete. The few cycles
shouldn't hurt.
Jul 2 '06 #6
Ulrich Hobelmann schrieb:
Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.
You could try the placement-new way, but others have done it before:

http://www.boost.org/doc/html/variant.html

Thomas
Jul 3 '06 #7
In article <%e************ *******@news.in digo.ie>, fg*******@SPAM. com
says...
Jerry Coffin posted:

static char buffer[4096]; // assume that's big enough...

That's not guaranteed to be suitably aligned.
True -- a bit of ugliness to attempt to keep the code as simple as
possible, and concentrate on the placement new part. You're right,
however, that I probably should have pointed out the limitations more
thoroughly. OTOH, hopefully the comment was enough to indicate that
this buffer was really only for demo, not real use...

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 3 '06 #8
Jerry Coffin posted:
In article <%e************ *******@news.in digo.ie>, fg*******@SPAM. com
says...
>Jerry Coffin posted:

static char buffer[4096]; // assume that's big enough...

That's not guaranteed to be suitably aligned.

True -- a bit of ugliness to attempt to keep the code as simple as
possible, and concentrate on the placement new part. You're right,
however, that I probably should have pointed out the limitations more
thoroughly. OTOH, hopefully the comment was enough to indicate that
this buffer was really only for demo, not real use...

Yes I see what you're getting at, try to keep the example as simple as
possible.

I myself like to throw in a little comment, maybe at that point in the
code, or perhaps afterwards down before my signature, something like:

static char buffer[64]; /* Let's pretend it's suitably aligned */
It's good to be pedantic.

--

Frederick Gotham
Jul 3 '06 #9
Thomas J. Gritzan wrote:
Ulrich Hobelmann schrieb:
>Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.

You could try the placement-new way, but others have done it before:

http://www.boost.org/doc/html/variant.html
Thanks, but that feels a bit more heavyweight than I planned to use.
Jul 3 '06 #10

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

Similar topics

3
6761
by: Curious Expatriate | last post by:
Hi- I'm completely stumped. I'm trying to write some code that will parse a file and rewrite it with all URLs replaced by something else. For example: if the file looks like this: <b>click here</b><a href="http://www.cnn.com">click me</a> ... then the output should be this:
1
6297
by: JS Bangs | last post by:
I started using PHP's object-oriented stuff a little while ago, which has mostly been a joy. However, I've noticed that they don't seem to echo as I would like. Eg: $this->field = 255; $this->key = 'id'; echo "$this->key is $this->field"; // prints "id is Array" // Thus I am forced to do this $keyval = $this->field;
5
16153
by: lawrence | last post by:
I've waited 6 weeks for an answer to my other question and still no luck, so let me rephrase the question. I know I can do this: <form method="post" action="$self"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> </form>
0
4920
by: Ben Eisenberg | last post by:
I'm trying to run a php script setuid. I've tried POSIX_setuid but you have to be root to run this. The files are located on a public access unix system and have me as the owner and nobody as the group. Rather than make them group writable where in anybody could make a script and write to my files i would like to make them setuid. I tried making a c prog with the setuid function. I used chmod and made it setuid. I called it with the system...
2
8559
by: Felix | last post by:
Hi, I've a problem: I want to have the result of my Mysql Query in a Table in my php file. Now I've this: <?
1
8704
by: James | last post by:
What is the best way to update a record in a MYSQL DB using a FORM and PHP ? Where ID = $ID ! Any examples or URLS ? Thanks
1
2940
by: Patrick Schlaepfer | last post by:
Why this code is not working on Solaris 2.8 host. Always getting: PHP Fatal error: swfaction() : getURL('http://www.php.net' ^ Line 1: Reason: 'syntax error' in /.../htdocs/ming2.php on line 28
1
3419
by: phpkid | last post by:
Howdy I've been given conflicting answers about search engines picking up urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3 Do search engines pick up these urls? I've been considering converting a site of mine to PHP-Nuke, but if the individual modules aren't picked up in search engines I'm not going to do it. Thanks phpKid
1
2552
by: lawrence | last post by:
What is the PHP equivalent of messaging, as in Java?
3
4915
by: Quinten Carlson | last post by:
Is there a way to conditionally define a function in php? I'm trying to run a php page 10 times using the include statement, but I get an error because my function is already defined. The docs state that a function cannot be undefined and adding "exit" to the included page doesn't free it up either. Any suggestions? B44CCD21
0
8425
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
8326
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
8845
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...
1
8522
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
8622
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
7355
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...
0
5647
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
4173
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...
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.