[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    Re: Weird "const"-ness problem
From:       Lubos Lunak <l.lunak () sh ! cvut ! cz>
Date:       2002-02-13 10:13:32
[Download RAW message or body]

On Wed 13. February 2002 10:29, Michael Goffioul wrote:
> Could anybody enlighten me on the following problem?
>
> In KPrinter class, there's a const function defined as
>
> const QString& KPrinter::option(const QString& key) const
> { return d->m_options[key]; }
>
> where d->m_options is a QMap<QString,QString>. Normally, the
> "const" attribute of this function should prevent the map from
> creating an empty entry in the map. I then have another class
> KPrinterImpl that is a friend of KPrinter. The problem is that
> when I call "printer->option(key)" somewhere in KPrinterImpl
> code, an empty key is created in the map, though the function
> is declared with "const". Why?
>
> Is this because of the "friendness" of KPrinterImpl?
> Is this because option() returns a reference instead of a plain
> QString object?
>
> Any help appreciated.

 Hmm. Another reason why to avoid putting things in the private d-pointer 
structure whenever possible.

 The 'd' pointer is of type 'KPrinterPrivate*'. In the context of the const 
method, it will be 'KPrinterPrivate *const', which is a const pointer to 
KPrinterPrivate, but not a pointer to const KPrinterPrivate (i.e. the pointer 
is const, but the data it points to isn't). Which means that d->m_options 
isn't a const object.

 The solution can be moving the data from KPrinterPrivate directly to the 
class, if it's possible, or changing the code to:

const QString& KPrinter::option(const QString& key) const
{
const KPrinterPrivate* const d_const = d;
return d_const->m_options[key];
}

-- 
 Lubos Lunak
 llunak@suse.cz ; l.lunak@kde.org
 http://dforce.sh.cvut.cz/~seli
 
>> Visit http://mail.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic