Does using callbacks in C++ increase coupling?

前端 未结 8 1836
予麋鹿
予麋鹿 2021-01-03 11:04

Q1. Why are callback functions used?

Q2. Are callbacks evil? Fun for those who know, for others a nightmare.

Q3. Any alternative to

8条回答
  •  爱一瞬间的悲伤
    2021-01-03 11:26

    Callbacks decrease coupling - the invoked party is passed some pointer and it has no idea what's behind it. Callbacks are such a fortunate solution that they are very widespread.

    For example look at sqlite3_exec(). You give it a query and optionally a callback. It executes the query and invokes the callback for each row as it is retrieved. Now it's SQLite's business to execute the query fast and with low resource consumtion and it's only your business to process the retrieved results as you like. You can add them to a container and process all later or you can process them immediately one-by-one or you can fax them somewhere and expect the other party to fax them back - SQLite doesn't care, it's completely abstracted and can just do its job.

提交回复
热议问题