Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c++ - private copy constructor/assignment operator and copy-initialization

This is a followup of this question

in the following code, why does line 1 compiles while line 2 and 3 does not (using visual C++ 2010)

class ABase
{
protected:
    ABase() {}
    ~ABase() {}
private:
    ABase( const ABase& );
    const ABase& operator=( const ABase& );
};

class A : ABase
{
};

class B
{
public:
    B() {}
    ~B() {}
private:
    B( const B& );
    const B& operator=( const B& );
};

int main( void )
{
    A a = A(); // line 1
    A a2( a ); // line 2
    B b = B(); // line 3

    return 0;
}

(note BA is a copy of boost::noncopyable)

edit: My problem is not to know why line 2 and 3 does not compile (I know that, the copy constructor is private), but why line 1 does.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Indeed line 1 should not compile.

Apparently vc++2010 has problems enforcing language rules in this case (may be because they're related to a base class and not to the object itself).

g++ diagnostic message about line 1 is very clear

ncopy.cpp: In copy constructor ‘A::A(const A&)’:
ncopy.cpp:7: error: ‘ABase::ABase(const ABase&)’ is private
ncopy.cpp:12: error: within this context
ncopy.cpp: In function ‘int main()’:
ncopy.cpp:27: note: synthesized method ‘A::A(const A&)’ first required here 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...