通过非const指向self的方法在const方法中修改self [英] Modifying self within const method via non const pointer to self

查看:153
本文介绍了通过非const指向self的方法在const方法中修改self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中, const 对象可以通过 const 方法修改自身,因为在该方法中,它可以通过非常量指针。 (基于ideone的相同程序

  #include< iostream> 

结构对象;

对象* g_pObject;

结构对象
{
Object():m_a(0){}

void ModifySelfViaConstMethod()const
{
g_pObject-> m_a = 37;
}

int m_a;
};

int main()
{
对象o;
g_pObject =& o;

const对象& co = o;
std :: cout<< co.m_a<< \n;
co.ModifySelfViaConstMethod();
std :: cout<< co.m_a<< \n;

返回0;
}

我对阅读c ++标准不太满意,所以我在这里问:



标准对此有何说明?



a) const 方法不能保证您在执行此类操作时对象保持不变



b)是否定义明确并且必须编译



c)其他?

解决方案


标准怎么说?


它(解释)说这个类型为 const对象* ,因此您不能直接通过 this 修改成员或调用非const成员函数。它没有说明您可以使用该函数可能访问的任何全局变量执行的操作;它只控制对调用该函数的对象的直接访问。


const 方法不能保证您在执行此类操作时不会改变对象


否。它说明了该功能不会修改该对象的意图,并提供了一些保护以防止意外破坏该意图。但这并不能阻止一个精神错乱的程序员使用 const_cast 或通过全局变量进行不受控制的耦合来破坏承诺。


是否已明确定义并且必须编译


是。 o 本身不是常量,因此没有什么可以阻止您使用非const指针或对其进行引用。成员函数上的 const 仅限制通过 this 对对象的访问,而不限制通过其他指针对任意对象的访问。 / p>

In following example const object can modify itself via const method, because in that method it acces itself via non-const pointer. (same program on ideone)

#include <iostream>

struct Object;

Object * g_pObject;

struct Object
{
    Object():m_a(0){}

    void ModifySelfViaConstMethod() const
    {
        g_pObject->m_a = 37;
    }

    int m_a;
};

int main()
{
    Object o;
    g_pObject = &o;

    const Object & co = o;
    std::cout << co.m_a << "\n";
    co.ModifySelfViaConstMethod();
    std::cout << co.m_a << "\n";

    return 0;
}

I am not so good with reading c++ standard, so I ask here:

What does standard says about this?

a)const method doesn't guarantee you that your object stays unmodified when you do stuff like this

b) Is it well defined that and it must compile

c) other ?

解决方案

What does standard says about this?

It says (paraphrasing) that this has type const Object *, so that you can't directly modify members or call non-const member functions via this. It says nothing about what you can do with any global variables that the function might have access to; it only controls direct access to the object the function is called on.

const method doesn't guarantee you that your object stays unmodified when you do stuff like this

No it doesn't. It states the intent that the function won't modify the object, and provides some protection against accidentally breaking that intent. It doesn't prevent a suitably deranged programmer from using const_cast, or (as here) uncontrolled coupling via global variables to break the promise.

Is it well defined that and it must compile

Yes. o is not itself constant, so there's nothing to stop you taking a non-const pointer or reference to it. The const on the member function only restricts access to the object via this, not to arbitrary objects via other pointers.

这篇关于通过非const指向self的方法在const方法中修改self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆