The best example I can give is with the Three.js library in javascript :
function createMesh(){
var geometry = new THREE.SphereGeometry(10, 5, 5);
var material = new THREE.MeshPhongMaterial();
var mesh = new Mesh(geometry, material);
return mesh;
}
This translates in C++ to :
Mesh* createMesh(){
SphereGeometry* geometry = new SphereGeometry(10, 5, 5);
MeshPhongMaterial* material = new MeshPhongMaterial;
Mesh* mesh = new Mesh(geometry, material);
return mesh;
}
Now, who should have the responsability to delete these 3 pointers. Should it be the user of the library? Or should the geometry and the material be destroyed in the destructor of Mesh, and the user should just delete the Mesh pointer? And if this is the case, how will the player know to not delete his pointers and avoid a double deletion?
Also, what if this happens :
SphereGeometry geometry(10, 5, 5);
MeshPhongMaterial material;
Mesh* mesh = new Mesh(&geometry, &material);
Thanks.
unique_ptr
the user has the complete choice to release the raw pointer or move it into a shared pointer (or any other kind of smart manager). Thereforeunique_ptr
should be the preferred choice.