Move constructor not being called

Hi,

I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
	class ClassA
	{
		int* p = new int;
	public:
		ClassA() = default;
		ClassA( ClassA&& other)
		{
			p = other.p;
			other.p = nullptr;
		}
		ClassA& operator=( ClassA&& other)
		{
			p = other.p;
			other.p = nullptr;
			return *this;
		}
		~ClassA()
		{
			delete p;
		}
	};

	std::unique_ptr<ClassA> source()
	{
		std::unique_ptr<ClassA> p{ new ClassA{} };
		return p;
	}
	void sourcesAndSinks()
	{
		std::unique_ptr<ClassA> up = source();

		std::unique_ptr<ClassA> pp{ std::move(up) };
		
	}


However, pp's move constructor is never called. I tried placing a breakpoint in ClassA move constructor but debugger tells me that code isn't available for debugging. I am using Visual Studio 2017 with Language set as ISO C++ 17.

What can be going wrong?

Regards,
Juan


 
std::unique_ptr<ClassA> pp{ std::move(up) };

This code calls the std::unique_ptr<ClassA> move constructor.
The ClassA move constructor is not called.

--------------------------------------------------------

 
int* p = new int;

Be careful with new when using default member initializers because they will be used automatically in all constructors that you define (even copy and move constructors) unless you explicitly specify another value to initialize the member with in the member initializer list.

This means that your ClassA move constructor is equivalent to this:

1
2
3
4
5
6
ClassA( ClassA&& other)
:	p(new int)
{
	p = other.p;
	other.p = nullptr;
}

And since the int is never deleted you've just created a memory leak.
Last edited on
Thank you Peter87!!
Topic archived. No new replies allowed.