C++ getter 函数 : const and non const

标签 c++ constants 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 中运行它,但它并没有给我更多的信息。

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

最佳答案

这里:

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

由于 *this 被转换为 Robot &(即未更改),因此调用了非常量版本的 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 也就是说,如果函数再复杂点,还是有一定意义的。

关于C++ getter 函数 : const and non const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435467/

相关文章:

C++ std::thread 应该在堆上或堆栈上创建

c++ - 使用 std::complex<double> 为 `*` 操作将 int 转换为 double

c++ - 如何在延迟着色系统中实现光遮挡?

C++ 常量使用说明

c++ - 通过重新使用的非 `const` 名称修改动态分配的 -`const` 对象是否合法?

c++ - Qml没有收到基类成员变量的更新值

C++ 在模板中使用静态常量类成员

C++:使用 Visual Studio 编译器时的常量指针

pointers - inout-parameter - 用另一个替换一个常量句柄

c++ - 在没有 const_cast 的情况下修改 *this 的 const 方法