Apply unique_ptr pointer instead of the usual

Hello. Please tell me, how do I replace the code of the design with the use of smart point

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

using namespace std;
int S=4;
class HeavyCar
{
/*....*/
public:
/*.....*/
};
class Fuller
{
HeavyCar**queue;
 
public:
Fuller(HeavyCar**h)
{
 
queue=new HeavyCar*[S];
for(int i=0;i<S;++i)
queue[i]=h[i];
 
}
~Fuller()
{
delete[]queue;
}
};
Think of what you're trying to achieve with your raw pointer to pointers - essentially in class Fuller you want an array of pointers to class HeavyCar of size 4. So in the brave new world of smart pointers lets also get rid of the array and replace it with ... a std::vector!!

So now you have, with #include<memory> throughout:


1
2
3
class HeavyCar{
....
};


and
1
2
3
4
class Fuller{	// not yet finalised, see below; 
	private:
		std::vector<std::unique_ptr<HeavyCar>> queue; 
}

But what about the fact that you still want the 4 HeavyCar (smart) pointers in your queue? Simple, use std::vector's std::initializer_list ctor in the Fuller class ctor initialization list to achieve this objective, so finally:
1
2
3
4
5
6
7
8
9
10
class Fuller{	// finalised  
	private:
		std::vector<std::unique_ptr<HeavyCar>> queue; 
	public:
		Fuller : queue{ std::make_unique<HeavyCar>(), 
				std::make_unique<HeavyCar>(), 
				std::make_unique<HeavyCar>(), 
				std::make_unique<HeavyCar>()} {}
		~Fuller() {}
}


In the above example the default HeavyCar ctor is used but you can also use any other HeavyCar ctor available. std::make_unique uses perfect forwarding, so you can pass HeavyCar's ctor arguments as the function arguments and not the class object itself. Also if the size of queue was quite large you could use an iterator or range loop as well with push_back().

One thing to note though is that std::make_unique is C++14, not C++11, so your compiler needs to be able to support this standard.
Last edited on
Topic archived. No new replies allowed.