lundi 17 avril 2023

In C++, are using reference types for member fields considered proper usage? Particularly when memory is allocated and owned outside the class

When memory is allocated and owned outside a class, is it cool to use a reference member field to reference the memory rather than passing it through as a pointer?

I'm mostly looking for best practices and what is and isn't "proper" usage.

There can't be any smart pointers.

Something like:

struct Fizz
{
    std::vector<bool> m_results;
    bool m_finalResult;
};

class Bar
{
public:
    Bar(Fizz& _givenFizz)
        : m_heldFizz(_givenFizz)
    {
    }

    void StartRunningThingsAsync()
    {
        // Run calculations with m_heldFizz.m_results asyncronously and then
        //    return from the other thread using the signal
        {
            m_heldFizz.m_finalResult = m_heldFizz.m_results[0];
            emit SignalStuffIsDone();
        }
    }

Q_SIGNALS:
    void SignalStuffIsDone();

private:
    Fizz& m_heldFizz;
};

class Foo
{
public:
    void RunCalculations()
    {
        m_usedFizz = new Fizz();
        m_usedFizz->m_results = {true, false};

        m_usedBar = new Bar(*m_usedFizz);
        connect(m_usedBar, &Bar::SignalStuffIsDone, this, &Foo::OnSignalStuffIsDone);
        m_usedBar->StartRunningThingsAsync();
    }

public Q_SLOTS:
    void OnSignalStuffIsDone()
    {
        if ( m_usedFizz->m_finalResult )
        {
            // Do some stuff
            std::cout << "Result is True";
        }
        else
        {
            // Do some different stuff
            std::cout << "Result is False";
        }

        delete m_usedBar;
        delete m_usedFizz;
    }

private:
    Fizz* m_usedFizz;
    Bar* m_usedBar;
};

int main(int argc, char* argv[])
{
    Foo foo1 = Foo();
    foo1.RunCalculations();
    std::cout << "Done";
}

I'm not sure if that's something that's ok over vs having Bar be something more like:

class Bar
{
public:
    Bar(Fizz* _givenFizz)
        : m_heldFizz(_givenFizz)
    {
    }

    void StartRunningThingsAsync()
    {
        // Run calculations with m_heldFizz.m_results asyncronously and then
        //    return from the other thread using the signal
        {
            m_heldFizz.m_finalResult = m_heldFizz.m_results[0];
            emit SignalStuffIsDone();
        }
    }

Q_SIGNALS:
    void SignalStuffIsDone();

private:
    Fizz* m_heldFizz;
};

Aucun commentaire:

Enregistrer un commentaire