gpt4 book ai didi

c - To const or not to const--当我的代码不会修改用户代码的字符串但我依赖的第三方代码忘记声明const时声明什么?

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:53 24 4
gpt4 key购买 nike

将以下代码视为组织中开发的大型项目,其中 our_function() 是内部开发的,我们可以完全控制它。 main() 是由我们的用户编写的,他们将链接到我们的库并调用 our_function()。但是 third_party_function() 是由另一家外部公司开发的,我们无法控制它;我们只能按原样使用它。

#include <stdio.h>

void third_party_function(char *s)
{
// s[1] = 'E'; // We're sure that this function doesn't have code like this.
printf("third_party_function: s: %s\n", s);
}

void our_function(const char *s)
{
/* Do something with s but treat it as read-only. */

/* our_function depends on third_party_function. we know that
* third_party_function is never supposed to modify the string passed to it
* but the third party developer of third_party_function forgot to declare
* its argument as 'const char *', hence the type cast below. */
third_party_function((char *) s);
}

int main()
{
char *s = "hello, world";

/* Do something with s, but treat it as read-only. */

/* our_function is developed in-house; we are sure that our_function should
* never modify the string passed to it. */
our_function("hello, world");

/* Do something more with s. Here we just print it to make sure
* our_function() has not modified it. */
printf("main: s: %s\n", s);
return 0;
}

我们 100% 确定 our_function() 永远不会修改传递给它的字符串。

我们也 100% 确定 third_party_function() 永远不会修改传递给它的字符串。

但是第三方开发者忘记用 const 限定符来限定 third_party_function() 的参数。

所以现在我面临的困境是是否要用 const 限定 our_function() 的参数,从而告诉我们的用户我们不会修改您的字符串。

我有两个相反的论点:

  1. 支持void our_function(const char *s) 的论点:我们想告诉我们的用户他们的字符串不会被修改。所以他们可以自由地传递常量字符串。
  2. 反对 void our_function(const char *s) 的论点:如果第三方代码的 future 升级导致 third_party_function() 修改它获取的字符串(假设他们取消注释s[1] = 'E' 语句),用户在编译时不知道他们的代码可能在运行时因段错误而崩溃。他们在编译时可能获得的任何有用的诊断都被强制的 (char *) 类型转换抑制了,这是将参数声明为 const char * 的直接结果。

这两个论点中的哪一个(耶!双关语!)在技术上是正确的论点?

注意:为了保持这个问题的客观性并防止它基于观点,我正在寻找能够得出一个选项优于另一个选项的结论的技术论据(而非观点)。如果从技术角度来看,没有一个选项是好的,那么这就是正确答案。如果有更好的选择,请在回答中告诉我。

最佳答案

为了安全起见,复制您收到的 C 字符串并使用该副本调用第三方函数,并让您自己的函数使用 const 限定符(如果它符合其语义)。

关于c - To const or not to const--当我的代码不会修改用户代码的字符串但我依赖的第三方代码忘记声明const时声明什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37327204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com