简体   繁体   English

变异和C ++ lambda

[英]Mutations and C++ lambdas

Trying to do functional programming in C++ and getting bit by some kind of mutation rule. 试图用C ++进行函数式编程并被某种突变规则所困扰。

I have this code: 我有以下代码:

  bpf_u_int32 netp, maskp;
  struct in_addr addr;
  // ...code
  auto set_address_string = [&](auto &do_assign) {
    if ((do_assign = inet_ntoa(addr)) == NULL)
      cerr << "error - inet_ntoa() failed" << endl;
    else
      cout << "Some IP: " << do_assign << endl;
  };

  char *net, *mask;
  addr.s_addr = netp;
  set_address_string(net);
  addr.s_addr = maskp;
  set_address_string(mask);
  cout << string(net) << endl;

Which is printing the value of mask when I expected the contents of net to be printed, say that net is supposed to be "10.0.0.0" and mask is supposed to be "255.255.255.0". 当我期望要打印的net的内容时,正在打印mask的值,比如说net应该是“ 10.0.0.0”,而mask应该是“ 255.255.255.0”。

I assume this has to do with the & I used for the variable do_assign? 我认为这与用于变量do_assign的&有关吗?

EDIT: 编辑:

Actual output is: 实际输出为:

Some IP: 10.0.0.0
Some IP: 255.255.255.0
255.255.255.0

but expected was: 但预期是:

Some IP: 10.0.0.0
Some IP: 255.255.255.0
10.0.0.0

From the manual: 从手册中:

The inet_ntoa() function converts the Internet host address in, given in network byte order, to a string in IPv4 dotted-decimal notation. inet_ntoa()函数将Internet主机地址(以网络字节顺序指定)转换为IPv4点分十进制表示形式的字符串。 The string is returned in a statically allocated buffer, which subsequent calls will overwrite. 该字符串在静态分配的缓冲区中返回,后续调用将覆盖该缓冲区。

Both net and mask will point to the same buffer, and, of course, the buffer will contain the result of the last call. netmask都将指向相同的缓冲区,并且当然,缓冲区将包含上一次调用的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM