Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8234779

Provide idiom for declaring classes noncopyable


    • Subcomponent:
    • Resolved In Build:



        There have been occasional bugs arising from inappropriate use of default copy constructors or assignment operators. These often arise through a failure to follow the Rule of 3, e.g. if a class needs any of a non-trivial destructor, copy ctor, or assignment operator, it needs all three.

        A common case is a class that should never be copied, for semantic reasons. It would be helpful to have a simple idiom to support that case. This would make it obvious the Rule of 3 is followed for the class, and help make cases where it isn't stand out a bit more so they get additional scrutiny.

        The suggested solution for the noncopyable case is to provide the following macro:

        // Declare the named class to be noncopyable. This macro must be used in
        // a private part of the class's definition. Doing so provides private
        // declarations for the class's copy constructor and assignment operator.
        // Because these operations are private, most potential callers will fail
        // to compile because they are inaccessible. The operations intentionally
        // lack a definition, to provoke link-time failures for calls from contexts
        // where they are accessible, e.g. from within the class or from a friend
        // of the class.
        // Note: The lack of definitions is still not completely bullet-proof,
        // as an apparent call might be optimized away by copy elision.
        // For C++11 the declarations should be changed to deleted definitions.
        #define NONCOPYABLE(C) C(C const&); C& operator=(C const&);


            Issue Links



                • Assignee:
                  kbarrett Kim Barrett
                  kbarrett Kim Barrett
                • Votes:
                  0 Vote for this issue
                  3 Start watching this issue


                  • Created: