开发者

Chain initialization without temporary pointers

开发者 https://www.devze.com 2023-02-19 12:55 出处:网络
An object of class A is constructed fr开发者_Python百科om an object of class B, which is inherited by class C. How can I create an A object without temporary pointers to the B object?

An object of class A is constructed fr开发者_Python百科om an object of class B, which is inherited by class C. How can I create an A object without temporary pointers to the B object?

B *my_b = new C();
A *my_a = new A( *my_b );
// but *my_b is only used here

Update: The constructor of A takes a B as the argument, not a C.


If you don't need to retain the object of type B and class A constructor copies the object and doesn't instead store a reference to it:

A* my_a = new A( B() );

otherwise you can't do anything much better than what you're doing already.


Don't use new unless you have a reason to.

A my_a = A( B() );

Or if there is a reason to new my_a:

A * my_a = new A( B() );
0

精彩评论

暂无评论...
验证码 换一张
取 消