How to actually implement the rule of five?

后端 未结 6 1137
遥遥无期
遥遥无期 2020-11-28 04:05

UPDATE at the bottom

q1: How would you implement the rule of five for a class that manages rather heavy resources, but of which you

6条回答
  •  孤城傲影
    2020-11-28 04:41

    Let me help you:

    #include 
    
    class AnObject
    {
    public:
      AnObject( size_t n = 0 ) : data(n) {}
    
    private:
      std::vector data;
    };
    

    From the C++0x FDIS, [class.copy] note 9:

    If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

    • X does not have a user-declared copy constructor,

    • X does not have a user-declared copy assignment operator,

    • X does not have a user-declared move assignment operator,

    • X does not have a user-declared destructor, and

    • the move constructor would not be implicitly defined as deleted.

    [ Note: When the move constructor is not implicitly declared or explicitly supplied, expressions that otherwise would have invoked the move constructor may instead invoke a copy constructor. —end note ]

    Personally, I am much more confident in std::vector correctly managing its resources and optimizing the copies / moves that in any code I could write.

提交回复
热议问题