Correct use of `= delete` for methods in classes

后端 未结 2 1596
被撕碎了的回忆
被撕碎了的回忆 2021-01-31 08:42

Is the following snipplet correct for un-defining all otherwise generated methods and constructors for a class?

struct Picture {

  // \'explicit\': no accidenta         


        
相关标签:
2条回答
  • 2021-01-31 09:31

    In addition to Xeo's answer:

    Yes, everything is correct. If you wanted you could eliminate all of the deleted members but the deleted copy constructor and deleted copy assignment and have the same effect:

    struct Picture {  // Also ok
    
      // 'explicit': no accidental cast from string to Picture
      explicit Picture(const string &filename) { /* load image from file */ }
    
      // no copy
      Picture(const Picture&) = delete;
    
      // no assign
      Picture& operator=(const Picture&) = delete;
    };
    

    The explicit declaration of the copy constructor inhibits the implicit generation of the default constructor, move constructor and move assignment members. Having these members explicitly deleted is a matter of taste. Some will probably see it as good documentation. Others may see it as overly verbose.

    0 讨论(0)
  • 2021-01-31 09:35

    Seems fine to me. The return value of operator= must be a normal reference, even if the object is constructed from a rvalue reference. That is because you can't just compile an lvalue (*this) to an rvalue.
    And it should take that rvalue reference per non-const Picture& operator=(Picture&&). How would you move from a constant object? ;)

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