Access specifiers(public, protected, and private) can be used to express and enforce higher-level constraints on how a type may be used.
The most common of these techniques is to disallow copying of an object by declaring its copy operations to be private and not defining them:

class NoCopy
{
    public:
        NoCopy(int);
    //...
    private:
        NoCopy(const NoCopy &);//copy ctor
        NoCopy& operator = (const NoCopy &);//copy assignment
};

It’s necessary to declare the copy constructor and copy assignment operator, since otherwise the compiler would declare them implicitly, as public inline members. By declaring them to be private, we forestall the compiler’s meddling and ensure that any use of the operations–whethere explicit or implicit–will result in a compiler-time error:

void aFunc(NoCopy);
void anotherFunc(const NoCopy &);
NoCopy a(12);
NoCopy b(a); //error! copy ctor
NoCopy c = 12; //error implicit copy ctor
a = b; // error! copy assignment
aFunc(a); // error! pass by value with copy ctor
aFunc(12); // error! implicit copy ctor
anotherFunc(a); //OK, pass by reference
anotherFunc( 12 ); // OK
Tags: .
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

RFC: Request For Comments. Orz..

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)
Website(recommended)