Files
Catch2/include/internal/catch_ptr.hpp
T

95 lines
2.4 KiB
C++
Raw Normal View History

2012-05-04 07:55:11 +01:00
/*
* Created by Phil on 02/05/2012.
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
#include "catch_common.h"
2013-03-13 08:04:50 +00:00
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
2012-05-15 08:02:36 +01:00
namespace Catch {
2012-05-04 07:55:11 +01:00
// An intrusive reference counting smart pointer.
// T must implement addRef() and release() methods
// typically implementing the IShared interface
template<typename T>
2012-05-15 08:02:36 +01:00
class Ptr {
2012-05-04 07:55:11 +01:00
public:
Ptr() : m_p( NULL ){}
Ptr( T* p ) : m_p( p ){
2012-07-28 20:37:07 +01:00
if( m_p )
m_p->addRef();
2012-05-04 07:55:11 +01:00
}
2012-11-30 18:54:06 +00:00
Ptr( Ptr const& other ) : m_p( other.m_p ){
2012-07-28 20:37:07 +01:00
if( m_p )
m_p->addRef();
2012-05-04 07:55:11 +01:00
}
~Ptr(){
if( m_p )
m_p->release();
}
void reset() {
if( m_p )
m_p->release();
m_p = NULL;
}
2012-05-04 07:55:11 +01:00
Ptr& operator = ( T* p ){
Ptr temp( p );
swap( temp );
return *this;
}
2012-11-30 18:54:06 +00:00
Ptr& operator = ( Ptr const& other ){
2012-05-04 07:55:11 +01:00
Ptr temp( other );
swap( temp );
return *this;
}
2012-11-30 18:54:06 +00:00
void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
T* get() { return m_p; }
const T* get() const{ return m_p; }
T& operator*() const { return *m_p; }
T* operator->() const { return m_p; }
bool operator !() const { return m_p == NULL; }
operator SafeBool::type() const { return SafeBool::makeSafe( m_p != NULL ); }
2013-07-03 19:14:59 +01:00
2012-05-04 07:55:11 +01:00
private:
T* m_p;
};
2013-07-03 19:14:59 +01:00
2012-05-04 07:55:11 +01:00
struct IShared : NonCopyable {
virtual ~IShared();
2012-11-30 18:54:06 +00:00
virtual void addRef() const = 0;
virtual void release() const = 0;
2012-05-04 07:55:11 +01:00
};
2013-07-03 19:14:59 +01:00
2012-11-30 18:54:06 +00:00
template<typename T = IShared>
2012-05-04 07:55:11 +01:00
struct SharedImpl : T {
2013-07-03 19:14:59 +01:00
2012-05-04 07:55:11 +01:00
SharedImpl() : m_rc( 0 ){}
2012-10-12 07:58:17 +01:00
2012-11-30 18:54:06 +00:00
virtual void addRef() const {
2012-05-04 07:55:11 +01:00
++m_rc;
}
2012-11-30 18:54:06 +00:00
virtual void release() const {
2012-05-04 07:55:11 +01:00
if( --m_rc == 0 )
delete this;
}
2013-07-03 19:14:59 +01:00
2012-11-30 18:54:06 +00:00
mutable unsigned int m_rc;
2012-05-04 07:55:11 +01:00
};
2013-07-03 19:14:59 +01:00
2012-05-04 07:55:11 +01:00
} // end namespace Catch
2013-03-13 08:04:50 +00:00
#ifdef __clang__
#pragma clang diagnostic pop
#endif
2012-05-04 07:55:11 +01:00
#endif // TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED