I got into the smart pointer business and I have question which best demonstrated on a code taken directly from the forums tutorial. Namely the inheritance example polygon:
< // dynamic allocation and polymorphism
#include <iostream>
#include <memory>
using namespace std;
class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area (void) =0;
void printarea()
{ cout << this->area() << '\n'; }
};
class Rectangle: public Polygon {
public:
Rectangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height; }
};
class Triangle: public Polygon {
public:
Triangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height/2; }
};
int main () {
//This works just fine
//Polygon * ppoly1 = new Rectangle (4,5);
//Polygon * ppoly2 = new Triangle (4,5);
//this works just fine as well
Polygon * ppoly1 = nullptr;
Polygon * ppoly2 = nullptr;
ppoly1 = new Rectangle (4,5);
ppoly2 = new Triangle (4,5);
//This does not work at all
///error: conversion from Rectangle to polygon
//unique_ptr<Polygon> ppoly1 = new Rectangle (4,5);
//unique_ptr<Polygon> ppoly2 = new Triangle (4,5);
//This works just fine
unique_ptr<Polygon> ppoly1(new Rectangle (4,5));
unique_ptr<Polygon> ppoly2(new Triangle (4,5));
// this one fails as well:
//error :no match for 'operator='
unique_ptr<Polygon> ppoly1 = nullptr;
ppoly1=new Rectangle (4,5);
If you look at the documentation for std::unique_ptr::operator=, it only allows assigning (copy or move) another unique_ptr or nullptr. Other than that you need to use the ctor.
very comprehensive intro to unique pointers! I am using C++11 at the moment but this will change very soon!
The move semantics was a good point! I made that error!