【问题标题】:What's the correct way to pass object pointers to functions that accept objects by reference?将对象指针传递给通过引用接受对象的函数的正确方法是什么?
【发布时间】:2021-02-20 22:52:16
【问题描述】:

C++ 新手,但不是 C

是否有一种正确的方式将对象指针传递给通过引用接受对象的函数?

我举了一个例子,我将取消引用的指针传递给方法foo(),但我想知道这是否被认为是良好的 C++ 实践,或者我是否应该做其他事情。

class Entity {
    public:
        int x;
        Entity(int y) {
            x = y;
        }
};

void foo(Entity& e) {
    std::cout << e.x << std::endl;
}

int main()
{
  
  Entity* e = new Entity(5);
  foo(*e);
}

【问题讨论】:

  • 这段代码对我来说看起来不错,因为它的价值。除了foo 应该采用const Entity&amp; e,因为它不会尝试修改对象。
  • 是的,这行得通。但更好的是:Entity e(5); foo(e);.
  • 一般来说,如果NULL 是一个有效参数,你只会传递一个指针。相反,如果您的函数期望其参数始终是一个有效对象,则使用引用。

标签: c++ pointers pass-by-reference


【解决方案1】:

当您通过引用函数传递参数时,您应该将它们标记为const,以告诉您自己(和其他程序员)该函数不会修改传入的参数。

如果您正在修改内容,则不会将其标记为const

class Entity {
public:
    int x;
    Entity(int y) {
        x = y;
    }
};

// pass arguments here by const reference since you're not modifying anything
void foo(const Entity& e) { 
    std::cout << e.x << std::endl;
}

int main() {
    Entity* e = new Entity(5);
    foo(*e);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2015-09-29
    • 2015-05-22
    • 1970-01-01
    • 2020-05-14
    • 2010-09-20
    • 2012-04-19
    相关资源
    最近更新 更多