是一个好主意,返回“ const char *“从一个函数? [英] Is it a good idea to return " const char * " from a function?

查看:737
本文介绍了是一个好主意,返回“ const char *“从一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个函数必须返回一个字符串。我看到一个特定的实现,他从函数返回一个const char *。



这样:

  const char * GetSomeString()
{
........
return somestlstring.c_str
}

SomeOtherFoo()
{
const char * tmp = GetSomeString();
string s = tmp;
}

现在我觉得有可能是错误的。我的肠子感觉不错吗?或者这是一个完全安全的代码吗?



请给我建议。我有一个感觉返回const char *这种方式可能会导致havoc ..



谢谢,
Arjun



b b b b b b b b b b

如果它是一个局部变量,你将返回一个指针,当 GetSomeString 完成时释放内存,因此它是一个悬空指针和错误。



这一切都归结于 somestlstring 的生命周期以及你对它执行的操作。由 .c_str()返回的指针保证只在字符串中的下一个变异操作有效。因此,如果事件从 .c_str() s 之前的调用改变 somestlstring code>构建你将处于未定义的行为土地。


Now I have a function that has to return a string. I saw a particular implementation where he returns a const char * from the function.

Something like this:

const char * GetSomeString() 
{ 
  ........   
  return somestlstring.c_str(); 
}

SomeOtherFoo ()
{
  const char * tmp = GetSomeString();
  string s = tmp;
}

Now I felt there is something potentially wrong with this. Is my gut feel right? or Is this a perfectly safe code?

Kindly give me ur suggestions. I have a feeling return const char * this way might result in havoc..

Thanks, Arjun

解决方案

Depending on what somestlstring is and what is being done there.

If it is a local variable you are returning a pointer into memory that is being released when GetSomeString completes, so it is a dangling pointer and an error.

It all boils down to the lifetime of somestlstring and the operations you perform on it. The pointer returned by .c_str() is guaranteed to be valid only up to the next mutating operation in the string. So if something changes somestlstring from the call to .c_str() and before s is constructed you will be in undefined behavior land.

这篇关于是一个好主意,返回“ const char *“从一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆