简体   繁体   English

在C++转发一个object

[英]Forwarding an object in C++

I am working on a project with an ESP32 and a MCP23017.我正在使用 ESP32 和 MCP23017 开发一个项目。

In the main program I create an object for the MCP and initialize the address.在主程序中,我为 MCP 创建了一个 object 并初始化地址。

Adafruit_MCP23X17 pin_Expander;
const int expander_addr = 0x20; // Adress 0x20 

void setup()
{
    Serial.begin(9600);

    pin_Expander.begin_I2C(expander_addr);
    expander_Init(pin_Expander);
}

Since I use many IOs in the project, I wanted to outsource the initialization of these and wrote a function. I have created a separate header file for the function.由于我在项目中使用了很多IOs,所以想把这些初始化外包,写了一个function。我为function单独创建了一个header文件。

void expander_Init(Adafruit_MCP23X17 pin_Expander)
{
    // Load the GPIOs
    pin_Expander.pinMode(pin1_Motor1, OUTPUT); // I have removed the other pins

    // Set all GPIOs to LOW
    pin_Expander.digitalWrite(pin1_Motor1, LOW); // I have removed the other pins
}

I wonder if this is a legitimate way to pass an object into another function?我想知道这是否是将 object 传递给另一个 function 的合法方式?

Adafruit_MCP23X17 is a C++ class , not some typedef that simulates reference semantics in C , so when you declare your function: Adafruit_MCP23X17是一个 C++ class ,而不是一些模拟 C 中引用语义的 typedef ,所以当你声明你的 function 时:

void expander_Init(Adafruit_MCP23X17 pin_Expander)

you're accepting the object by value , not by reference, which means expander_Init(pin_Expander);您按接受 object,而不是按引用,这意味着expander_Init(pin_Expander); copies pin_Expander and passes in the copy.复制pin_Expander并传入副本。 Any mutations to the copy would not typically affect the original version (unless the class is poorly designed†).副本的任何突变通常不会影响原始版本(除非 class 设计不当†)。

If you want to modify the original version, change the prototype to:如果要修改原始版本,请将原型更改为:

void expander_Init(Adafruit_MCP23X17& pin_Expander)
                                 // ^ added & to make it accept by reference

which means you'll accept a reference to whatever the caller passed, no copies involved, and anything you do to that reference is equivalent to doing it to the original caller-passed object.这意味着您将接受对调用者传递的任何内容的引用,不涉及副本,并且您对该引用所做的任何操作都等同于对原始调用者传递的 object 进行操作。


† I'll note: I wouldn't be surprised if the class was poorly designed, and all instance methods effectively modified global, not per-instance, state (low-level hardware manipulation can often make assumptions like this), so your original code might work just fine, but it's not guaranteed without source code inspection, and it might involve some inefficiencies in the extra copy-and-destroy work that passing-by-reference avoids. †我会注意到:如果 class设计不当,并且所有实例方法都有效地修改了全局而不是每个实例,我不会感到惊讶,state(低级硬件操作通常可以做出这样的假设),所以你的原始代码可能工作得很好,但如果不检查源代码就不能保证它,并且它可能涉及通过引用传递避免的额外复制和销毁工作的一些低效率。

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

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