诀窍确保特定类的"仅"rvalues可以存在?

Joh*_*hnB 13 c++

在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)

现在,丰富的物体应该只是暂时的,因为它们不应该在被包裹的不良物体中存活.理想情况下,富集对象不应该存储在变量中,而只能作为对函数的右值引用传递.

有没有办法确保,即尽可能使其成为自动防故障?

Jar*_*d42 6

您可以仅提供 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)