Search code examples
c++constantspass-by-referencetemporary-objects

const reference function parameter: Is it possible to disallow temporary objects?


It it possible to have a function parameter that enforces the following semantics:

The parameter will not be altered by the function. Calling the function never creates copy or temporary object for the parameter.

Example:

void f(const std::string & str);

Interface tells clients that the parameter will not be altered, and if the parameter is already of type std::string, no copy is created.

But it is still possible to call this as

const char * hello = "hello";
f(hello);

which creates a temporary std::string object before the function f is entered and destroys it again after exit from f.

Is it possible to disallow this, either with a different function declaration, or by (hypothetically) altering std::string implementation.


Solution

  • I'm going to start from the end here.

    or by (hypothetically) altering std::string implementation

    Don't do this, for fear of nasal demons. Seriously, don't. Let the standard library behave in a standard fashion.

    Is it possible to disallow this, either with a different function declaration

    Another declaration is just the ticket, as a matter of fact. Add an overload that accepts an r-value reference, and define it as deleted:

    void f(std::string && str) = delete;
    

    Overload resolution will pick it for temporaries, and the deleted definition will cause an error. Your intended function can now only be called with l-values.