Re: Calling constructor
From: Alf P. Steinbach (alfps_at_start.no)
Date: Fri, 13 Feb 2004 05:08:34 GMT
On Thu, 12 Feb 2004 20:00:24 +0100, Sylvain <email@example.com> wrote:
>Let's say I have the following code where a class 'pipo' has 8 instances
>foo ( const char * _name):
> name = _name
> const char * name;
Class 'foo' has one very big assumption built-in:
* The lifetime of the character array that is the 'name' of a 'foo'
instance must include the lifetime of the 'foo' instance.
Otherwise the 'foo' instance may be referring to some deallocated
or otherwise cleaned-up memory, no longer a meaningful 'name'.
> for (unsigned int i = 0 ; i < 8; ++i)
> ostringstream ost;
> ost << "MY_FOO_" << i;
> string name = ost.str();
> mf[i] = new foo (name.c_str());
Here the big 'foo' assumption is violated.
The 'foo' constructor is passed a pointer to the internal memory
of a 'string' instance.
Shortly after that 'string' instance goes out of scope and deallocates
the memory now pointed to by the 'foo' instance.
>Is it mandatory to do in such a way: using array of pointers on foo.
>Or may I do it by using plain array of instances of foo?
You can even use a 'std::vector', which is a good habit to get into
(even if it buys you nothing but overhead in this particular case).
>In this case, I have no clue how to process to call the constructor with
>the correct C like string as defined in the exemple...
In the 'foo' constructor you should _copy_ the string.
The easiest way to do that is to use a 'std::string' as member,
instead of a 'char const*'.
When you use 'std::string' you don't have to deal with allocation and