从 boost::algorithm::join 返回值的范围是什么?
What is the scope of returned values from boost::algorithm::join?
您可以通过哪些方式使用boost::algorithm::join之类的返回值?
std::stringstream ss;
ss<<"quack";
std::cout << ss.str().c_str() << std::endl; // bad idea
这是一个坏主意,在 sbi 在 https://stackoverflow.com/a/1430774/的评论中解释道
std::vector<std::string> v;
v.push_back("foo");
v.push_back("bar");
std::cout << boost::algorithm::join(v,"-").c_str() << std::endl; // what about this?
这让我想知道这是否有同样的问题?
有人可以解释一下这种返回值的范围吗?
由于您没有存储对 char* 的引用,因此两个表达式都没有问题:
从标准.. http://isocpp.org/std/the-standard
Temporary objects are destroyed as the last step in evaluating the
full-expression (1.9) that (lexically) contains the point where they
were created. [12.2/3]
因此,在上述两种情况下,您在表达式中使用 char* 指针。boost::algorithm::join 和 stringstream.str() 在表达式末尾可用,c_str指针也是如此。
您发送的链接中的 sbi 注释是指从一个表达式中的临时字符串中获取 c_str(),并将其存储在 const char* 中,并将其传递给第二个语句中的 C 函数。
此外,我通常仅在调用需要 const char* 的 C 样式函数或外部库函数时才尝试使用 c_str。在 ostream 的情况下<<它已经接受了 std::string,并且需要 2 秒来添加运算符<<函数以支持新类型。
相关文章:
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- set_intersection范围范围
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 在 c++ 中解决段树以外的范围查询的有效方法是什么?
- 这个变量在 C++ 中的范围是什么?
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 满足标准::范围::范围概念
- 向量向量的范围范围
- 为什么这个循环变量在循环范围之外是可访问的
- 运算符重载中变量的数据类型和范围应该是什么
- 统一实际分布的范围限制是多少
- 用辅助方法范围范围的问题来操纵字符串
- 用于循环范围范围
- 在C++中实现随机预言机(输出在范围内是随机的,但对于相同的输入输出是相同的)
- 在C++11中,用什么方法对数组进行简单的范围管理是最干净的
- 矢量超出范围/范围检查
- 以一种漂亮的STL方式检查一个范围是否是另一个范围的子范围