我找不到太多的信息const_cast.我能找到的唯一信息(在Stack Overflow上)是:
将
const_cast<>()用于添加/删除变量的常量(岬)(或挥发性岬).
这让我很紧张.可能const_cast会导致意外行为?如果是这样,什么?
或者,什么时候可以使用const_cast?
如何使适配器类适当地支持const和非const底层数据?
RigidBody是描述对象物理属性的类.
这是它非常简化的版本(1D): -
class RigidBody{
float position=1;
public: float getPosition()const{ return position;}
public: void setPosition(float ppos){ position=ppos;}
};
Run Code Online (Sandbox Code Playgroud)
Adapter封装RigidBody.
它提供了一个小失真的功能get/set position: -
class Adapter{
public: RigidBody* rigid; int offset=2;
public: float getPosition(){
return rigid->getPosition()+offset; //distort
}
public: void setPosition(float ppos){
return rigid->setPosition(ppos-offset); //distort
}
};
Run Code Online (Sandbox Code Playgroud)
我可以RigidBody通过以下方式间接设定位置Adapter: -
int main() {
RigidBody rigid;
Adapter adapter; //Edit: In real life, this type is a parameter of many function …Run Code Online (Sandbox Code Playgroud) 我最近在努力寻找一个很难找到的bug.我试图将lambda传递给一个获取std::function对象的函数.lambda正在捕获一个不可复制的对象.
我想通了,显然一些副本必须在所有通行证之间发生.我来到这个结果是因为我总是以error: use of deleted function错误结束.
以下是产生此错误的代码:
void call_func(std::function<void()> func)
{
func();
}
int main()
{
std::fstream fs{"test.txt", std::fstream::out};
auto lam = [fs = std::move(fs)] { const_cast<std::fstream&>(fs).close(); };
call_func(lam);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我通过在std::fstream对象中加载对象来解决这个问题std::shared_ptr.这工作正常,但我认为可能有更性感的方式来做到这一点.
我现在有两个问题:
fstream在for循环中生成了许多对象和lambda ,并且每个fstream都有一个lambda写入它.因此,fstream只能通过lambdas 来访问对象.我想为一些回调逻辑做这个.有没有像我尝试过的lambda那样更漂亮的方式?这似乎是一个愚蠢的问题,但我真的需要澄清一下:
这会给我的计划带来任何危险吗?
是否const_cast需要?
如果我更改了输入指针值,它是否可以安全地工作,std::string还是会创建未定义的行为?
到目前为止唯一的问题是,每当我修改输入指针并使其无法使用时,这可能会影响字符串"some_text".
std::string some_text = "Text with some input";
char * input = const_cast<char*>(some_text.c_str());
Run Code Online (Sandbox Code Playgroud)
谢谢你给我一些提示,我想避免自己拍摄
在C++程序中,我有一个结构,其中包含指向其自己类型的另一个实例的指针:
struct Foo
{
const Foo* ptr;
};
Run Code Online (Sandbox Code Playgroud)
我想声明并初始化这个结构的两个const实例,它们指向彼此:
const Foo f1 = {&f2};
const Foo f2 = {&f1};
Run Code Online (Sandbox Code Playgroud)
但是,这会导致编译时错误error: 'f2' was not declared in this scope(显然因为f1在f1之后声明,即使f1的声明引用它).
我正在努力做到可能和合理吗?如果是,我该如何使它工作?
一种解决方法可能是避免使f1 const,然后在声明f2之后重新分配指针f1.ptr = &f2;,但是如果可以的话我宁愿避免这种情况.