c++ - 将 const char * const 参数的成员分配给新值

标签 c++ casting constants

我正在处理一个第三方库,为了简化我的代码,我想修改其中的结构。

有第三方结构

struct structure {
    const char *c;
    // ...
};

我有一个函数

void prep(const structure *s) {
    std::string str("hello");
    const char *t_c = s->c;
    s->c = str.c_str(); // structure::c is a const char *
    handle(s); // makes use of overriden c
    s->c = t_c; // Set back in case library tries to free/use memory later
}

我如何在这里进行适当的 const 转换?

最佳答案

我假设 handle 声明为 void handle(const structure*);

最简单的解决方案是复制s,修改拷贝然后将其传递给handle。由于 sconst,您知道可以对需要传播到原始 s 的拷贝进行任何更改。您还无需将 s->c 重置为其原始值。

void prep(const structure *s) 
{
    structure mycopy(*s); // Make a copy of s
    std::string str("hello");
    mycopy.c = str.c_str(); // structure::c is a const char *
    handle(&mycopy); // makes use of overriden c
}

如果您无法复制结构,请考虑通过删除sconst 说明符来修改您的函数声明。如果您简单地删除 const ,您将获得以下可以正常编译的函数。请注意,生成的函数不是异常安全的。如果 handle 抛出异常,您将无法将 s->c 成员重置为其原始值。

void prep(structure *s)
{
    std::string str("hello");
    const char *t_c = s->c;
    s->c = str.c_str(); // structure::c is a const char *
    handle(s); // makes use of overriden c
    s->c = t_c; // Set back in case library tries to free/use memory later
}

如果一切都失败了,你也许可以使用 const_cast作为最后的手段。确保 s 没有指向实际上是 const 的实例,并确保当 s 不在其中时不会抛出异常原始状态。被迫使用 const_cast 可能表明设计决策不当。

void prep(const structure *s) 
{
    std::string str("hello");
    const char *t_c = s->c;
    const_cast<structure*>(s)->c = str.c_str(); // structure::c is a const char *
    handle(s); // makes use of overriden c
    const_cast<structure*>(s)->c = t_c; // Set back in case library tries to free/use memory later
}

关于c++ - 将 const char * const 参数的成员分配给新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43613157/

相关文章:

c++ - const 指针或引用的位置

c++ - 使用 OpenGL 在 C++ 中弹出文本输入框

c# - IsAssignableFrom、IsInstanceOfType 和 is 关键字,有什么区别?

c++ - boost::phoenix::static_cast_ 编译错误

C++ 将 int 转换为 double

C++如何将非常数列表传递给需要常量列表的函数

java - 为什么最终变量不总是一个常量表达式?

c++ - future 与 promise

c++ - 用spirit x3解析递归规则

c++ - OpenGL ping pong 一次通过,而不是两次