std::reference_wrapper around *this
std::reference_wrapper around *this
我有一个方案,我需要将*this
链接到返回std::optional<std::reference_wrapper<T>>
而不是T&
而不是CC_3的函数(原因是此问题的范围不足)。我使用std::reference_wrapper
的原因是因为std::optional
无法进行参考,至少在C 11中不能进行参考。但是,这无效,因为我似乎遇到了终生问题。这是一个最小示例:
#include <iostream>
#include <functional>
struct test {
std::reference_wrapper<test> foo() {
val = 42;
return *this;
}
test& foo2() {
val = 50;
return *this;
}
int val;
};
void bar(test t) {
std::cout << std::move(t).val << "n";
}
int main()
{
auto f = test().foo();
bar(f);
auto g = test().foo2();
bar(g);
}
这将输出0 50
而不是预期的42 50
。如果我将其分为两个语句:
auto f = test();
auto f2 = f.foo();
bar(f2);
它可以按预期工作。使用调试器,我发现编译器正在优化某些表达式,而val
则是不可初学的,这使我认为我在代码中具有不确定的行为。
我的行为不确定吗?如果是这样,我该如何避免在这里?
我的行为不确定吗?
是。auto
从用于初始化它的表达式中推论对象的类型。然后,您使用类型std::reference_wrapper<test>
的表达式来初始化f
。临时test()
在初始化f
之后消失了,因此f
立即悬挂。
您可以像已经这样做一样拆分声明,也可以使用std::references_wrappers
的get成员函数:
auto f = test().foo().get();
无论哪种方式,std::reference_wrapper<test>
都不是替换的下降,以便在所有情况下C 支持。代理对象永远不会。
我的行为不确定吗?
是。看看线auto f = test().foo();
。f
是std::reference_wrapper<test>
,它指的是test()
。test()
的寿命在此行的末尾结束,您最终得到了悬空的参考。auto g = test().foo2();
并非如此,因为它复制了返回值(感谢@storyteller在这里帮助我)。
我如何在这里避开它?
您需要从std::reference_wrapper
零件中拆除寿命管理。这将有效:
test t;
auto f = t.foo();
// Do stuff with f until this scope ends.
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- 析构函数中的"delete this"
- 为什么成员函数内的"this"指针为空?
- 为什么我需要在转换构造函数上引用 this->?
- "this"指针的值在对象的生存期内是否恒定?
- std::reference_wrapper around *this