Home > Mobile >  Scope of variables in Qt vs vanilla c
Scope of variables in Qt vs vanilla c

Time:11-25

Disclaimer: I am total newbie to Qt.

Let's assume we have a byte array returned from a function innerFunc that is later used in another function outerFunc.

QByteArray innerFunc(){
 QProcess ls;
 ls.start("ls", QStringList() << "-1");
 return ls.readAll();
}
void outerFunc(){
 QByteArray gotcha = innerFunc();
 .
 .
 .
}

In vanilla c I would expect readAll function to return a pointer that needs to be deleted later. In Qt this function returns an instance of the QByteArray class so I guess it shouldn't be accessed outside of the innerFunc's scope.

If so, how should I properly transfer the data to an outer function? Should it copied to QByteArray *tmp = new QByteArray or is it unnecessary?

CodePudding user response:

The code you have looks fine. QByteArray is like std::vector<uint8_t> or std::string and not like a pointer. It manages its own memory. It's fine to return it from a function or pass it to a function by value. The compiler will take care of copying and/or moving the data from one object to another as appropriate, using the contructors/operators defined by the QByteArray class.

  • Related