在C++中是否有任何技巧可以确保类的用户只能生成rvalues?
例:
struct PoorClass { /* ... */};
struct EnrichedClass {
explicit EnrichedClass (const PoorClass & poor)
: m_poor (poor)
{
}
/* additional functionality for poor objects */
private:
const PoorClass & m_poor;
}
const EnrichedClass asEnriched (const PoorClass & poor)
{
return EnrichedClass { poor };
}
Run Code Online (Sandbox Code Playgroud)
现在,丰富的物体应该只是暂时的,因为它们不应该在被包裹的不良物体中存活.理想情况下,富集对象不应该存储在变量中,而只能作为对函数的右值引用传递.
有没有办法确保,即尽可能使其成为自动防故障?
您可以仅提供 r 值方法struct EnrichedClass:
struct EnrichedClass {
explicit EnrichedClass (const PoorClass& poor) : m_poor (poor) {}
/* additional functionality for poor objects */
void foo() &&; // note the && at the end.
private:
const PoorClass & m_poor;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
966 次 |
| 最近记录: |