开发者

Initialize ref. field with ref. parameter: Is a copy made?

I am wondering if a copy is made in the following situation, or if both references will point to the same object. Consider an class with a single const ref field which is initialized from const ref parameter:

class Foo {
 public:
  Foo(const vector<double>& the_doubles) : my_doubles(the_doubles) {}
 private:
  const vector<double>& my_doubles;
}

So, will my_doubles point to the same vector that was passed in to the constructor, or will开发者_如何学JAVA a copy be created?


A reference merely introduces an alias for an existing name (or, sometimes, value). Consider:

int a = 42;
int& b = a;

b is now an alias for a. If we furthermore write

int& c = b;

then c is an alias for b and hence in turn for a.

The same applies in your situation: no copy is ever made.


there is no copy made, both will point to the same obj


It will refer ("point") to the same vector that was passed in the constructor.

Otherwise reference members would be pretty useless!


You are passing by reference. Since it is required to be const there will only be read access to the variables in the vector. Since it is pass by reference no copy will be made. my_doubles will be a const reference to whatever vector was passed into your constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜