mardi 4 octobre 2016

Specifying a `const int&` that doesn't bind temporaries

Is there a way to specify a constant reference as an argument type (of a function) that doesn't bind temporaries? That is, is there a standard way to specify both that the reference is const but that it can only bind to non-temporary values, with attempting to bind to a temporary resulting in a compiler error¹?


For example, in the case of the constructor of a class X,

class X
{
public:
    X(const int &value)
      : mValue(value)
    {}

private:
    const int &mValue;
};

what would be a nice way to ensure that

class Y
{
public:

    /* ... */

    X* GetXForValue() const
    {
        return new X(mValue);
    }

private:
    int mValue;
};

compiles, but when called with a temporary, e.g. X x(100);, it does not?


¹) I could overload the function for int&& and then not define it, but that would give the wrong idea and only result in a linker error.

Aucun commentaire:

Enregistrer un commentaire