Classes with dynamic size in C ++

I would like to create a class Wordin which there is a word. I will have a class instance for almost every word in the dictionary (so many) - and no, I cannot use the tree structure to store this for my specific application. Of course, the size of the lines can change, and I do not want to kill memory. I would like to do this in a class like this:

class Word {
    public:
        ...
    private:
        int         len;
        LetterData  letters[];
};

And then dynamically highlight Word using:

Word *pNewWord = malloc(sizeof(Word)+sizeof(LetterData)*len);   

I understand that this is not very C ++ 'ish. So my questions are: firstly, is there a better way to do this, and if not, will it cause problems? The word does not inherit any other type of class (I am pretty sure that inheritance will kill this ...).

: - , ...

+4
4

​​C. C99 (2.6.7. " " ).

++ " ". , , ++. ++:

, . , , .

++ 11 , " " ( 0 struct).

, :

  • .
  • . ( ) . .
  • , .
  • , (, )
  • , , . / .

, , - . , , LetterData .

+3

, , , - std::string:

class Word
{
public:
    std::size_t getSize() const; // in place of your 'len' member.

private:
    std::string m_data;
};

, Word cf. , m_data - .

, , ++ , .

+5

, - , , , . , .

, , , std:: map std:: set, .

cppcon .

"CppCon 2017: John Lakos" ( "" ) "

" " , , Word " LetterData" . Word , std::vector ( , ). , , .

, , , / node.

, . , , "", .

, , . , , ..

+1

, , , .

, , letters , , , , , .

malloc , ++, :

Word *pNewWord = reinterpret_cast<Word*>(malloc(sizeof(Word)));

, ++ new, :

Word *pNewWord = new Word;

, , .

0

Source: https://habr.com/ru/post/1687553/


All Articles