Can I use new in class definition?
I want to put the new in a switch case structure
like:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Boundary_t *B;
switch(kind) {
case Dirichlet:
B=new Dirichlet_t();
break;
case Neumann:
B=new Neumann_t();
break;
case Cauchy:
B=new Cauchy_t();
break;
}
|
Never used a new in class definition, and feel strange by using new in here. so ask, thank you!
Yes.
Make sure that
Boundary_t has a virtual destructor.
And ideally use a smart pointer instead of a raw pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <memory>
struct Boundary_t { virtual ~Boundary_t() {} /* ... */ } ;
struct Dirichlet_t : Boundary_t { /* ... */ };
struct Neumann_t : Boundary_t { /* ... */ };
struct Cauchy_t : Boundary_t { /* ... */ };
enum kind_t { Dirichlet, Neumann, Cauchy };
std::unique_ptr<Boundary_t> create( kind_t kind )
{
Boundary_t* boundary = nullptr ;
switch(kind)
{
case Dirichlet:
boundary = new Dirichlet_t();
break;
case Neumann:
boundary = new Neumann_t();
break;
case Cauchy:
boundary = new Cauchy_t();
}
return std::unique_ptr<Boundary_t>(boundary) ;
}
int main()
{
auto ptr = create(Neumann) ;
// ....
}
|
and also just know that its only possible in c++11 compliant compilers. otherwise it would have to be in a constructor
Topic archived. No new replies allowed.