On Apr 17, 7:13 pm, Chris Uzdavinis <cuz...@[EMAIL PROTECTED]
> wrote:
> On Apr 16, 5:43 pm, mpho <tjab...@[EMAIL PROTECTED]
> wrote:
>
> > X(int s, T *p) : sz(s), ptr(new T[s])
> > {
> > assert(ptr != NULL);
> > for (int i = 0, i < sz; i++)
> > ptr[i] = p[i];
> > }
>
> Your assertion can never fail, since "new" throws a std::bad_alloc
> when it fails. Therefore, the assertion is misleading and should
> probably be removed.
>
> > //other members
> > ~X() { delete ptr; ptr = NULL; }
> > };
>
> Whoops! Your destructor must perform the array form of deletion:
>
> delete [] ptr;
>
> There is no need to set ptr to NULL afterwords, since as soon as we
> exit the destructor, the object containing ptr no longer exists, and
> its members can never be accessed again.
>
> > int main(){
>
> > ar[10] = {ten values};
> > Y yobj(10, ar); //problem here(?)
> > ......
> > .....
>
> > }
>
> > What's the problem above?
>
> 1) ar has no type
>
> 2) "ten values" is pseudocode
>
> 3) Any uncaught exception (that can unwind the stack past main) will
> cause std::terminate() to be called. Since there are no try/catch
> blocks in your program, and you say an exception is occurring, it
> should be of little surprise that your program terminates.
{ edits: quoted signature and banner (see the end of this article)
removed,
please don't quote extraneous material -- even if the clc++m banner is a
very
fine one. -mod }
Dear all,
The obvious errors have really been mistypes and not deliberate. I
apologize. Thanks for the replies, the problem still persists. The
complete code, excluding the unnecessary stuff by your comments, is:
typedef T //something
class X {
int sz;
T *ptr;
public:
X(int s, T *p) : sz(s), ptr(new T[s])
{
for (int i = 0, i < sz; i++)
ptr[i] = p[i];
}
X(const X& other);
X& operator=(const X&);
~X() { delete [] ptr; }
};
class Y {
X xobj;
public:
Y(int s, T *p) : xobj(s, p) { }
//other members
~Y() { }
};
No problem with copy constructor and assignment.
int main(){
T ar[10] = {1,2,3,4,5,6,7,8,9,10};
Y yobj(10, ar); //problem here(?)
.......
......
}
No try/catch blocks in the program. Should this not work?
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|