-
January 25th, 2010, 07:17 PM
#1
cast from void* to const char*
Hi!
I have the following struct:
Code:
struct cBuffer
{
char data[1024];
int bytesRecorded;
bool flag;
cBuffer(char * data_, int bytesRecorded_, bool flag_) :
bytesRecorded(bytesRecorded_), flag(flag_)
{
memcpy(static_cast<void *>(data), static_cast<void *>(data_),
bytesRecorded * sizeof(char));
}
};
I would like to turn char data[1024] to const char data[1024], the same goes
for the constructor:
cBuffer(const char * data_, int bytesRecorded_, bool flag_)
But then I fail using the memcpy() function because of the wrong cast.
how could I sort that out?
thanks
-
January 25th, 2010, 07:22 PM
#2
Re: cast from void* to const char*
Well, you certainly can't put a const field into the destination of a memcpy.
However, you can cast a const char* to a const void*.
-
January 25th, 2010, 09:36 PM
#3
Re: cast from void* to const char*
ok, do you think the following could be a fine way around it?
Code:
#include <algorithm>
struct cBuffer
{
char data[1024];
int bytesRecorded;
bool flag;
cBuffer(const char * data_, int bytesRecorded_, bool flag_) :
bytesRecorded(bytesRecorded_), flag(flag_)
{
std::copy(data_, data_ + (bytesRecorded_ * sizeof(char)), data);
}
};
thanks
-
January 25th, 2010, 09:53 PM
#4
Re: cast from void* to const char*
You can use
const_cast<char> (expression)
Code:
char chr[10] ;
const char * bhr = const_char<char*>(chr);
-
January 25th, 2010, 11:30 PM
#5
Re: cast from void* to const char*
Why do you want to make the array const? If you are trying to protect it from the outside world, would you be able to make the array private and provide accessor functions so you have strict control over it?
The use of const_cast is nearly always a sign that something is wrong with the way a program is coded. (Usually meaning that initial authors didn't think about const issues, and later authors band-aided the resulting problems rather than taking the extra time to fix them.)
Rare examples to the contrary are the use of functions which ordinarily change the pointed-to-value, but which can be guaranteed not to in some specific instance where a side-affect is desired. For example:
Code:
class SomeMultiThreadedClass
{
...
public:
int GetCurrentValueOfSomeVariable(void) const
{
// Add zero to get the current value
return InterlockedExchangeAdd(const_cast<volatile LONG *>(&m_i), 0);
}
private:
volatile LONG m_i;
};
Another use is to get rid of a volatile qualifier, which is also a rare need.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|