简体   繁体   English

C ++ getter函数:const和非const

[英]C++ getter function : const and non const

I'm writing a program with a robot class in C++. 我正在用C ++中的机器人类编写程序。 The following code, when I try to access the getter crash with 以下代码,当我尝试访问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

Here is the getter code : 这是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

I'm trying to implement the const and non const function correctly as I found it defined somewhere else on this site. 我正在尝试正确实现const和non const函数,因为我发现它在本网站的其他地方定义了。 The same kind of getter returning a std::vector works but as soon as try SomeRobot.getX() , it crashes. 返回std::vector的相同类型的getter可以工作,但是只要尝试SomeRobot.getX() ,它就会崩溃。

I've been running it in valgrind and it didn't gave me much more information. 我一直在valgrind中运行它,但没有给我更多信息。

So what is wrong in the code that makes it crash ? 那么,导致崩溃的代码有什么问题呢?

Here: 这里:

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

Since *this is cast to Robot & (ie, not changed), the non-const version of getX() is called, making this function infinitely recursive. 由于*this强制转换为Robot & (即未更改),因此将调用getX()非常量版本,从而使该函数无限递归。 It goes on to die with a stack overflow. 它继续死于堆栈溢出。

Instead, write 相反,写

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

to make getX() call getX() const . 使getX()调用getX() const The same applies for getY() . 同样适用于getY()

Obligatory note: Be very, very, very careful with const_cast . 强制性说明:使用const_cast要非常非常小心。 This is one of the few contexts where using it makes some sense 1 and is not insanely dangerous. 这是使用它的某些意义1 ,并且没有疯狂的危险的少数情况之一。 Although, I have to say that the function bodies of getX() and getY() are short enough that I'd have no qualms duplicating them. 虽然,我不得不说getX()getY()的函数体足够短,以至于我没有多余的重复条件。

1 That is to say, would make some sense if the functions were more complicated. 1也就是说,如果功能更复杂,那将是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM