I am trying to understand the ideas of pointers and references in C++. I am stuck with the following, what would be the specific behaviour in this case? I have a class like this:
class MyClass{
public:
MyClass(const QByteArray & raw){
this->m_rawData =raw;
}
private:
QByteArray m_rawData;
}
Let's say I create the instance like this:
bool otherClass::someOtherMethod(){
QByteArray data = QString("sometext").toUtf8();
MyClass instance = new MyClass(data);
return true;
}
I pass the data
variable address to my class constructor, then I exit the local method of OtherClass
. The QByteArray data
will be destroyed and its memory freed, right? But what will happen in MyClass instance
? Will this
MyClass(const QByteArray & raw){
this->m_rawData =raw;
}
actually copy the content of raw
into m_rawData
or will it copy the actual reference of the raw and m_rawData
will become invalid when the otherClass::someOtherMethod
returns?
So the QByteArray data will be destroyed and its memory freed right?
-- No. Your new class now holds a reference to it. Even so, in C++, you're generally responsible for memory management unless you use a smart pointer (C++ is not a garbage-collected language), so if you fail to deallocate the memory, it will simply leak unless you maintain a reference to it.this->m_rawData =raw;
will copy the address ofraw
intom_rawData
? I was thinking that it would do something like this:QByteArray& operator=(const QByteArray &other) { this->c_str = malloc(other.size()); this->c_str = strcpy(other.c_str); //etc .. return *this; }