Do we need an accessible copy constructor for value initialization in C++98/03?

时间秒杀一切 提交于 2019-12-13 16:16:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!