0

First try:

class Local {
 public:
    Local() {std::cout << "default\n"; }
    Local(const Local&) {std::cout << "copy ctor!\n"; }
};

int main() {
    // Direct list init -> Value init -> Default init
    Local obj{};

    // Copy initialization -> non-explicit copy ctor
    Local obj_one = obj;

    // Temporary value init -> Copy initialization -> non-explicit copy ctor 
    Local obj_two = Local{};

    return 0;
}

Second try (add explicit):

class Local {
 public:
    Local() {std::cout << "default\n"; }
    // now here explicit
    explicit Local(const Local&) {std::cout << "copy ctor!\n"; }
};

int main() {
    Local obj{};

    // (1) Error, copy-initialization does not consider explicit constructor
    Local obj_one = obj;

    // (2) Why there is no error?
    Local obj_two = Local{};

    return 0;
}

In case (1) everything - fine. But what about case (2)? I read in this post that in case (2):

Value-initializes a temporary and then copies that value into c2 (Read 5.2.3/2 and 8.6/14). This of course will require a non-explicit copy constructor (Read 8.6/14 and 12.3.1/3 and 13.3.1.3/1 ).

clang++ -std=c++17 main.cpp
Gusev Slava
  • 2,136
  • 3
  • 21
  • 26

0 Answers0