Reputation: 73
A moments ago, I was exercising with design patterns, and recently, I've tried to implement a Factory Method pattern. My friend told me that I should always use smart pointers, so I've tried it, but my compiler throws an exception called "Access Violation". What am I doing wrong? There is one interface called "Shape", three inheriting classes from it, Client class and main function. I've tried to do everything with smart pointers, but I'm a little bit unsure, if I'm doing it right.
#include <iostream>
#include <memory>
class Shape
{
public:
virtual void printShape() = 0;
static std::shared_ptr<Shape> Create(int num);
};
class Triangle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Triangle. \n";
}
};
class Circle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Circle. \n";
}
};
class Rectangle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Rectangle. \n";
}
};
class Client
{
private:
std::shared_ptr<Shape> shape;
public:
Client()
{
shape=Shape::Create(1);
}
std::shared_ptr<Shape>getShape()
{
return shape;
}
};
std::shared_ptr<Shape> Shape::Create(int num)
{
switch (num)
{
case 1:
return std::shared_ptr<Circle>();
break;
case 2:
return std::shared_ptr<Triangle>();
break;
case 3:
return std::shared_ptr<Rectangle>();
break;
}
}
int main()
{
std::shared_ptr<Client> client;
std::shared_ptr<Shape> shape = client->getShape();
shape->printShape();
}
Upvotes: 2
Views: 100
Reputation: 172864
The return statements like return std::shared_ptr<Circle>();
just returns an empty std::shared_ptr
, which contains nothing. Dereference on it like shape->printShape();
leads to UB.
You should construct an object and make it managed by std::shared_ptr
. E.g.
std::shared_ptr<Shape> Shape::Create(int num)
{
switch (num)
{
case 1:
return std::make_shared<Circle>();
break;
case 2:
return std::make_shared<Triangle>();
break;
case 3:
return std::make_shared<Rectangle>();
break;
}
}
And also for client
.
std::shared_ptr<Client> client = std::make_shared<Client>();
Or just
Client client; // it seems no need to use shared_pointer for client
std::shared_ptr<Shape> shape = client.getShape();
Upvotes: 6
Reputation: 21
You make pointers without objects You have to write
return std::shared_ptr<Circle>(new Circle());
Or better use std::make_shared
return std::make_shared<Circle>();
Upvotes: 2