从函数返回“c_str” [英] Returning 'c_str' from a function

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

问题描述

这是从一个小库,我在网上找到:

 为const char * GetHandStateBrief(常量PostFlopState *状态)
{
    静态的std :: ostringstream出来;    // ...函数的其余部分...    返回out.str()。c_str()
}

在我的code我这样做:

 为const char * D = GetHandStateBrief(安培;后);
性病::法院LT&;< D<<的std :: ENDL;

现在,在第一个 D 包含垃圾。后来我意识到,当函数返回,因为的std :: ostringstream 是在栈上分配的,我从函数获取C字符串被破坏。于是我又说:

(out.str()c_str())

 的strdup回报;

而现在我能得到我从功能所需要的文本。

我有两个问题:


  1. 我是否理解正确吗?


  2. 我后来注意到,退出(类型为的std :: ostringstream 的)与静态存储分配。并不意味着该对象是应该留在内存中,直到程序终止?如果是这样,那么为什么不能字符串进行访问?



解决方案

的strdup分配字符串的堆一个副本,您必须手动以后免费的(免费()我认为)。如果可以选择,那会好得多返回的std ::字符串

的静态存储了没有帮助,因为名为.str()返回一个临时的std ::字符串,这是破坏了函数退出的时候。

This is from a small library that I found online:

const char* GetHandStateBrief(const PostFlopState* state)
{
    static std::ostringstream out;

    // ... rest of the function ...

    return out.str().c_str()
}

In my code I am doing this:

const char *d = GetHandStateBrief(&post);
std::cout<< d << std::endl;

Now, at first d contained garbage. I then realized that the C string I am getting from the function is destroyed when the function returns because std::ostringstream is allocated on the stack. So I added:

return strdup( out.str().c_str());

And now I can get the text I need from the function.

I have two questions:

  1. Am I understanding this correctly?

  2. I later noticed that out (of type std::ostringstream) was allocated with static storage. Doesn't that mean that the object is supposed to stay in memory until the program terminates? And if so, then why can't the string be accessed?

解决方案

strdup allocates a copy of the string on the heap, which you have to free manually later (with free() I think). If you have the option, it would be much better to return std::string.

The static storage of out doesn't help, because .str() returns a temporary std::string, which is destroyed when the function exits.

这篇关于从函数返回“c_str”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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