C ++ getter函数:const和非const

时间:2015-04-03 15:51:30

标签: c++ const const-correctness

我正在用C ++编写一个带有机器人类的程序。以下代码,当我尝试使用

访问getter崩溃时
==19724== Stack overflow in thread 1: can't grow stack to 0xffe801ff8
==19724== Warning: client switching stacks?  SP change: 0x15788828 --> 0xffeffe990
==19724==          to suppress, use: --max-stackframe=68342473064 or greater
unknown location(0): fatal error in "trying": memory access violation at address: 0xffe801ff8: no mapping at fault address

以下是getter代码:

#ifndef ROBOT_MAP
#define ROBOT_MAP

#include <iostream>
#include <stdio.h>
#include <cv.h>
#include <highgui.h>

class Robot{
protected : 

    int _y;
    int _x;
public : 

    Robot(int x, int y): _x(x), _y(y){};

    void setX(int x){_x = x;}
    void setY(int y){_y = y;}

    const int& getX() const {return _x;}
    int& getX(){return const_cast<int&>(static_cast <Robot &>(*this).getX());}
    const int& getY() const {return _y;}
    int& getY(){return const_cast<int&>(static_cast <Robot &>(*this).getY());}


};
#endif

我正在尝试正确实现const和非const函数,因为我发现它在此站点上的其他位置定义。返回std::vector的同一类getter有效,但只要尝试SomeRobot.getX(),它就会崩溃。

我一直在valgrind中运行它并没有给我更多信息。

那么导致它崩溃的代码有什么问题?

1 个答案:

答案 0 :(得分:4)

下面:

int& getX(){return const_cast<int&>(static_cast <Robot &>(*this).getX());}

由于*this被强制转换为Robot &(即未更改),因此调用非{const}版本的getX(),使此函数无限递归。它继续死亡,堆栈溢出。

相反,写一下

//                                                     vvvvv-- here
int& getX(){return const_cast<int&>(static_cast <Robot const &>(*this).getX());}

getX()拨打getX() const。这同样适用于getY()

强制性说明:对const_cast非常非常非常小心。这是少数使用它的情况之一 1 并且不是非常危险。虽然,我必须说getX()getY()的功能主体足够短,以至于我没有任何疑虑重复它们。

1 也就是说,如果函数更复杂,会有所帮助。