473,385 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

using placement new

REH
Hi. I want to have a union that contained various types, some of which are
classes with constructors. I'm attempting to acheive this with placement
new. Please tell me if the following code snippet meets the current
standard. Should I cast char* to void* before casting to std::string*?

Regards,

REH
class entry {
public:
enum entry_type {
none, str
};

entry() : m_type(none) {}

entry(const std::string& s) : m_type(str) {new(m_data.str)
std::string(s);}

// note: my compiler didn't like the use of std::string below.
// it would only accept using a typedef of std::string or a using
clause.
// specifically, it didn't like the ~string(). why?
~entry() {using std::string; if (m_type == str)
reinterpret_cast<string*>(m_data.str)->~string();}

entry_type get_type() const {return m_type;}

std::string get_str() const
{
if (m_type == str)
*reinterpret_cast<string*>(m_data.str);
else
throw format_error(); // defined elsewhere
}

private:
entry_type m_type;

union {
double dbl; // ensure any necessary alignment of types
char str[sizeof(std::string)];
} m_data;
};
Jul 23 '05 #1
5 1819
REH wrote:
Hi. I want to have a union that contained various types, some of which are classes with constructors.


What's wrong with a union of primitives and of pointers to types with
constructors?

Look up a "variant" class.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 23 '05 #2
REH

"REH" <me@you.com> wrote in message
news:fH*******************@twister.nyroc.rr.com...
Hi. I want to have a union that contained various types, some of which are classes with constructors. I'm attempting to acheive this with placement
new. Please tell me if the following code snippet meets the current
standard. Should I cast char* to void* before casting to std::string*?

Regards,

REH
class entry {
public:
enum entry_type {
none, str
};

entry() : m_type(none) {}

entry(const std::string& s) : m_type(str) {new(m_data.str)
std::string(s);}

// note: my compiler didn't like the use of std::string below.
// it would only accept using a typedef of std::string or a using
clause.
// specifically, it didn't like the ~string(). why?
~entry() {using std::string; if (m_type == str)
reinterpret_cast<string*>(m_data.str)->~string();}

entry_type get_type() const {return m_type;}

std::string get_str() const
{
if (m_type == str)
*reinterpret_cast<string*>(m_data.str);
else
throw format_error(); // defined elsewhere
}

private:
entry_type m_type;

union {
double dbl; // ensure any necessary alignment of types
char str[sizeof(std::string)];
} m_data;
};


Anyone see any portability and/or standard issues with the above?

Thanks a lot.
Jul 23 '05 #3
REH wrote:
Hi. I want to have a union that contained various types, some of which are
classes with constructors.

As TC++PL is mentioning:
"10.4.12 Unions

A named union is defined as a struct, where every member has the same address (see C.8.2).
A union can have member functions but not static members.

In general, a compiler cannot know what member of a union is used; that is, the type of
the object stored in a union is unknown. Consequently, a union may not have members with
constructors or destructors. It wouldn’t be possible to protect that object against
corruption or to guarantee that the right destructor is called when the union goes out of
scope.

Unions are best used in low-level code, or as part of the implementation of classes that
keep track of what is stored in the union (see 10.6[20]).


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #4
REH

"Ioannis Vranos" <iv*@remove.this.grad.com> wrote in message
news:1112043107.612258@athnrd02...
REH wrote:
Hi. I want to have a union that contained various types, some of which are classes with constructors.

As TC++PL is mentioning:
"10.4.12 Unions

A named union is defined as a struct, where every member has the same

address (see C.8.2). A union can have member functions but not static members.

In general, a compiler cannot know what member of a union is used; that is, the type of the object stored in a union is unknown. Consequently, a union may not have members with constructors or destructors. It wouldn’t be possible to protect that object against corruption or to guarantee that the right destructor is called when the union goes out of scope.

Unions are best used in low-level code, or as part of the implementation of classes that keep track of what is stored in the union (see 10.6[20]).

Yes, I know that. The statement you commented on was just a preface to
explaining what I was trying to acheive.
Jul 23 '05 #5
REH wrote:
Anyone see any portability and/or standard issues with the above?

Your code made to compile. You may check the comments:
#include <string>
class format_error {};

class entry {
public:
enum entry_type {
none, str
};

entry() : m_type(none) {}

//==> Non-portable operation. See below.
entry(const std::string &s) : m_type(str) {new(m_data.str)
std::string(s);}

// note: my compiler didn't like the use of std::string below.
// it would only accept using a typedef of std::string or a using clause.
// specifically, it didn't like the ~string(). why?
~entry() {using std::string; if (m_type == str)
(reinterpret_cast<string *>(m_data.str))->~string();}

entry_type get_type() const {return m_type;}

std::string get_str()
{
if (m_type == str)
*reinterpret_cast<std::string *>(m_data.str);
else
throw format_error(); // defined elsewhere
}

private:
entry_type m_type;

union {
double dbl; // ensure any necessary alignment of types

// ==> Made unsigned char since std::string is a non-POD type
// ==> just to give it some more chance.
// ==> Since std::string is a non-POD type though, this code is not
// ==> portable.
unsigned char str[sizeof(std::string)];
} m_data;
};
int main()
{
}
--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #6

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

Similar topics

20
by: Ioannis Vranos | last post by:
When we use the standard placement new operator provided in <new>, and not a definition of owr own, isn't a call to placement delete enough? Consider the code: #include <new>
6
by: Marc Mutz | last post by:
Hi, I'm in discussion with a lib vendor who uses placement new to forward construction to another ctor, like this: MyClass( ... ) { new (this) MyClass( ... ); } I asked them to use a private...
3
by: Brian Gideon | last post by:
I stumbled across something odd today about the placement of the using keyword. Section 9.3.2 of the C# v1.1 specification did not answer my question. My confusion is isolated to what happens in...
5
by: ma740988 | last post by:
I've got a struct which is comprised of POD types. I know in advance where in memory the struct resides. To make a long story short, I'm doing transfers of 16 bit ADC sampled data between...
5
by: removeps-generic | last post by:
Hi. I'm using placement new to re-initialize part of an object. Is this OK? struct BaseImp { All& r_all; BaseImp(All& all) : r_all(all) }; struct Calc::Imp : public BaseImp
4
by: sreedhar.cs | last post by:
Hi all, In my application,I want to place a vector in a specific location in shared memory.(a user supplied pointer). I understand that the STL allocator mechanism places the data objects within...
15
by: mangesh | last post by:
This code is from c++ faq in section 11 : void someCode() { char memory; void* p = memory; Fred* f = new(p) Fred(); f->~Fred(); // Explicitly call the destructor for the placed object }
13
by: shsingh | last post by:
I have a class A containing some map as data variables. I creat an object of class A on heap by allocatiing memory by using "malloc". This will return me the required memory but the object is not...
5
by: Lagarde Sébastien | last post by:
Hello, I write code to debug new call with following macro: #define new (MemoryManager::Get().setOwner (__FILE__, __LINE__, _FUNCTION-), FALSE) ? NULL : new The setOwner allow to save the...
15
by: LuB | last post by:
I am constantly creating and destroying a singular object used within a class I wrote. To save a bit of time, I am considering using 'placement new'. I guess we could also debate this decision -...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.