1. 当声明一个类时,编译器会自动为该类生成默认构造函数,复制构造函数,赋值操作符以及析构函数;
2.自动生成的各个函数和操作符都是public的;
3.当声明一个类不允许复制时,可以将一个类的复制构造函数和赋值操作符声明为private,但是实际中,一般写一个noncopyable类,让不允许使用复制构造函数的类继承于该noncopyable类,boost类就实现了那么一个基类,代码很简单如下:
// Boost noncopyable.hpp header file --------------------------------------//
// (C) Copyright Beman Dawes 1999-2003. 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)
// See http://www.boost.org/libs/utility for documentation.
#ifndef BOOST_NONCOPYABLE_HPP_INCLUDED
#define BOOST_NONCOPYABLE_HPP_INCLUDED
namespace boost {
// Private copy constructor and copy assignment ensure classes derived from
// class noncopyable cannot be copied.
// Contributed by Dave Abrahams
namespace noncopyable_ // protection from unintended ADL
{
class noncopyable
{
protected:
noncopyable() {}
~noncopyable() {}
private: // emphasize the following members are private
noncopyable( const noncopyable& );
const noncopyable& operator=( const noncopyable& );
};
}
typedef noncopyable_::noncopyable noncopyable;
} // namespace boost
#endif // BOOST_NONCOPYABLE_HPP_INCLUDED
//
// main.cpp
// nocopy
//
// Created by busyfisher on 13-6-17.
// Copyright (c) 2013年 busyfisher. All rights reserved.
//
#include <iostream>
#include <string>
class nocopyable{
protected:
nocopyable(){}
~nocopyable(){}
private:
nocopyable(const nocopyable&);
const nocopyable& operator =(const nocopyable&);
};
class person:public nocopyable{
public:
person():age(0){}
void set_name(const std::string& str){
name = str;
}
void set_age(const int& _age){
age = _age;
}
private:
int age;
std::string name;
};
int main(){
person p1;
p1.set_age(20);
p1.set_name("Liming");
person p2(p1);//错误,call to implicitly-deleted copy constructor of 'person'}