lundi 24 février 2020

C++ primer 5 ed. Writing a move constructor for class String

I have this exercise from C++ primer 5 ed. It asks me to add a move constructor and a move assignment operator for my class String.

  • String has pointers to character (char*). It looks like:

    class String
    {
      public:
        String(String&&) noexcept; // move constructor
        String& operator=(String&&) noexcept;// move assignment operator
    
      private:
        iterator beg_; //using iterator = char*;
        iterator end_; 
        iterator off_cap_;
        alloc alloc_; // using alloc_ = std::allocator<char>
    
    };
    

Now in implementation file I've defined the move-ctor this way:

// move constructor
String::String(String&& rhs) noexcept :
    beg_(rhs.beg_), // or beg_(std::move(rhs.beg_))?
    end_(rhs.end_),
    off_cap_(rhs.off_cap_),
    alloc_(rhs.alloc_)// or alloc_(std::move(rhs.alloc_))?
{
    std::cout << "String move-ctor\n";
    rhs.beg_ = rhs.end_ = rhs.off_cap_ = nullptr; // putting objects in a destructible valid state
        // alloc_
}
  • So should I use std::move on those members or directly? because they are Built-in Pointers to char? - The two cases give me the expected results.

  • Should I move allocator alloc_? if So, how? and what will happen to the move-from alloctor? and how can I put in a destructible valid state?

  • Excuse me for such many questions. Thank you for your efforts and time.

PS: N.B: Please don't ask me about breaking the rule of 3, 5 and 6 because for readability and brevity I've not copied it from my source.

Aucun commentaire:

Enregistrer un commentaire