【问题标题】:C++: a list with "const pointer" as members VS a list with "pointer to const" as membersC++:以“const 指针”为成员的列表 VS 以“指向 const 的指针”为成员的列表
【发布时间】:2013-05-27 01:28:06
【问题描述】:

如果有人问了这个问题,我深表歉意。

我知道“const 指针”与“指向 const 的指针”之间的含义和语法差异。

char * const myPtr;是“const 指针”,不能用作“myPtr = &char_B;”

const char * myPtr;是“指向 const 的指针”,不能用作“*myPtr = 'J';”

如果我使用 MFC 的容器,http://msdn.microsoft.com/en-us/library/fw2702d6%28v=vs.71%29.aspx

我想听听你们的cmets关于我的声明:

  1. CObList 或 CPtrList 不能满足我的要求,对吗?
  2. 我的第一个想法是使用CTypedPtrList,例如:

    CTypedPtrList 表示具有“常量指针”成员的列表。

这确实有效但“无用”:

class CAge
{
public:
    int   m_years;
    CAge( int age ) { m_years = age; }
};

CTypedPtrList<CPtrList, CAge* const> list;
list.AddTail(new CAge(10));
list.AddTail(new CAge(5));

POSITION pos = list.GetHeadPosition();
while(pos)
{
    CAge* a = (CAge*)list.GetNext(pos);
    a = new CAge(11);  //That's why I say it is "useless", because the returned value can be assigned

    list.GetNext(pos) = new CAge(11);   //Expected, can not pass compile
}
  1. 但是,CTypedPtrList 不起作用。我想要一个包含“指向 const 的指针”成员和更多的列表。

    CTypedPtrList<CPtrList, const CAge*> list2;
    //list2.AddTail(new CAge(10));          //Help! This does not pass compile, then how to initialize list2???
    //list2.AddTail(new CAge(5));
    
    POSITION pos2 = list2.GetHeadPosition();
    while(pos2)
    {
        CAge* a = (CAge*)list2.GetNext(pos2);
        a->m_years = 50;    //This passed compile. That's why I say "MORE".
    
        //((CAge*)list2.GetNext(pos2))->m_years = 50;       //This passed compile (because of type cast)
        //((const CAge*)list2.GetNext(pos2))->m_years = 50; //this does not pass compile (because of type cast as well)
    }
    
  2. 其实,对于上面的场景,我其实想要一个“神奇”的列表。如果一个指针(非常量指针)被添加到这个“魔术”列表中,那么稍后从列表中检索指针将是一个“常量指针”,不能使用该指针来改变指向对象的内容。

问题:如何定义“魔法”列表?

【问题讨论】:

    标签: c++ list pointers mfc constants


    【解决方案1】:

    不可能将新对象强制为const。类型系统仅确保指向旧对象的引用/指针保持const

    至于CAge* a = (CAge*)list2.GetNext(pos2);,只需移除演员表即可。强制类型转换破坏了类型系统(实际上这就是强制类型转换的重点),因此您应该不会对它们允许您通过 const 引用路径修改对象感到惊讶。

    【讨论】:

    • 谢谢!是的,正如你所说,如果我使用“CAge* a = list2.GetNext(pos2);”然后编译器可以捕获错误“错误C2440:'initializing':无法从'const CAge '转换为'CAge *'”;但是,如果我使用“CAge a = list.GetNext(pos);”,我仍然可以调用“a = new CAge(11);”然后。这是否意味着我对容器中 const 指针“无用”的评论仍然有效?
    • 另一个问题,初始化包含“指向 const”成员的列表的可能方法是什么?你知道是否有办法定义上一节中描述的这种“神奇”列表吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2014-10-18
    • 2016-02-26
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2013-05-02
    相关资源
    最近更新 更多