C++getter函数:常量和非常量
C++ getter function : const and non const
我正在用C++编写一个带有robot类的程序。以下代码,当我尝试使用访问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和nonconst函数,因为我在这个网站的其他地方发现了它的定义。返回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());}
使CCD_ 6调用CCD_。getY()
也是如此。
必须注意:小心const_cast
。这是为数不多的使用它有意义的情况之一1并且没有疯狂的危险。尽管如此,我不得不说getX()
和getY()
的功能体足够短,我毫不犹豫地复制它们。
1也就是说,如果函数更复杂,这将是有意义的。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性