一般来说,问题在于对象不仅引入了数据,还引入了行为。
通过手动复制数据,我们可能会破坏对象的固有行为,这可能依赖于复制构造函数。
一个很好的例子是任何共享的或唯一的指针——通过复制它,我们打破了我们在使用它时与该类达成的“交易”。
无论复制过程在语义上是否正确,这样做背后的想法都是错误的,并且违反了对象编程范式。
示例代码:
/** a simple object wrapper around a pthread_mutex
*/
class PThreadMutex
{
public:
/** locks the mutex. Will block if mutex is already locked */
void lock();
/** unlocks the mutex. undefined behavior if mutex is unlocked */
void unlock();
private:
pthread_mutex_t m_mutex;
};
/** a simple implementation of scoped mutex lock. Acquires and locks a Mutex on creation,
* unlocks on destruction
*/
class ScopedLock
{
public:
/** constructor specifying the mutex object pointer to lock
* Locks immediately or blocks until lock is free and then locks
* @param mutex the mutex pointer to lock
*/
ScopedLock ( PThreadMutex* mutex );
/** default destructor. Unlocks the mutex */
~ScopedLock ();
/** locks the mutex. Will block if mutex is already locked */
void unlock();
private:
PThreadMutex* m_mutex;
// flag to determine whether the mutex is locked
bool m_locked;
// private copy constructor - disable copying
ScopedLock(ScopedLock &mutex) { (void)mutex; /* to get rid of warning */ };
};
如果您复制ScopedLock
类,手动解锁它,然后恢复该值并在构造函数中执行另一个解锁,它将导致未定义的行为(或至少在析构函数中出现 EPERM 错误)。