Search code examples
c++gcc

Is there a way to force the use of auto_ptr to be a compile time error?


Perhaps I’ve missed it, but I’ve searched for this topic but haven’t found an answer.

I’ve just spent quite a bit of time removing all auto_ptr occurrences from our code base and we don’t want it creeping back in.

To clarify for the perfectly reasonable comment questions: We still allow it but we want it completely eliminated by the time we fully switch to C++20. I've removed the c++20 tag since it was misleading.

Is there a way to prevent programmers from using it in the future? Not a warning but completely prevent it.

If possible, I am looking for a solution that would just address the instances of auto_ptr, not all deprecated warnings.


Solution

  • auto_ptr was deprecated in C++11 and removed in C++17, so one easy way to turn use of auto_ptr into an error would be to compile your code as C++17 (or later). Not all compilers actually removed auto_ptr - leaving it in for backwards compatibility, but GCC for example emits a warning that can be turned into an error.

    To turn on C++17 standards compliant mode in the GCC compiler, build with the -std=c++17 flag. To turn the deprecation warning into an error, add the -Werror=deprecated-declarations flag.

    Example (foo.cc):

    #include <memory>
    int main() {
        std::auto_ptr<int> p;
    }
    

    Compile as: g++ -std=c++17 -Werror=deprecated-declarations foo.cc

    Result:

    foo.cc: In function ‘int main()’:
    foo.cc:4:8: error: ‘template<class> class std::auto_ptr’ is deprecated: use 'std::unique_ptr' instead [-Werror=deprecated-declarations]
        4 |   std::auto_ptr<int> p;
          |        ^~~~~~~~
    In file included from /usr/include/c++/13.1.1/memory:78,
                 from foo.cc:1:
    /usr/include/c++/13.1.1/bits/unique_ptr.h:65:28: note: declared here
       65 |   template<typename> class auto_ptr;
          |                            ^~~~~~~~
    cc1plus: some warnings being treated as errors