c++ - C++中的困惑

标签 c++ pass-by-reference parameter-passing

我是 C++ 的新手,目前正在学习它。我有几个问题..

  1. void DoSomething(const Foo& foo)void DoSomething(Foo foo) 之间有什么区别? 如果我们不指定 & 那么实例Foo 的将按值传递(而不是引用)。除了在编译时不检查外,它与在参数中使用 const + & 相同。那么,为什么有 const + & 成为没有 & 和 const 的争论的最佳实践?

    在 C# 中,传递对象是“通过引用”,但似乎不是在 C++ 中。

  2. 我正在读的书说成员函数通过引用传递隐式参数..

    谁能给我隐式参数的样本和引用?我知道如果我们想通过引用传递对象,我们需要使用 & (例如 Foo(Person& p) )但是 C++ 是如何通过引用传递对象的隐式参数的呢?我读到 C++ 中的隐式参数就像 Contructor(string str) : strMemberVariable(str) {} ...

  3. 在 C++ 中,数组是唯一通过引用传递的吗?

  4. 为什么我不能在 Foo 类中使用 Foo fInstance

例子:

class Foo {

public:    
    Foo() { }

    Foo(const Foo& f) : fInstance(f) {   }  

    Foo fInstance;      
};

提前致谢。

最佳答案

1 What is the differences between void DoSomething(const Foo& foo) and void DoSomething(Foo foo)? If we don't specify & then the instance of Foo will be passed by value ( not reference ). It will be the same as having const + & in argument except no checking at compile-time. So, Why does having const + & become the best practice over the argument without & and const?

In C#, passing the object is "by reference" but seems like it's not in C++.

有几个区别,按重要性排序:

  • 如果无法复制对象Foo,则需要通过引用传递
  • 如果对象 Foo 是一个基类,您应该通过引用获取它,以便用户可以使用派生类调用您的函数
  • 即使您拥有对它的 const 引用,实际对象的值也可能会改变
  • 效率,复制用户类型可能代价高昂,但编译器可能足够聪明,可以解决这个问题,所以...

2 The book that I'm reading said that Member functions pass the implicit parameter by reference..

Could anyone give me the sample of implicit parameter and by reference? I know that if we want to pass the object by reference, we need to use & (e.g. Foo(Person& p) ) but how come C++ pass the object by reference for implicit parameter? I read that implicit parameter in C++ is like Contructor(string str) : strMemberVariable(str) {} ...

隐式参数应该理解为this,也就是对象本身。它通过引用有效传递,因为您可以在成员函数中修改它的状态。

按照Konrad的说法:注意this本身不是通过引用传递的,this是对象的引用(指针) , 但按值传递。您不能随心所欲地更改对象的内存地址;)

3 Is the array the only that pass by reference in C++?

他们不是。您将看到数组元素发生变化,但数组(结构)不会发生变化。

根据 FredOverflow 的评论,一个例子:

void fun(int* p, size_t size);

int main(int argc, char* argv[])
{
  int array[15];
  fun(array, 15);
}

我们不知道 fun 做了什么,它可能会改变 array 的一些元素,但无论它做什么,array 都会保留15 个整数的数组:内容改变,结构不变。

因此,要更改 array,我们需要另一个声明:

void changer(int*& array, size_t& size);

这样我们就可以同时更改内容和结构(并传回新的大小)。当然,我们只能使用动态分配的数组调用此函数。

4 Why can't I use Foo fInstance in Foo class?

因为那是无限递归。从编译器的角度考虑一下,并尝试猜测 Foo 的大小。 Foo 的大小是其属性大小的总和,可能还加上一些填充和类型信息。此外,对象大小至少为 1,以便可以对其进行寻址。那么,如果 Foo 有一个 Foo,它的大小是多少:)?

通常的解决方案是使用智能指针:

class Foo
{
public:

private:
  std::unique_ptr<Foo> mInstance;
};

因为指针的大小不依赖于所指向对象的大小,所以这里没有进行递归:)

关于c++ - C++中的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3124350/

相关文章:

c++ - 如何声明第三方定义的不透明匿名结构?

c++ - Win32 C API : Alternative to broken execl*() family of functions?

python - PyQt:如何使用 QAxWidget 通过引用发送参数

c++ r值引用应用于函数指针

php - PHP 引用赋值的误解

负整数的 C++ 优化

C++ 方法覆盖

c++ - 在 Android 上使用 OpenCV 将 cv::Mat 传递给 JNI 时出错

java - 尝试在android中传递参数

swift - 类名作为 swift 中的函数参数