【发布时间】:2021-08-25 20:56:00
【问题描述】:
下面的行为也不如我所愿,因为在基于范围的 for 循环进入主体之前调用了 Foo 的析构函数,从而使迭代器无效(msvc 2019)。
有没有办法在不更改以下代码中的语法的情况下“捕获” Foo 对象?我已经看到了 for 循环的 c++20 初始化程序部分,但是如果有不需要它的替代解决方案,那将是首选。
struct Foo
{
Foo& operator<<(std::string s) { ...; return *this }
auto begin() {...}
auto end() {...}
}
for (auto& row : Foo() << "bar")
{
// this fails because destructor of Foo is already called
// how to extend the lifetime of the Foo object into the scope of the for loop?
}
【问题讨论】:
-
长话短说,不。临时对象的生命周期延长不会通过函数调用来延长(
operator <<就是这样) -
@NathanOliver 我在想
Foo operator<<(std::string s) && { ...; return std::move(*this); }的方向(但还没有让它工作)这似乎是一个潜在的解决方案? -
就像我说的,临时对象不会通过函数调用来生存。没有办法解决这个问题。既然要使用
Foo() << "bar",那是做不到的。你可以创建一个构造函数来调用你的operator <<,然后你的语法就会变成for (auto& row : Foo("bar"))。 -
@NathanOliver 在上面评论的示例中,我移动了临时 Foo,并返回了新版本。正如您所说,现在为空的对象不会在函数调用中存活,但这不重要吗?
-
我想念你按价值返回。那应该确实有效。可能想就这样实现的功能提出一个新问题,但如果它给您带来错误/意外行为,请确保提供minimal reproducible example。
标签: c++ syntax c++17 syntactic-sugar