Defining copy constructor in a class inherited from POD struct

本小妞迷上赌 提交于 2019-12-08 04:40:38

问题


As you know compiler defines default constructor, copy constructor, assignment operator and destructor for POD structures if it weren't defined manually. Usually (or maybe should I say always) it's a bit copy operation. So I've decided to inherit my class from Win structure BITMAP to provide memory allocation in constructor and freeing in destructor. I haven't used composition 'coz I want to allow using it with some WinAPI functions. Here is a some piece of code:

class CPreviewFrame : public BITMAP
{
public:
   CPreviewFrame( );
   CPreviewFrame( std::size_t width, std::size_t height, UCHAR bytesPerPixel = 3 );
   CPreviewFrame( const CPreviewFrame& frame );

   ~CPreviewFrame( );
   .....
};

And copy constructor is defined something like that:

CPreviewFrame::CPreviewFrame( const CPreviewFrame& frame ):
   BITMAP( static_cast<BITMAP>(frame) ), //question is here
   m_bufferSize( frame.m_bufferSize )
{
   bmBits = new uint8_t[ m_bufferSize ];
   memcpy( bmBits, frame.bmBits, m_bufferSize );
}

So my question is: Is it proper way to call compiler defined copy constructor from inherited structure or should I copy all fields manually in constructor body? Both variants look somewhat strange for me because POD structs can't have constructors despite compiler defines them. How can you call constructor for POD data type if it doesn't exist by definition?

P.S. Code mentioned above compiles well on VS2010.

P.P.S. There is related question to this theme posted by me here.


回答1:


BITMAP(frame) will do the trick with no cast needed as the compiler will know the type of the parent and be able to implicitly convert the argument. Note that if you want to use a cast to explicit show what you're doing, cast as a reference type: BITMAP( static_cast<const BITMAP&>(frame) ),

Also, seriously consider this inheritance. Sometime a year or two from now someone's going to delete one of your CPreviewFrame objects as a BITMAP. Best case they leak memory, worst case you spend days or weeks debugging why the app isn't working right. Composition (with an appropriate interface that may call WinAPI function behinds the scene) isn't typically that complicated to implement and it will more accurately and correctly model your problem here.

Alternately you could use composition and just provide a getter to the bitmap portion (as suggested in a comment). This exposes implementation details of your class but might make it easier to code to the Win API in the short term.



来源:https://stackoverflow.com/questions/7555545/defining-copy-constructor-in-a-class-inherited-from-pod-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!