Explicit Copy constructor call syntax

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-11 06:28:17

问题


When I declare my copy constructor as explicit, calling it using = instead of () doesn't compile. Here's my code:

class Base
{
    public:
        explicit Base(){cout<<__PRETTY_FUNCTION__<<endl;}
        explicit Base(Base& b){cout <<__PRETTY_FUNCTION__<<endl;}
};

int main()
{
    Base a;
    Base b=a;
}

The compiler says:

error: no matching function for call to ‘Base::Base(Base&)’

If I change it to

Base b(a);

It compiles fine. I thought C++ considers these two styles of instantiations the same. If I remove the explicit keyword it does works both ways. I'm guessing there is some implicit conversion going on when I use =. So what am I missing here?


回答1:


No, they are not the same. C++ Standard section § 12.3.1 [class.conv.ctor]

An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used


Base b(a); // Direct initialization
Base b=a;  // Copy initialization

Copy initialization (using =) doesn't consider explicit constructors, but direct initialization (using ()) does.

You'll have to use a cast or make your constructor non explicit if you want to use copy initialization.



来源:https://stackoverflow.com/questions/28010392/explicit-copy-constructor-call-syntax

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