簡體   English   中英

為boost :: shared_ptr命名typedef <const Foo>

[英]Naming a typedef for a boost::shared_ptr<const Foo>

愚蠢的問題,但說你有Foo課:

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

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

使用const Foo :: RcPtr不會阻止在類上調用非const方法,以下將編譯:

#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;
}

但是命名一個typedef ConstRcPtr對我來說意味着typedef會是

typedef const boost::shared_ptr<Foo> ConstRcPtr;

這不是我感興趣的。一個更奇怪的名字,但可能更准確,是RcPtrConst:

typedef boost::shared_ptr<const Foo> RcPtrConst;

但是,谷歌搜索RcPtrConst獲得零命中,因此人們不會將其用作typedef名稱:)

有沒有人有任何其他建議?

typedef的名稱不表示用於定義其類型的語法結構。 typedef名稱應該傳達它的一些期望的含義。 例如,標准將const T的迭代器名稱定義為const_iterator ,即使迭代器本身不是const(您仍然可以增加它)。 事實上,迭代器的整個目的是改變它,以便迭代序列:)

typedef T const* const_iterator;

對於指針,我個人認為沒有什么理由通常將它們定義為常量。 因此,尾隨部分前面的Const可以傳達與迭代器相同的含義,並且將與現有實踐一致。 所以我認為你去發言完全沒問題

typedef boost::shared_ptr<Foo const> ConstRcPtr;

實際上,這就是std::allocator<>::const_pointer的措辭。

關於const去向的說法是對的:你需要另一個typedef。 在我們的項目中,我們使用Foo :: TPtrFoo :: TConstPtr作為標准typedef。

為什么這意味着? 當人們談論“常量指針”(與非常量指針相反)時,它們幾乎總是指const char* ,而不是char *const const_iterator是一個迭代器到const,而不是一個const的迭代器,我不會感到驚訝的是ConstRcPtrRcPtr之間的關系與const_iteratoriterator之間的關系是一樣的。

如果你需要區分const char*char *const ,那么是的,你可以將char *const稱為“const指針”,將const char*稱為“指向const的指針”。 但你幾乎從不這樣做,因此短語“const指針”用於常見情況。 我認為這也適用於此,除非您計划鍵入以下四個:

boost::shared_ptr<Foo>
boost::shared_ptr<const Foo>
const boost::shared_ptr<Foo>
const boost::shared_ptr<const Foo>

在這種情況下,您必須對名稱更有創意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM