code_junkie

Smart pointers with a library written in C

Nov 14th, 2011
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. std::auto_ptr<cv_ptr> matrix(cv_ptr(cvCreateMat(320, 240, CV_32FC3)));
  2. cvPow(matrix.get()->get()); // one get for the auto_ptr, one for the cv_ptr
  3.  
  4. class cv_auto_ptr {
  5. public:
  6. cv_auto_ptr();
  7. ~cv_auto_ptr();
  8.  
  9. // each method would just be a proxy for the smart pointer
  10. CvMat* get() { return this->matrix_.get()->get(); }
  11. // all the other operators/methods in auto_ptr would be the same, you get the idea
  12.  
  13. private:
  14. auto_ptr<cv_ptr> matrix_; // cv_ptr deletes CvMat properly
  15. }
  16.  
  17. class Mat
  18. {
  19. CvMat* impl;
  20. public:
  21. Mat(/* Constructor Arguments */)
  22. {
  23. impl = cvCreateMat(/* BLAH */);
  24. }
  25. ~Mat()
  26. {
  27. cvReleaseMat(impl);
  28. }
  29. operator CvMat*()
  30. { // Cast opertator. Convert your C++ wrapper object into C object
  31. // when you use it with all those C functions that come with the
  32. // library.
  33.  
  34. return impl;
  35. }
  36. };
  37.  
  38. void Plop(CvMat* x)
  39. { // Some C function dealing with CvMat
  40. }
  41.  
  42. int main()
  43. { // Don't need to dynamically allocate
  44. Mat m; // Just create on the stack.
  45. Plop(m); // Call Plop directly
  46.  
  47. std::auto_ptr<Mat> mP(new Mat);
  48. Plop(*mP);
  49. }
  50.  
  51. struct CvMatDeleter
  52. {
  53. void operator( CvMat* p ) { cvReleaseMat( p ) ; }
  54. };
  55.  
  56. void test()
  57. {
  58. std::tr1::shared_ptr< CvMat > pMat( cvCreateMat(320, 240, CV_32FC3), CvMatDeleter() );
  59. // . . .
  60. }
  61.  
  62. void f() {
  63. try {
  64. CvMat* mat = cvCreateMat(320, 240, CV_32FC3));
  65. // ...
  66. } catch(...) {
  67. cvReleaseMat(mat);
  68. throw;
  69. }
  70. cvReleaseMat(mat);
  71. }
  72.  
  73. namespace cv {
  74.  
  75. class Mat {
  76. public:
  77. enum Type { /* ... */ };
  78. Mat(int w, int h, Type type) {
  79. impl = cvCreateMat(w, h, intFromType(type));
  80. }
  81.  
  82. ~Mat() {
  83. cvReleaseMat(impl);
  84. }
  85.  
  86. void pow() { // wrap all operations
  87. cvPow(impl);
  88. }
  89.  
  90. private:
  91. CvMat* impl;
  92. };
  93.  
  94. }
Add Comment
Please, Sign In to add comment