qt-interest@trolltech.com
[Top] [All Lists]

Re: [Qt-interest] Const correctness with QSharedPointer

Subject: Re: [Qt-interest] Const correctness with QSharedPointer
From: Stephen Jackson
Date: Mon, 7 Dec 2009 21:31:43 +0000
2009/12/7 Brad Howes :
> On Dec 7, 2009, at 3:31 PM, Colin Kern wrote:
>
>> I want to pass a QSharedPointer to a function as a const pointer, so
>> that the compiler will enforce that I don't mutate the object the
>> shared pointer is pointing to.  Can I do this with "void func(const
>> QSharedPointer<A> p);" or does that just enforce that I won't change
>> what the shared pointer is pointing to?
>
>
> I usually use const QSharedPointer<A>& but your declaration is also correct.
>

I'm sorry but both of these options permit mutation of the object
pointed at, as demonstrated by the following code.

The commented out options 1 & 2 both compile, permit the increment and print 5.

The uncommented version is what you need to throw a compile-time error on ++*p;

#include <QtGui>
#include <iostream>

// 1. void foo(const QSharedPointer<int> p)
// 2. void foo(const QSharedPointer<int> & p)
void foo(const QSharedPointer<const int> p)
{
        ++*p;
}

int main()
{
        QSharedPointer<int> p(new int);
        *p = 4;
        foo(p);

        std::cout << *p << "\n";

        return 0;
}

i.e. you need "void func(const QSharedPointer<const A> p)"

-- 
HTH,

Stephen Jackson

_______________________________________________
Qt-interest mailing list
Qt-interest@xxxxxxxxxxxxx
http://lists.trolltech.com/mailman/listinfo/qt-interest

<Prev in Thread] Current Thread [Next in Thread>