Macros to disallow class copy and assignment. Google -vs- Qt

前端 未结 11 1237
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 06:22

To disallow copying or assigning a class it\'s common practice to make the copy constructor and assignment operator private. Both Google and Qt have macros to make this eas

相关标签:
11条回答
  • 2020-12-13 07:09

    Qt version is backward compatible, while google's is not.

    If you develop your library and deprecate the use of assignment before you completely remove it, in Qt it will most likely retain the signature it originally had. In this case older application will continue to run with new version of library (however, they won't compile with the newer version).

    Google's macro doesn't have such a property.

    0 讨论(0)
  • 2020-12-13 07:12

    I'd just like to mention that there is an alternative strategy for implementing an abstraction for disallowing copy and assignment of a class. The idea is to use inheritance instead of the preprocessor. I personally prefer this approach as I follow the rule of thumb that it is best to avoid using the preprocessor when at all possible.

    boost::noncopyable is an example implementation. It is used as follows:

    class A : noncopyable
    {
        ...
    };
    
    0 讨论(0)
  • 2020-12-13 07:12

    Both serve the same purpose

    Once you write this one:

    Class &operator=(const Class &);
    

    you will get the benefits of chain assignments. But in this case you want the assignment operator to be private. so it doesn't matter.

    0 讨论(0)
  • 2020-12-13 07:14

    Incidentally, if you have access to the Boost libraries (You don't? Why the heck not??), The Utility library has had the noncopyable class for a long time:

    class YourNonCopyableClass : boost::noncopyable {
    

    Clearer IMHO.

    0 讨论(0)
  • 2020-12-13 07:15

    From the standard, 12.8, clause 9: "A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X&, or const volatile X&." It says nothing about the return type, so any return type is permissible.

    Clause 10 says "If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly."

    Therefore, declaring any X::operator=(const X&) (or any other of the specified assignment types) is sufficient. Neither the body nor the return type is significant if the operator will never be used.

    Therefore, it's a stylistic difference, with one macro doing what we'd likely expect and one saving a few characters and doing the job in a way that's likely to surprise some people. I think the Qt macro is better stylistically. Since we're talking macro, we're not talking about the programmer having to type anything extra, and failing to surprise people is a good thing in a language construct.

    0 讨论(0)
提交回复
热议问题