Search code examples
c++visual-studiofunctionmove-semanticspass-by-rvalue-reference

Can I forbid temporary objects as parameters?


Let's say I have the function:

void foo(Object& o) {
    /* only query o, dont alter it*/
}

Is it possible to call this function only with already constructed objects and have Visual Studio throw a compile error if I call the function with a temporary object?

struct Object {
    /*Members*/
}

void foo(Object& o) {
    /* only query o, dont alter it*/
}

int main() {
    Object o = Object();
    foo(o); // allow this
    foo(Object()) // but disallow this
}

Solution

  • If your parameter is not const, the function won't accept temporaries.

    If your parameter is const, the function accepts both temporary and regular objects.

    But if you want to prevent that, you can use the following

    struct Object{};
    void foo(const Object& o) {
        /*only query o, don't alter it*/
    }
    void foo(Object&& ) = delete;
    
    int main() {
        Object o;
        foo(o); // allow this
        foo(Object{}); // but disallow this
    }
    

    Live