educative.io

Educative

Move constructor works with const member

Hi, its written that move constructor also won’t work with a class having const member. But it does seem to work.
#include
using namespace std;

class ConstClass {
public:
	ConstClass(int data): data_(data) {}

	int data() const { return data_; }

private:
	const int data_;
};

int main() {
	ConstClass c1{ 100};
	ConstClass c2{ 200};
	ConstClass c3{ ConstClass(2) };

	cout << c3.data() << endl;
	return 0;
}

Course: https://www.educative.io/collection/10370001/4779553429389312
Lesson: https://www.educative.io/collection/page/10370001/4779553429389312/4541789693804544

Hello @Pankaj_Singh, It seems like you have not used the move constructor in your example code. The correct way to use the move constructor will look like this.

    `Move(Move&& source) //move constructor

    :data{ source.data } //base initializer list
    {
        cout << "Move Constructor for "

             << *source.data << endl;

        source.data = nullptr;
    }`

Hi, Thanks for you reply.

But my question is, as per the course, if we have any const member, compiler implicitly deletes move semantics.

But in the code snippet I have included, c3 object should be created with move constructor, right? (R value). And this works, so either

  1. Implicit move constructor works .
  2. Or compiler must have called implicit copy constructor if move counterpart is deleted.

@Pankaj_Singh Your second statement is correct. Compiler use copy semantics ( = ) for all move requests because const variables lose their ability to use move semantics.