How Allocation / Resize / Free memory with QT?



  • In the Qt-library I haven't found methods to work with memory like malloc, realloc and free() of standard library C++.

    Are there any analogues in Qt?


  • Qt Champions 2016

    @AlekseyB

    yes, its c++ so there is new and delete ?

    there also classes for use cases, like
    http://doc.qt.io/qt-5/qtcore-ipc-sharedmemory-example.html


  • Moderators

    @AlekseyB malloc, realloc and free()are actually C not C++.
    In C++ one usually uses new and delete.
    Since Qt is a C++ framework you use C++ language - so use new/delete. There is no need for Qt to reinvent the wheel.


  • Qt Champions 2016

    To add to @jsulm
    Do not use malloc with class since the constructor is not called.



  • @mrjj

    As I understand operators new and delete are used to individual objects. But I need allocation memory for array of objects. For example, to allocate 1000 elements of type char. Is operators new and delete is applicable for this problem?


  • Qt Champions 2016

    @AlekseyB
    Hi
    yes, they are.
    http://www.cplusplus.com/doc/tutorial/dynamic/

    int * foo;
    foo = new int [5]



  • @AlekseyB said in How Allocation / Resize / Free memory with QT?:

    As I understand operators new and delete are used to individual objects. But I need allocation memory for array of objects. For example, to allocate 1000 elements of type char. Is operators new and delete is applicable for this problem?

    Usually it's nowadays recommended that manual low-level memory management is avoided in C++ as much as possible. You may want to use QVector instead: "reserve(size) explicitly preallocates memory for size items". Or QByteArray. See http://doc.qt.io/qt-5/containers.html. I don't know your background or real needs, but if you for example come from C and embedded systems background and are now trying desktop applications it's recommended to go higher level than you have used to, leaving []-arrays and char* behind. Ignore me if you already know what you need.



  • @mrjj
    In the above case, you cann't change the size of the allocated memory. The new and delete operators can only allocate and deallocate memory.

    What's wrong with using malloc, realloc and free?


  • Qt Champions 2016

    @AlekseyB
    Hi
    There is nothing wrong using malloc, realloc and free for NON classes but there are so many better alternatives that
    there seems to be no reason why to use them.

    std::vector<char> mylist
    mylist.reserve(1000);
    its the same as
    char mylist[1000];

    BUt , the vector is so much cooler
    u can just do mylist.resize(2000);
    it has a size() to tell how many etc.
    and they are much easier to send as paramters. the list goes on :)



  • Thanks for all!


Log in to reply