【发布时间】:2012-06-15 22:23:58
【问题描述】:
(注意:这与Usage preference between a struct and a class in D language 有关,但用于更具体的用例)
在为 C++ 代码编写 D 接口时,SWIG 和其他人会执行以下操作:
class A{
private _A*ptr;//defined as extern(C) elsewhere
this(){ptr=_A_new();}//ditto
this(string s){ptr=_A_new(s);} //ditto
~this(){_A_delete(ptr);} //ditto
void fun(){_A_fun(ptr);}
}
假设不需要继承。
我的问题是:使用结构体代替类不是更好吗?
优点是:
1)效率(堆栈分配)
2) 易用性(无需到处写新的,例如:auto a=A(B(1),C(2)) vs auto a=new A(new B(1),new C(2)))?
缺点是: 需要额外的字段 is_own 来通过 postblit 处理别名。
最好的方法是什么? 还有什么需要担心的吗? 这是一个尝试:
struct A{
private _A*ptr;
bool is_own;//required for postblit
static A opCall(){//cannot write this() for struct
A a;
a.ptr=_A_new();
a.is_own=true;
return a;
}
this(string s){ptr=_A_new(s); is_own=true;}
~this(){if(is_own) _A_delete(ptr);}
void fun(){_A_fun(ptr);}
this(this){//postblit;
//shallow copy: I don't want to call the C++ copy constructor (expensive or unknown semantics)
is_own=false; //to avoid _A_delete(ptr)
}
}
请注意,在调用以下函数时需要 postblit:
myfun(A a){}
【问题讨论】: