问题
This question refers only to pre C++11. Consider the following seemingly broken code:
struct X
{
X(){} // default user-provided constructor
private:
X(const X&){}
};
int main()
{
X x = X();
}
Live on Coliru
According to cppreference.com in pre C++11 the default ctor will be called:
The effects of value initialization are:
1) if T is a class type with at least one user-provided constructor of any kind, the default constructor is called;
...
This seem to imply that the copy ctor doesn't necessarily need to be accessible. Is this correct or not? The code above does not compile, so it seems that a copy ctor must be accessible.
回答1:
Value initialization doesn't require it, but you need an accessible copy constructor to do this:
X x = X();
That's copy initialization, which requires an accessible copy constructor. Even though it will not call that copy constructor, it still needs to exist.
C++17 might be the first version where that need will be lifted.
来源:https://stackoverflow.com/questions/34602933/do-we-need-an-accessible-copy-constructor-for-value-initialization-in-c98-03