Re: classes with pointer data members.
On 28 Mrz., 18:13, mpho <tjab...@gmail.com> wrote:
To my earlier question in this thread, a (simpler :-) solution that
worked without throwing all sorts of exceptions is:
How did you come to the conclusion that your code below
might never fail? Since you are using new[], this
operation might fail as well.
T& T::operator=(const T& other){
if (this == &other) return *this;
else {
type *p = new type[s] //s -> size of array pointed to by
'pointer'
std::copy(other.pointer, other.pointer + other.s, p);
s = other.s;
delete [] pointer;
pointer = p;
//similarly for any other pointers.
}
return *this;
}
See "Programming with Exceptions" by Bjarne Stroustrup.
Your code snippet does not use a better/safer strategy as
any of the answers you got so far. In contrast, this code
will leak memory, if the copy c'tor of type can throw.
As recommended by Mathias Gaunard, you should probably use
std::vector<type> instead. Most implementations I know of
can even better optimize your code as your hand-crafted
vector via new[]/delete[] will do - *and* will be exception-safe.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]