【发布时间】:2023-04-04 01:19:01
【问题描述】:
class MoveSemantic{
public:
// For inserting a value
MoveSemantic(short &value);
MoveSemantic(short &&value);
short &storedValue;
};
// Reference forced to initialize
MoveSemantic::MoveSemantic(short &value) : storedValue(value) {}
MoveSemantic::MoveSemantic(short &&value) : storedValue(value) {}
// Passing a RValue => Assiging to reference => Is this safe ?
MoveSemantic semantik(100);
cout << semantik.storedValue; // 100
我最近发现可以通过滥用右值语义为类内的引用分配临时值... 但是为什么这可能呢?内存的行为如何?
这是否会由于分配而延长临时变量“100”的生命周期? 这有多安全?临时值什么时候被作用域破坏?
【问题讨论】:
标签: c++ pointers design-patterns reference move