C++ Passing by Reference – Best Practices

cpointersqtreference

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?

Best Answer

Under the hood, it might be implemented differently, but the visible effect of

MyClass(const QByteArray & raw){
        this->m_rawData =raw;
}

will be that the contents of raw get copied into m_rawData and will survive after raw has been destructed.

This works because m_rawData is declared as being a value of type QByteArray. If it would have been a pointer or a reference, then it would have been left dangling if raw was destructed before m_rawData.

One important thing to remember in C++ is that everything is a value unless you explicitly make it a pointer or a reference.