-1
CString s("ok");
CString alpha=move(s);

using this exact code, the compiler uses copy constructor to initial alpha...!

but when i explicitly define move constructor it uses move constructor and done the work according to the need...!

The question is when you have a keyword Move,and even by using the move keyword(not defining a move constructor by yourself), it still uses the copy constructor...Why, what is the default coding of move constructor and what is the use of move keyword when there is no Move constructor defined by our side..?

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 5
    `move` is a function, not a keyword. It also doesn't move anything. Move constructors do the moving. – chris Dec 12 '17 at 19:13
  • 1
    Possible duplicate of [What are move semantics?](https://stackoverflow.com/questions/3106110/what-are-move-semantics) – user1810087 Dec 12 '17 at 19:15
  • @chris i know that. That is not what i am asking bro. When there is a move constructor available in our class, it uses move constructor. But if we donot use this move fuction. copy constructor is called – Hamza Farooqi Dec 12 '17 at 19:19
  • 2
    @HamzaFarooqi in simple words: It collapses to a copy... https://stackoverflow.com/q/13725747/1810087 – user1810087 Dec 12 '17 at 19:20
  • I read in a book that the move function converts Lvalue to an R value refernce. Once i changed the reference of 's' as R value reference then why does it calls copy constructor as copy constructor takes L value reference. – Hamza Farooqi Dec 12 '17 at 19:34
  • What do you want/expect it to do? – user1810087 Dec 12 '17 at 19:38
  • it should call bydefault move constructor. – Hamza Farooqi Dec 12 '17 at 19:42
  • 2
    There's no move constructor to call. The language chose the safe route of not generating one if there's a different user-provided "rule of five" member because the chance of the compiler doing something wrong was too high and it would break old code. – chris Dec 12 '17 at 19:47
  • ´move´ should be used only when rvalue is temporary or anonymous object that will no longer exist after that expression. – Tracer Dec 30 '17 at 22:58

1 Answers1

3

The compiler will not provide a default move constructor if you provide a user-defined copy constructor, assignment operator, or destructor. The assumption is that if you need special logic for copying or destroying the object it's likely that you will need special logic for moving as well, and simply using the default could be dangerous. If you do not, you can explicitly tell the compiler to provide the default move constructor.

struct CString
{
    CString(const CString& other)
    {
        // Do whatever
    }

    CString(CString&&) = default;
};

Be careful doing this though. For a string wrapper you likely need to set a pointer to nullptr in your move constructor to avoid a double-delete.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52