I'd like to create a class Word
, which houses a word. I'll have an instance of the class for pretty much every word in the dictionary (so lots) -- and no, I cannot use a tree structure to store this for my particular application. Of course, the size of the strings may vary, and I don't want to kill memory. I'd like to do this in a class, as so:
class Word {
public:
...
private:
int len;
LetterData letters[];
};
And then dynamically allocate Word using:
Word *pNewWord = malloc(sizeof(Word)+sizeof(LetterData)*len);
I realize this isn't very C++'ish. So my questions are: first, is there a better way of doing this, and if not, is this going to cause problems? Word will not inherit any other class types (I'm fairly certain that inheritance would kill this...).
Note: memory usage and speed are very important -- I'd like to avoid an extra pointer per word, and I'd like to avoid an extra pointer deference per access...
std::string
s to store your text rather than your class which doesn't seem to do anything more. Also what are you really trying to do here as there is probably a much better way of doing this – EdroiLetterData letters[]
is same asLetterData *letters
– Deterrentmalloc
won't compile because you would need to cast 2. Mixingmalloc
andnew
sounds like a recipe for disaster (malloc
does not call constructors andfree
does not call destructors) 3.std::string
andstd::vector
are the best way to represent strings and dynamically sizing collections. – Carpicletters[]
, and then accessletters[3]
, the compiler knows where letters[0] is, so it would hard code a reference to that plus 3. If you do*letters
, it would need to read the pointer stored*letters
, add three, and deference that (which, unless the array is right next to it, would likley result in a cache miss...). – Intarsiastd::string
is a lot smarter than your class. If you have normal sized natural language words, most string implementations would use the Short String Optimization and not have any dynamic allocation at all. Could save onemalloc
call per word. – Paugh