Move constructor not working with const string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Move constructor not working with const string

Hi all Please refer below code : https://code.sololearn.com/cEyO8r8PktRr/?ref=app I can see that code works perfectly fine if string s is not declared const... Here , s being non const , I can observe s get deleted and prints nothing where as it print proper value for S2 Issue is in case of string s declared as const... Why move constructor is not giving compile time error? Does move not need non const objects ?

16th Mar 2021, 7:31 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 3
It's because std::string's move constructor does not take a const rvalue. A move constructor requires the modification of the original object and since that object is const you cannot move so it calls the copy constructor instead.
16th Mar 2021, 8:13 PM
Dennis
Dennis - avatar
+ 3
// C++ program with declaring the // move constructor #include <iostream> #include <vector> using namespace std;   // Move Class class Move { private:     // Declare the raw pointer as     // the data member of class     int* data;   public:         // Constructor     Move(int d)     {         // Declare object in the heap         data = new int;         *data = d;         cout << "Constructor is called for "              << d << endl;     };       // Copy Constructor     Move(const Move& source)         : Move{ *source.data }     {           // Copying the data by making         // deep copy         cout << "Copy Constructor is called -"              << "Deep copy for "              << *source.data              << endl;     }       // Move Constructor     Move(Move&& source)         : data{ source.data }     {           cout << "Move Constructor for "              << *source.data << endl;         source.data = nullptr;     }  
16th Mar 2021, 8:00 PM
Qusi AL-Hejazi
Qusi AL-Hejazi - avatar