tags:

views:

123

answers:

5

Hi,

I'm designing a Buffer class whose purpose is to represent a chunk of memory.

My underlying buffer is a char* (well, a boost::shared_array<char> actually, but it doesn't really matter).

I'm stuck at deciding what prototype to choose for my constructor:

Should I go with:

Buffer(const void* buf, size_t buflen);

Or with:

Buffer(const char* buf, size_t buflen);

Or something else ?

What is usually done, and why ?

+6  A: 

I'd prefer char*, because for me personally it plays better with being "a buffer". void* seems more like "a pointer to I don't know what". Besides, it is what your underlying is, anyway.

Eli Bendersky
A `void*` is not a "pointer to I don't know where", it's a "pointer to I don't know what" :-)
paxdiablo
@pax: yeah, I guess that sounds better (though initially I thought it sounds equivalent), so I changed it to "what"
Eli Bendersky
+6  A: 

API interface is more clear for user, if buffer has void* type, and string has char* size. Compare memcpy and strcpy function definitions.

Alex Farber
Indeed makes sense.
ereOn
A: 

I usually use char*, or unsigned char*. I find that when I use void*, I end up doing a lot of casting to char* to do anything useful with it.

However, if you aren't going to be accessing the individual bytes, then void* is probably better.

Kristopher Johnson
+6  A: 

For the constructor and other API functions, the advantage of void* is that it allows the caller to pass in a pointer to any type without having to do an unnecessary cast. If it makes sense for the caller to be able to pass in any type, then void* is preferable. If it really only makes sense for the caller to be able to pass in char*, then use that type.

Mike Morearty
I agree with you :)
vulkanino
+1  A: 

I generally use unsigned char as the underlying structure (don't want signedness to mess up with my buffer for I know what reason). However I usually typedef it:

typedef unsigned char byte;

And then refer to it as byte* which neatly conveys the meaning in my opinion, better than either char* or void* at least.

Matthieu M.
I can't +1 this hard enough. This relieves all those bugs with `char` such as `char buf[42]; ... if(buf[i] == 0xFF) // *never true*`
Thanatos