mercredi 18 septembre 2019

Reference member is set to 0 after object is out of scope

Let's consider the following example of having reference to already destroyed object.

struct Config
{
    unsigned int m_maxSize = 1;
};

class FileReader
{
public:
    FileReader(Config& config) : m_cfg(config){
    }

    Config& m_cfg;
};

class FileReaderUser
{
    FileReader* m_fileReader;
public:
    FileReaderUser(){
        Config cfg;
        cfg.m_maxSize = 1234;
        m_fileReader = new FileReader(cfg);
    }

    void PrintSize(){
        std::cout << "Config value: " << m_fileReader->m_cfg.m_maxSize << std::endl;
    }
};

int main()
{
    FileReaderUser fileReaderUser;
    fileReaderUser.PrintSize();
}

In this example output is 0. My question is why is it zero? I would expect to have access violation if memory was already taken by some other object (not sure if it's true), or to have untouched old (1234) value. It's compiled on GCC 7.2.0 in Debug.

Aucun commentaire:

Enregistrer un commentaire