函数签名,按值传递与引用差异

Function signature, pass by value vs reference difference

我对 C++ 很困惑,因为我一直在使用 python。所以这是例子:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>

    void print(const boost::system::error_code& e,
               boost::asio::steady_timer* t, int count) {
                if (count < 5) {
                    std::cout << count << std::endl;
                    ++(count);
                    t->expires_at(t->expiry() + 
                    boost::asio::chrono::seconds(1));
                    t->async_wait(boost::bind(print,
                    boost::asio::placeholders::error, t, count));
                }
    }
    
    int main() {
        boost::asio::io_context io;
        int count = 0;
        boost::asio::steady_timer t(io, boost::asio::chrono::seconds(1));
        t.async_wait(boost::bind(print,
        boost::asio::placeholders::error, &t, count));
        io.run();
          std::cout << "Final count is " << count << std::endl;
        return 0;
    }

下面的输出是:

0
1
2
3
4
Final count is 0

即使我将签名更改为使用 int& count:

void print(const boost::system::error_code& e,
           boost::asio::steady_timer* t, int& count) 

输出还是一样。 引用运算符有什么意义?

顺便说一句。我知道我可以像 int* count 那样做某事以使最终计数为 5,但这不是我的问题的重点。 顺便说一句2。您有推荐给其他编程语言的人的 oreilly c++ 书籍吗?

boost::bind returns 一个函数对象。它存储一个 count 作为数据成员:

class Functor {
     int copyCount;
};

调用 boost::bind 时复制此 int。 Functor 提供函数调用运算符,它调用绑定的 print 函数:

class Functor {
     int copyCount;
public:
     void operator()() {
         print(...,copyCount);  // [1]
     }
};

in [1] copyCount 被传递给 print 函数。因为是普通类型,所以不管是拷贝传递还是引用传递。如果它是复杂的数据类型,其中复制操作很重,print(ComplexData&) 将是首选,以避免不必要的复制。

通过 boost::ref 你将 count 变量包装成一个指向 int 的指针。所以你对原始对象进行操作。并且可以修改。