[Solved] Returning const QSharedPointer



  • Let's consider the following code:

    class Foo {
    	int a;	
    };
    
    class Bar {
    public:
    	Bar() {
    		_foo = new Foo;
    	}
    	
    	const Foo* foo() const {
    		return _foo;
    	}
    
    private:
    	Foo* _foo;
    }
    

    How would I implement the same behavior using QSharedPointer? I understand how to use QSharedPointer but I don't understand how I would return a QSharedPointer that is a const pointer (the return type of the public method in the Bar class) so that the caller of Bar::foo() gets just "const access" to the Foo object.



  • This post is deleted!


  • Here is a complete example. The trick is to use QSharedPointer<const Foo>.

    #include <QSharedPointer>
    #include <QDebug>
    
    struct Foo
    {
        ~Foo()
        {
            qDebug() << "Foo destroyed";
        }
    
        int count() { return 7; }
        int sum(int a, int b) const { return a + b; }
    };
    
    
    class Bar
    {
    public:
        Bar() : mFoo(new Foo) {}
        QSharedPointer<Foo> foo() { return mFoo; }
        QSharedPointer<const Foo> constFoo() const { return mFoo; }
    
    private:
        QSharedPointer<Foo> mFoo;
    };
    
    
    int main()
    {
        //intentially store it as a local variable
        //this shows how the reference count is incremented
        QSharedPointer<const Foo> constFoo(nullptr);
        {
            {
                Bar bar;
                constFoo = bar.constFoo();
    
                //error, discards const qualifiers of const Foo
                //qDebug() << constFoo->count();
                qDebug() << constFoo->sum(5, 6);
                qDebug() << bar.foo()->count();
            }
    
            qDebug() << "bar has gone out of scope, constFoo holds the last reference";
        }
    }


  • Awesome, thank you very much!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.