我们需要一个可访问的复制构造函数用于C ++ 98/03中的值初始化? [英] Do we need an accessible copy constructor for value initialization in C++98/03?

查看:167
本文介绍了我们需要一个可访问的复制构造函数用于C ++ 98/03中的值初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题仅指前C ++ 11 。考虑下面看似破碎的代码:

  struct X 
{
X用户提供的构造函数
private:
X(const X&){}
};

int main()
{
X x = X();
}

Live on Coliru



根据 cppreference.com 在C ++ 11之前的默认ctor将被调用:


价值初始化的效果是:



1)如果T是至少有一个用户提供的类类型




p>这似乎暗示复制ctor不一定需要可访问。这是正确与否?

解决方案

上面的代码不能编译,因此看起来值初始化不需要它,但你需要一个可访问的副本构造函数来执行此操作:

  X x = X 

这是复制初始化,需要一个可访问的复制构造函数。即使它不会调用该复制构造函数,它仍然需要存在。



C ++ 17可能是第一个需要解除的版本。


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.

解决方案

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.

这篇关于我们需要一个可访问的复制构造函数用于C ++ 98/03中的值初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆