Re: Same name parameter and data member initialization
On Feb 9, 2:23 pm, Grizlyk <grizl...@yandex.ru> wrote:
James Kanze wrote:
So allocate it:
,name( new char[ strlen(name) + 1 ] )
Or better yet:
,name( duplicateString(name) )
with the necessary functionality in duplicateString.
Note, the code is unsafe for exceptions (in generic case).
It depends on what you mean by "generic case". In the orignal
example, the code was exception safe, and if the above is used
to replace the original example, it is also exception safe.
If the class contains several such pointers, of course, you'll
probably want to factor them out into as many base classes or
smart pointers. boost::scoped_ptr is very good for this, and
std::auto_ptr can also be used. Except, of course, that here,
we are talking about a dynamic array---in almost all cases,
std::string or std::vector< char > would be used, e.g.:
std::vector< char > name ;
and
, name( name, name + strlen( name ) + 1 )
,for example.)
With the kind of pointers you need ideally two-stage sequence
of initializing:
A::A(int id, double pay, char* name ): // auto: //:)
id(id),
pay(pay),
//first stage
//here zero for delete[] safe
name(0)
{
//second stage
A::name=new char[ strlen(name) + 1 ];
}
Which doesn't change anything with regards to my suggestion
(except make the code more complex and more difficult to
understand).
but since C++ does not support control of auto/noauto destructor
calls, you can do like this:
//dtor replacement
A::do_delete(){ delete[] name; }
//dtor
A::~A(){ do_delete(); }
//will call dtor
A& A::operator= (const A&);
//will call dtor replacement
A::A(int id, double pay, char* name ):
id(id),
pay(pay),
//first stage
//here zero for delete[] safe
name(0)
{
try{
//second stage
A::name=new char[ strlen(name) + 1 ];
...
}
catch(...){ do_delete(); throw; }
}
Which is doing things the hard way, and totally unnecessary in
the case in question.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34