I have the following issue:
I want to delete a mother object if an exception is thrown inside the constructor of one of its members. How do I do that?
The following does NOT what I want. Just you have something to refer to...
#include <iostream>
struct A
{
A(int i)
:mem(0)
{
try{
if(i > 9) throw 0;
}catch(int x) { std::cout << "mem max size 9\n"; return;}
mem = i;
}
int mem;
};
struct B
{
B(int i)
:mem(i)
{
}
const A mem;
};
int main()
{
B b1(2);
B b2(10);
std::cout << "b1: " << b1.mem.mem << std::endl;
std::cout << "b2: " << b2.mem.mem << std::endl;
}
//~ output:
//~ mem max size 9
//~ b1: 2
//~ b2: 0
Edit
Following this link I changed my code as follows
#include <iostream>
struct A
{
A(int i)
:mem(0)
{
if(i > 9) throw 0;
else mem = i;
}
int mem;
};
struct B
{
B(int i)
try
:mem(i)
{
}
catch(int e)
{
std::cerr << "Error #" << e << std::endl;
}
const A mem;
};
int main()
{
B b1(2);
B b2(10);
}
//~ output:
//~ Error #0
//~ terminate called after throwing an instance of 'int'
//~ Aborted
But, I don't want the program to abort... how can I prevent that?
If I do it like this, the program does not get aborted but the B object is being constructed despite the exception...
#include <iostream>
struct A
{
A(int i)
:mem(0)
{
try
{
if(i > 9) throw 0;
}
catch(int e)
{
std::cerr << "A Error #" << e << std::endl; return;
}
mem = i;
}
int mem;
};
struct B
{
B(int i)
try
:mem(i)
{
}
catch(int e)
{
std::cerr << "Error #" << e << std::endl;
}
const A mem;
};
int main()
{
B b1(2);
B b2(10);
std::cout << "b1: " << b1.mem.mem << std::endl;
std::cout << "b2: " << b2.mem.mem << std::endl;
}
//~ A Error #0
//~ b1: 2
//~ b2: 0
and if I re-throw in the catch in A the program gets aborted again...