Re: Silver bullet for C++ memory management ?
On Mar 19, 2:52 pm, MN <nguyent...@gmail.com> wrote:
Hi there,
I've been using smart pointer to save my efforts on dealing with
memory management in C++. A sample of code is as below.
//////// begin of code /////////
#define PtrOf(X) boost::shared_ptr < X >
prefer typedef
...
class Animal {
public:
Animal(const std::string& name) { _name = name; }
private:
std::string _name;};
typedef boost::shared_ptr<Animal> PtrAnimal;
...
PtrOf(Animal) animal(new Cow());
PtrAnimal animal(new Animal("Cow") );
...
//////// end of code /////////
It has been worked well, however there are two ugly problems:
1) If we put the macro in a class interface, it's really ugly and
obstruct the clarity of the interface.
class Farm {
public:
Farm(PtrOf(Animal) a);
becomes Farm(PtrAnimal a);
};
2. More seriously, if we have to use some 3rd party libraries which do
not use the same convention, instead using bare pointer, we have a
bigger problem to deal with.
Use a wrapper to handle the gory details.
void LibWrapper(PtrAnimal a)
{
libCall( a.get() );
}
My question is whether there is a way to address C++ memory management
to reduce it to a painless task ( as Java and C# ) without using 3rd
party garbage collector ?
Sure. Just allocate memory an never worry about freeing it :^)
OK that's not a good strategy. I don't know of a any easy way to
do it. That's probably one major reason why garbage collection
was added to Java and C#.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]