且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象传递给 C++ 中的函数?

更新时间:2021-10-23 18:19:17

C++11 的经验法则:

按值传递,除非

  1. 你不需要对象的所有权,一个简单的别名就可以了,在这种情况下,你通过const引用,莉>
  2. 你必须改变对象,在这种情况下,使用通过非const左值引用
  3. 您将派生类的对象作为基类传递,在这种情况下,您需要通过引用传递.(使用前面的规则来决定是否通过const 引用.)
  1. you do not need ownership of the object and a simple alias will do, in which case you pass by const reference,
  2. you must mutate the object, in which case, use pass by a non-const lvalue reference,
  3. you pass objects of derived classes as base classes, in which case you need to pass by reference. (Use the previous rules to determine whether to pass by const reference or not.)

实际上从不建议通过指针传递.可选参数***表示为 std::optional(boost::optional 用于较旧的 std 库),并且通过引用可以很好地使用别名.

Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional (boost::optional for older std libs), and aliasing is done fine by reference.

C++11 的移动语义使按值传递和返回即使对于复杂对象也更具吸引力.

C++11's move semantics make passing and returning by value much more attractive even for complex objects.

传递参数通过const引用,除非

  1. 它们将在函数内部进行更改,并且此类更改应反映在外部,在这种情况下,您通过非const 引用
  2. 该函数应该可以不带任何参数调用,在这种情况下,您可以通过指针传递,以便用户可以传递NULL/0/nullptr 代替;应用前面的规则来确定是否应该传递一个指向 const 参数的指针
  3. 它们是内置类型,可以复制传递
  4. 它们将在函数内部进行更改,并且此类更改不应反映在外部,在这种情况下,您可以通过复制strong>(另一种方法是根据之前的规则传递并在函数内部进行复制)
  1. they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-const reference
  2. the function should be callable without any argument, in which case you pass by pointer, so that users can pass NULL/0/nullptr instead; apply the previous rule to determine whether you should pass by a pointer to a const argument
  3. they are of built-in types, which can be passed by copy
  4. they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function)

(这里,传值"被称为传值",因为传值总是在C++03中创建一个副本)

(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)

还有更多内容,但是这几条初学者规则会让您走得更远.

There's more to this, but these few beginner's rules will get you quite far.