gpt4 book ai didi

c++ - boost::algorithm::join 返回值的范围是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:33:49 27 4
gpt4 key购买 nike

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

关于c++ - boost::algorithm::join 返回值的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21902776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com