Re: Calling constructor
From: Alf P. Steinbach (alfps_at_start.no)
Date: 02/13/04
- Next message: Victor Bazarov: "Re: Differences between "class::member" & "object.member""
- Previous message: Victor Bazarov: "Re: Problem with virtual member function pointer (how to invoke the base?!)"
- In reply to: Sylvain: "Calling constructor"
- Next in thread: John Carson: "Re: Calling constructor"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 13 Feb 2004 05:08:34 GMT
On Thu, 12 Feb 2004 20:00:24 +0100, Sylvain <sylvain.boucher@aitb.org> wrote:
>Let's say I have the following code where a class 'pipo' has 8 instances
>of foo:
>
>class foo
>{
>foo ( const char * _name):
> name = _name
> {
>
> }
>private:
> 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'.
>class pipo
>{
>foo *mf[8];
>pipo()
>{
> 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.
No.
>Or may I do it by using plain array of instances of foo?
Yes.
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
deallocation.
- Next message: Victor Bazarov: "Re: Differences between "class::member" & "object.member""
- Previous message: Victor Bazarov: "Re: Problem with virtual member function pointer (how to invoke the base?!)"
- In reply to: Sylvain: "Calling constructor"
- Next in thread: John Carson: "Re: Calling constructor"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|