mpho wrote:
> This seems straightforward but gives this runtime error: terminate
> called after throwing an instance of 'std::bad_alloc' , what() :
> std9bad_alloc . I have:
>
> class X {
> int sz;
> T *ptr;
Unknown type T.
>
> public:
> X(int s, T *p) : sz(s), ptr(new T[s])
> {
> assert(ptr != NULL);
What's the purpose of the assert here? Do you want to make sure the
standard allocator is working correctly? Unless you have overloaded
new[] and implemented it incorrectly, ptr cannot ever be null here.
> for (int i = 0, i < sz; i++)
Syntax error.
> ptr[i] = p[i];
> }
>
> //other members
>
> ~X() { delete ptr; ptr = NULL; }
Undefined behaviour. What has been allocated via new[] requires
delete[]. Besides, setting ptr to null is as gratuitous as the assert
before. ptr cannot be legally accessed anymore after the destructor has
executed.
> };
>
> class Y {
> X xobj
Missing semicolon.
>
> public:
> Y(int s, T *p) : xobj(s, p) { } //OK?
> //other members
> ~Y() { } //OK?
> };
>
> then
>
> int main(){
>
> ar[10] = {ten values};
Unknown identifer ar. If this is supposed to be its definition, where is
the type?
> Y yobj(10, ar); //problem here(?)
> ......
> .....
Syntax error.
> }
> What's the problem above?
> Thank you.
The main problem is that you submit ill-formed and incomplete code and
expect others to correct the obvious errors and guess the not so obvious
bits that are missing. Without knowing what T is, it is impossible to
say what is going on.
The only glaring runtime problem is the new[]/delete mismatch, but I
doubt that it would cause std::bad_alloc to be thrown (although with
undefined behaviour, anything is possible). The most likely cause is
inifinite recursion somewhere in the code you have not shown, which
causes the free store to be exhausted.
--
Gerhard Menzl
Non-spammers may respond to my email address, which is composed of my
full name, separated by a dot, followed by at, followed by "fwz",
followed by a dot, followed by "aero".
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|