- 论坛徽章:
- 0
|
在 WTF 库中:
nonecopable.h
- #ifndef WTF_Noncopyable_h
- #define WTF_Noncopyable_h
- // We don't want argument-dependent lookup to pull in everything from the WTF
- // namespace when you use Noncopyable, so put it in its own namespace.
- namespace WTFNoncopyable {
- class Noncopyable {
- Noncopyable(const Noncopyable&);
- Noncopyable& operator=(const Noncopyable&);
- protected:
- Noncopyable() { }
- ~Noncopyable() { }
- };
- } // namespace WTFNoncopyable
- using WTFNoncopyable::Noncopyable;
- #endif // WTF_Noncopyable_h
复制代码
拷贝构造和赋值构造搞成private, 然后让其他类派生 ,派生类应该没法调用拷贝构造和赋值构造了吧,
可这么做有什么意义,有什么具体的应用场景么?哪位能举个小case么?
ownptr.h
- #ifndef WTF_OwnPtr_h
- #define WTF_OwnPtr_h
- #include <algorithm>
- #include <wtf/Assertions.h>
- #include <wtf/Noncopyable.h>
- namespace WTF {
- template <typename T> class OwnPtr : Noncopyable {
- public:
- explicit OwnPtr(T* ptr = 0) : m_ptr(ptr) { }
- ~OwnPtr() { safeDelete(); }
- T* get() const { return m_ptr; }
- T* release() { T* ptr = m_ptr; m_ptr = 0; return ptr; }
- void set(T* ptr) { ASSERT(!ptr || m_ptr != ptr); safeDelete(); m_ptr = ptr; }
- void clear() { safeDelete(); m_ptr = 0; }
- T& operator*() const { ASSERT(m_ptr); return *m_ptr; }
- T* operator->() const { ASSERT(m_ptr); return m_ptr; }
- bool operator!() const { return !m_ptr; }
- // This conversion operator allows implicit conversion to bool but not to other integer types.
- typedef T* (OwnPtr::*UnspecifiedBoolType)() const;
- operator UnspecifiedBoolType() const { return m_ptr ? &OwnPtr::get : 0; }
- void swap(OwnPtr& o) { std::swap(m_ptr, o.m_ptr); }
- private:
- void safeDelete() { typedef char known[sizeof(T) ? 1 : -1]; if (sizeof(known)) delete m_ptr; }
- T* m_ptr;
- };
-
- template <typename T> inline void swap(OwnPtr<T>& a, OwnPtr<T>& b) { a.swap(b); }
- template <typename T> inline T* getPtr(const OwnPtr<T>& p)
- {
- return p.get();
- }
- } // namespace WTF
- using WTF::OwnPtr;
- #endif // WTF_OwnPtr_h
复制代码
void safeDelete() { typedef char known[sizeof(T) ? 1 : -1]; if (sizeof(known)) delete m_ptr; }
这句怎么这么怪异?
[ 本帖最后由 windyrobin 于 2009-7-16 15:48 编辑 ] |
|