函数参数中的引用
Reference at the function parameter
嗨,我
目前正在学习如何在 c++ 中实现状态机,但我真的不明白我用以下代码为我的函数提供了什么:
void promptfornextevent(elevatorstate& state, int event){
std::cout<<"Current State = "<< state.Description() << std::endl;
}
我在主函数中这样称呼它:
int main(){
...
elevatorstate* currentstate = new state_1stfloor;
promptfornextevent(*currentstate, event);
...
}
我不明白在电梯状态和状态线上使用参考的观点。我的函数究竟从主函数接收什么?我以为我给我的函数一个对象(由当前状态指向)
首先,通过引用传递参数,可以避免创建参数的额外副本。引用指向在 main 函数中创建的同一对象。
如果通过 copy 传递参数,则会调用 elevatorstate
的复制构造函数,并将返回值分配给state
参数。
由于在 promptfornextevent
函数中使用相同的对象,因此即使您返回到 main
函数,在 promptfornextevent
中对对象所做的任何更改都将保留。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用