Replacing ** with boost::scoped_array

Started by
3 comments, last by Codedummie 20 years, 4 months ago
Hi, I'm new to smart pointers and like to change my current program to use these. In some cases I use something like the following to have pointers to an array

class Class 1 {
Class2** t;
    Class1() {
        t = new Class2*[10];
        for(int i = 0;  i < 10; i++) {
            t[i] = new Class2();
            t[i]->doFunction();
        }
    }
};
Question 1: Do I need to use the pointers to the array for effiency or is just the array sufficient? Question 2: How to I replace the ** with smart pointers? I thought of using boost::scoped_array. [edited by - Codedummie on November 28, 2003 3:32:56 AM]
Advertisement
Since what you want is a dynamic container of pointers, I would use something like this:
vector<shared_ptr<t> > t;t.resize(10);for (i=0; i < 10; i++){     t[i] = shared_ptr<t>(new Class2());     t[i]->DoSomething();}


boost::scoped_ptr is only meant for pointers that will never be copied.

[edited by - Ironpoint on November 28, 2003 4:22:14 AM]
you might as well do

class Class1 {    vector<Class2> t;public:    Class1() : t(10) {//initialise vector to size 10        for (i=0; i < t.size(); ++i) {            t[i].DoSomething();        }    }};


You could use a standard algorithm rather than writing out the loop by hand, and someone will probably go on to suggest it. That might be a bit more than you''ll understand.

vector is part of the standard library. It means you don''t have to worry about dynamically allocating memory for arrays. If you store objects rather than pointers to objects then you can let the vector look after all of your memory allocation.
Thanks for the tips. Petewood, do you mean using the iterator? When is is better to use a std::vector and when a smart pointer?

[edited by - Codedummie on December 3, 2003 5:46:06 AM]
quote:Original post by Codedummie
When is is better to use a std::vector and when a smart pointer?


To my mind the main reason for using smart pointers is so that memory is cleared up automatically, including and especially in the case of an exception being thrown.

You would use a smart pointer, such as auto_ptr, to hold a pointer to a single object, not an array. auto_ptr''s destructor calls delete and not delete[] which would be necessary to delete an array. However you don''t need an auto_array as using vector (or whatever container is appropriate) will again automatically clear up its memory in the presence of exceptions.

see Bjarne''s FAQ.

quote:Petewood, do you mean using the iterator?

I meant you could write

std::for_each(t.begin(), t.end(), std::mem_fun( &Class2::doFunction );

for_each takes two iterators given by ''begin'' and ''end'' and then operates on the sequence of objects that they represent. It calls the member function Class2::doFunction on each object.

This topic is closed to new replies.

Advertisement