Search code examples
c++14c++17autocopy-elisiondeleted-functions

How to disable instantiating a temporary class?


I'm working with an expression template class which should not be instantiated to avoid dangling references. But I'm temped to declare a variable with auto and 'auto' create a named instance of a temporary class.

How can I disable auto declaration of temporary class in the following code?

class Base
{
};

class Temp : public Base
{
public:
    Temp()         {}
    Temp(int, int) {}
    Temp(const Temp&) = default;
    Temp(Temp&&)      = default;
};

Temp testFunc(int a, int b) {
    return Temp{a,b};
}

int main() {
    Base a = testFunc(1,2); // this should work
    auto b = testFunc(1,2); // this should fail to compile
    return 0;
}

Solution

  • You seem to want to prevent users from using auto on a particular type. That's not possible in any version of C++. If it is legal C++ for a user to write T t = <expr>;, where T is the type of <expr>, then it will be legal for a user to write auto t = <expr>; (ignoring class data members). Just as you cannot forbid someone from passing <expr> to a template function using template argument deduction.

    Anything you do to prevent auto usage will also inhibit some other usage of the type.