简体   繁体   English

C ++滥用字符串连接

[英]C++ abuse of string concatenation

So I've generated some code over the last few months, maybe more, where I've use the C++ string library to concatenate strings. 所以我在最近几个月生成了一些代码,可能更多,我使用C ++字符串库来连接字符串。 Like so: 像这样:

template< typename T >
string tostr( const T & val ); // implmented wherever

void somelibraryfunction( const char * );

// begin actual code

somelibraryfunction( ( "foo" + tostr( 5 ) ).c_str( ) );

This compiles and works fine. 这编译并正常工作。 My concern is the string temporary that is created is destroyed after an address to it's c_str is taken, and I'm just relying on reading the recently freed but uncleared memory. 我关心的是创建的字符串临时在它的c_str的地址被删除后被销毁,而我只是依赖于读取最近释放但未清除的内存。 Any thoughts? 有什么想法吗?

The temporary string is not destroyed until the entire statement has completed, which isn't until after the library function returns. 在整个语句完成之前,临时字符串不会被销毁,直到库函数返回之后。 As long as the function doesn't save a copy of that address somewhere for later use, your code is fine. 只要该函数不在某处保存该地址的副本供以后使用,您的代码就可以了。 (Storing a copy of the string contents is fine; it just shouldn't store the char* pointer value, which becomes invalid when the temporary string goes away.) (存储字符串内容的副本很好;它只是不应该存储char*指针值,当临时字符串消失时它变为无效。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM