unique_ptr and error 'deleting function'.

Hello,
Been away from c++ for a few months now (apart from answering a few questions on this site). I was trying to see if i could do a simple program using just my memory that involved unique_ptr's, but getting an error:
"attempting to reference a deleted function". I thought that by getting a reference to my pointer would not invoke a copy constructor but i'm clearly wrong.
Any ideas on how best to fix this?
Cheers in advance.

Here's the 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <memory>
#include <vector>

class Shape
{
public:
	virtual void Draw() = 0;
};


class Square : public Shape
{
public:
	virtual void Draw()
	{
		std::cout << "\nDrawing a square.....\n";
	}

};

class Circle : public Shape
{

public:
	virtual void Draw()
	{
		std::cout << "\nDrawing a cirlce.....\n";
	}
};


int main()
{
	typedef std::unique_ptr<Shape> ShapePointer;
	ShapePointer pSquare = std::make_unique<Square>();
	ShapePointer pCircle = std::make_unique<Circle>();

	std::vector<ShapePointer> list;

	list.push_back(pSquare);
	list.push_back(pCircle);
	
	for (ShapePointer& it : list)
	{
		it->Draw();
	}

	return 0;
}
/usr/include/c++/v1/memory:1645:31: error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<Shape, std::__1::default_delete<Shape> >'
Lines 41 and 42 are trying to copy the unique pointers. Consider instead:
41
42
	list.emplace_back(std::move(pSquare));
	list.emplace_back(std::move(pCircle));
http://coliru.stacked-crooked.com/a/7d62ce46682b2581
Last edited on
ahhhhhh.
Cheers LB. Four months of java have killed my c++ brain cells and i have an interview next tuesday :/

Thanks again.
one more question:

A similar member function exists, push_back, which either copies or moves an existing object into the container.


i'm not 100% sure why emplace_back is preferable over push_back?

EDIT: ignore my question. i've googled and understood. Cheers again.
Last edited on
Warning: undefined behaviour; the destructor of Shape must be virtual

Favour: list.push_back( std::make_unique<Square>() ) ;

over:
1
2
ShapePointer pSquare = std::make_unique<Square>();
list.emplace_back(std::move(pSquare));
gotcha.
Cheers fella.
Topic archived. No new replies allowed.