从 boost::algorithm::join 返回值的范围是什么?

What is the scope of returned values from boost::algorithm::join?

本文关键字:范围 范围是 是什么 返回值 boost algorithm join      更新时间:2023-10-16

您可以通过哪些方式使用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 秒来添加运算符<<函数以支持新类型。