我有一个返回 std::string
的 getter 并想将它复制到 char 数组
。
我的第一次尝试是使应用程序崩溃:expression: string iterators incompatible
std::copy(getString().begin(), getString().end(), array);
我通过添加一个临时变量解决了这个问题:
std::string temp = getString();
std::copy(temp.begin(), temp.end(), array);
有没有比使用临时变量或将返回类型更改为指针更好的方法(没有测试但假设这也有效)?
谢谢!
最佳答案
你没有说 getString()
有什么返回类型。有几个选项:
std::string getString();
const std::string& getString();
std::string& getString();
理想情况下,我们不关心什么,因为该界面将来可能会发生变化(今天听起来好像您不确定)。如果我们不必在接口(interface)更改的不幸事件中重新编写客户端代码,那将会很有帮助。
因此,与其使用临时引用,不如使用 const 引用:
const std::string& temp = getString();
std::copy(temp.begin(), temp.end(), array);
如果 getString
实际上返回一个字符串拷贝,您可能会感到惊讶,它的生命周期将与引用 temp
一样长。
如果它返回一个引用,代码仍然有效。
从 c++14 开始,更通用是有值(value)的:
auto&& temp = getString();
std::copy(std::begin(temp), std::end(temp), array);
getString()
现在可以返回对象或任何支持 value_type
char
关于c++ - std::copy with return values - 防止 "expression: string iterators incompatible"的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942052/