【发布时间】:2015-04-03 15:51:29
【问题描述】:
我正在用 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 中运行它,但它并没有给我更多信息。
那么导致它崩溃的代码有什么问题?
【问题讨论】:
-
默认的构造函数是邪恶的。你为什么写这个?
-
是的,这是第一次实现。我实际上需要删除它。
-
简单的getter函数不需要返回常量引用,按值返回即可。还有非常量的 getter,当你所要做的就是返回实际变量时,为什么还要进行所有这些 const 转换?如果有的话,做相反的事情,非常量 getter 明确地返回变量,而常量 getter 执行
const_cast到const Robot,这对我来说似乎更安全。 -
既然你有一个 setter,我看不出有充分的理由通过引用返回它,这比让
_x公开更好。为什么不想按值返回 intint getX() const { return _x; } -
我只是想了解如何做好 const 正确的代码。所以我遵循了一些“规则”,我在这里似乎无法再次找到关于你应该如何做的事情(如果你不想再次写 getter)。我知道这里很丑:P.
标签: c++ constants const-correctness