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 ?
2 Réponses
+ 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.
+ 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; 
    } 
 






