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

前端 未结 3 1396
[愿得一人]
[愿得一人] 2020-12-16 14:04
int value = 5; // this type of assignment is called an explicit assignment
int value(5); // this type of assignment is called an implicit assignment
<
相关标签:
3条回答
  • 2020-12-16 14:11

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

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

    0 讨论(0)
  • 2020-12-16 14:14

    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)!

    0 讨论(0)
  • 2020-12-16 14:23

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

    Otherwise, no difference.

    0 讨论(0)
提交回复
热议问题