verdude verdude - 11 days ago 4x
C++ Question

Why is the copy constructor called when I am not passing an instance of the class?

I have a class Server which has a constructor:

Server::Server(int port) {
// initialize some class variables
port_ = port;

I try to create an instance of the class like so:

int main(int argc, char** argv) {
int port = 3000;
Server server = Server(port);

And I get this compile error:

server_main.cpp:32:32: error: use of deleted function ‘Server::Server(const Server&)’
Server server = Server(port);

Now, I understand why the copy constructor was implicitly deleted, but why is it being called?

The error goes away if I add a copy constructor to the class. Is there any other way to avoid this?


Server server = Server(port); is copy initialization, which requires copy/move ctor to be accessible.

You could change it to direct initialization:

Server server(port);