Do we need an accessible copy constructor for valu

2019-07-11 10:42发布

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条回答
爷的心禁止访问
2楼-- · 2019-07-11 11:42

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.

查看更多
登录 后发表回答