0

Using Apple clang version 12.0.0 (clang-1200.0.32.29) -std=c++17, the following code does not compile

struct C {
  C()  {}
  C(C&& other) {std::cout << "move\n";}
  //C(const C& other) {std::cout << "copy\n";}
  void operator()(float x) {}
};

int main(){
  std::function<void(float)> f = C();
}

unless I uncomment the copy constructor. Yet when I run the executable, I find out that the copy constructor is never called.

Does the standard require that a copy constructor be defined in this scenario? If so, why? If not, why does the code not compile?

I have resisted adding a copy constructor because, in the code from which this minimal example was derived, the class has a member of type std::unique_ptr.

songyuanyao
  • 163,662
  • 15
  • 289
  • 382
pnklein
  • 733
  • 5
  • 7
  • *Yet when I run the executable, I find out that the copy constructor is never called.* -- You can't determine whether the code is valid this way. The code must follow the rules of C++, even though the compiler may optimize away the copy. – PaulMcKenzie Jun 09 '21 at 02:12
  • @cpplearner Thank you! That is what I needed to know. Do you want to form an answer that I can upvote? Or is my question too similar to the one you cited? – pnklein Jun 09 '21 at 02:32

0 Answers0