C++ 从函数返回“ const char * ”是个好主意吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2514539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:45:29  来源:igfitidea点击:

Is it a good idea to return " const char * " from a function?

c++string

提问by AMM

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.

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

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..

请给我你的建议。我有一种感觉 return const char * 这种方式可能会导致严重破坏..

Thanks, Arjun

谢谢,阿琼

回答by David Rodríguez - dribeas

Depending on what somestlstringis and what is being done there.

取决于那里somestlstring是什么以及正在做什么。

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

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

It all boils down to the lifetime of somestlstringand 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 somestlstringfrom the call to .c_str()and before sis constructed you will be in undefined behavior land.

这一切都归结为生命周期somestlstring以及您对其执行的操作。由 返回的指针.c_str()保证仅在字符串中的下一个变异操作之前有效。因此,如果somestlstring从调用 to 到构造.c_str()之前发生了变化,s您将处于未定义的行为领域。

回答by AMM

If you are asking about the lifetime of the const char *returned by the std::stringc_str()function, it is valid until you modify the string you obtained it from, or until the string is destroyed. Returning it from a function is OK (though I would say not great practice), provided you bear those two facts in mind.

如果您询问函数const char *返回 的生命周期std::stringc_str(),则在您修改从中获取它的字符串或字符串被销毁之前,它都是有效的。从函数返回它是可以的(尽管我会说这不是很好的做法),前提是您牢记这两个事实。

回答by Johannes Schaub - litb

This is OK under the conditions @Neil elaborated on. However a better way would be to return a reference to the string

在@Neil 阐述的条件下,这是可以的。然而,更好的方法是返回对字符串的引用

string const& GetSomeString() 
{ 
  ........   
  return somestlstring; 
}

string s = GetSomeString();

Still keeping in mind that ′somestlstring` must not be a local automatic variable but stored somewhere else in a namespace or a class. Otherwise you can return the string by value

仍然要记住,'somestlstring' 不能是局部自动变量,而是存储在命名空间或类中的其他地方。否则,您可以按值返回字符串

string GetSomeString() 
{ 
  ........   
  return somestlstring; // can be a local automatic variable
}

string s = GetSomeString();

回答by peterchen

To add some scenarios in which this would be ok:

添加一些可以的场景:

  • somestlstringis a global variable initialized in the same translation unit (.cpp) as GetSomeString()
  • somestlstringis a non-static class member, and GetSomeString is a member of that class. In that case, the lifetime of the pointer returned must be documented (basically - as others said - until the strign changes or the object is destroyed)
  • you are returning a char const * to a literal or compile-time initialized string
  • somestlstring是在与 GetSomeString() 相同的翻译单元 (.cpp) 中初始化的全局变量
  • somestlstring是非静态类成员,而 GetSomeString 是该类的成员。在这种情况下,必须记录返回的指针的生命周期(基本上 - 正如其他人所说 - 直到 strign 更改或对象被销毁)
  • 您将 char const * 返回到文字或编译时初始化的字符串

回答by Thomi

It's not great - how long does the memory for your string stick around? Who is responsible for deleting it? Does it need to be deleted at all?

这不是很好 - 您的字符串的内存会保留多长时间?谁负责删除它?有必要彻底删除吗?

You're better off returning a string object that is responsible for allocating and freeing the string memory - this could be a std::string, or a QString (if you're using Qt), or CString (if you're using MFC / ATL).

你最好返回一个负责分配和释放字符串内存的字符串对象——这可能是一个 std::string,或者一个 QString(如果你使用 Qt),或者 CString(如果你使用 MFC) / ATL)。

on a slightly different note, will your string ever be unicode? Most string classes can deal transparently with unicode data, but const char will not...

稍微不同一点,你的字符串会是 unicode 吗?大多数字符串类可以透明地处理 unicode 数据,但 const char 不会......

回答by Didier Trosset

It depends upon where the somestlstringvariable is located.

这取决于somestlstring变量所在的位置。

If it is a variable locale to the GetSomeString()function, then this is plainly wrong. Indeed, the somestlstringvariable is destroyed at the end of the function, and thus the const char *points to something that does not exist anymore.

如果它是GetSomeString()函数的可变语言环境,那么这显然是错误的。事实上,somestlstring变量在函数结束时被销毁,因此const char *指向不再存在的东西。

If it is a global variable, then this code is right.

如果是全局变量,那么这段代码就对了。