Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming a typedef for a boost::shared_ptr<const Foo>

Silly question, but say you have class Foo:

class Foo
{
public:
    typedef boost::shared_ptr<Foo> RcPtr;

    void non_const_method() {}
    void const_method() const {}
};

Having a const Foo::RcPtr doesn't prevent non-const methods from being invoked on the class, the following will compile:

#include <boost/shared_ptr.hpp>

int main()
{
    const Foo::RcPtr const_foo_ptr(new Foo);
    const_foo_ptr->non_const_method();
    const_foo_ptr->const_method();

    return 0;
}

But naming a typedef ConstRcPtr implies, to me, that the typedef would be

typedef const boost::shared_ptr<Foo> ConstRcPtr;

which is not what I'm interested in. An odder name, but maybe more accurate, is RcPtrConst:

typedef boost::shared_ptr<const Foo> RcPtrConst;

However, Googling for RcPtrConst gets zero hits, so people don't use this as a typedef name :)

Does anyone have any other suggestions?

like image 388
Blair Zajac Avatar asked Oct 31 '25 08:10

Blair Zajac


1 Answers

The name of a typedef does not represent the syntactical construct used to define its type. The typedef name should convey some of its desired meaning. For example, the Standard defines the names of iterators over const T as const_iterator, even though the iterator itself is not const (you can still increment it). In fact, the whole purpose of an iterator is to change it, in order to iterate over a sequence :)

typedef T const* const_iterator;

For pointers, i personally see little reason to generally typedef them as constant. So the Const in front of the trailing parts could convey the same meaning as the iterators do, and will go with existing practice. So i think it is perfectly fine for you to go and say

typedef boost::shared_ptr<Foo const> ConstRcPtr;

In fact, this is how std::allocator<>::const_pointer is worded too.

like image 181
Johannes Schaub - litb Avatar answered Nov 02 '25 22:11

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!