[Qt-interest] Const correctness with QSharedPointer
Stephen Jackson
spjackson42 at gmail.com
Mon Dec 7 22:31:43 CET 2009
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
More information about the Qt-interest-old
mailing list