是有问题的stringstream.str()。c_str()? [英] is there issue will stringstream.str().c_str()?

查看:292
本文介绍了是有问题的stringstream.str()。c_str()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

  stringstream ss(012345678901234567890123456789012345678901234567890123456789); 

一些文章说由于ss.str返回temp对象,调用.c_str();

  const char * cstr2 = ss.str 

但我运行的例子,没有问题?如何理解?

解决方案


但是我运行的例子,没有问题? >

事实上,表达式没有问题:

  const char * cstr2 = ss.str()。c_str(); 


ss.str()返回的临时(复制) code>将会运行足够长的时间,让你得到底层的c字符串与 c_str()



当然,在表达式的末尾你会有一个 const char 指向一个可能 deallocated(这在很大程度上取决于 std :: basic_string 实现)。



因此这可能不是一个好主意。你应该做的是:

  auto x = ss.str(); 
const char * cstr2 = x.c_str();

上面的代码不会给你带来麻烦,因为返回值 str()现在正被复制/不再是临时的,访问 x.c_str()会给你一个有效的指针。


For Code:

stringstream ss("012345678901234567890123456789012345678901234567890123456789");  

some articles said it is wrong for followed usage due to ss.str return temp object and will destructered before call .c_str();

 const char* cstr2 = ss.str().c_str();  

but I run the example, there is no problem? how to understand?

解决方案

But I run the example, there is no problem?

In fact, there's nothing wrong in the expression:

const char* cstr2 = ss.str().c_str();

The temporary (copy) object returned by ss.str() will live long enough to let you get the underlying c-string with c_str().

Of course by the end of the expression you'll have a const char pointer to an object that is probably deallocated (this depends heavily on the std::basic_string implementation).

Therefore this is likely not a good idea. What you should do instead is:

auto x = ss.str();
const char* cstr2 = x.c_str(); 

The above code won't get you any trouble, since the returned value of str() is now being copied/is not a temporary anymore, and the access to x.c_str() will give you a valid pointer.

这篇关于是有问题的stringstream.str()。c_str()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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