foo.h
#include "class1.h"
class foo{
private:
class1* class1ObjectPointer;
public:
foo();
virtual ~foo();
void foomethod();
}
foo.cpp (VERSION 1)
#include "foo.h"
foo::foo()
{
this->class1ObjectPointer = new class1();
}
foo::~foo()
{
if( this->class1ObjectPointer != NULL ){
delete class1ObjectPointer;
this->class1ObjectPointer = NULL;
}
}
foo::foomethod(){
*(this->class1ObjectPointer) = some_method();
//suppose some method returns an object of class1
}
foo.cpp (VERSION 2)
#include "foo.h"
foo::foo()
{
this->class1ObjectPointer = NULL;
}
foo::~foo()
{
if( this->class1ObjectPointer != NULL ){
delete class1ObjectPointer;
this->class1ObjectPointer = NULL;
}
}
foo::foomethod(){
class1 object;
object = some_method();
//suppose some method returns an object of class1
this->class1ObjectPointer = new class1(object); // copy constructor
}
Which pointer assignment is better in the following cases:
- objects of class1 always have fixed size (e.g. a class with fixed variables in it)
- objects of class1 may have members with variable size (e.g. a class that has a matrix in it which can potentially have different sizes)
Would you suggest any other and better way of doing what I did in these snippets?
It’s probably better (more efficient, and easier to avoid memory leaks) to reassign the object per your first example than to allocate a new object – as demonstrated by the memory leak in your second example.
It looks very much like you don’t need a pointer at all; just embed an object in your class:
Your second situation makes no sense – objects of a particular class are all the same size.
If you really do need to store a pointer (perhaps because you need polymorphism), then the simplest way to handle it is with a smart pointer:
If you really want to manage it yourself, then you’ll need to override the default copy constructor and copy-assignment operator per the Rule of Three, make sure you delete the old object when reassigning the pointer, and be careful about exception safety. And there’s no need to either check for
NULLbefore deleting, or to assignNULLin the destructor.