What's the difference between explicit and implicit assignment in C++

我只是一个虾纸丫 提交于 2019-11-29 03:25:19

They differ if a class has a constructor marked 'explicit'. Then, one of these does not work.

Otherwise, no difference.

Neither of these is an assignment of any kind -- they're both initialization. The first uses copy initialization, and the second direct initialization. (FWIW, I'm pretty sure I've never heard the terms "explicit assignment" or "implicit assignment" before).

Edit: (Mostly in response to Nathan's comment):

Here's a corrected version of the code from your comment:

#include <iostream>

struct Foo { 
    Foo() { 
        std::cout << "Foo::ctor()" << std::endl; 
    } 
    Foo(Foo const& copy) { 
        std::cout << "Foo::cctor()" << std::endl; 
    } 
    Foo& operator=(Foo const& copy) { 
        std::cout << "foo::assign()" << std::endl; 
        return *this; 
    } 
};

int main(int, const char**) { 
    Foo f; 
    Foo b(f); 
    Foo x = b;
    return 0; 
}

The result from running this should be:

Foo::ctor()
Foo::cctor()
Foo::cctor()

If you run it and get an foo::assign(), throw your compiler away and get one that works (oh, and let us know what compiler it is that's so badly broken)!

Only the first one is an assignment. They are both initialization.

Edit: actually, I'm wrong. Neither are assignment.

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