开发者

question on c++ reference

suppose I have this vector

vector<Object> m;

and then I have the following assignments:

vector<Object> o = m;
vector<Object> k = &m;

vector o will be a COPY of vector开发者_JAVA技巧 m whereas vector k will point to the exact same object as vector m....am I right?

in other words, if I go, o.push_back(something), this will modify vector o but not vector m whereas if I go k.push_back(something), this will indeed modify vector m.

am I wrong or right?


Right for o, wrong for k.

vector<Object> k = &m;
//                 ^^ -- you're taking the address of m here

To make a reference, use

vector<Object>& k = m;
//            ^ -- this makes a reference


Yes, that's conceptually right - except you missed an asterisk or perhaps used an ampersand too much in your sample.

vector<Object> o = m;
vector<Object>* k = &m; // use address-of (&) to create a pointer (*) to m

Pointers always carry this * with them.

Now, m.push_back(...) and k->push_back(...) modify exactly the same object. Note the use of ->, which is used to access a member of a pointer.

If you want to create a reference, you don't use the & - think of it being done implicitly by the compiler:

vector<Object>& k = m; // no address-of here, but k is a reference to m

now, k.push_back() can be used to access m.


This code will not even compile. The type of the expression &m is vector<Object>*, which cannot be assigned to the variable k (its type is vector<Object>).

Possibly you meant to do this:

vector<Object> o = m;
vector<Object>& k = m;

in which case o will be a copy of m (resulting in o and m having copies of the same elements, therefore modifying the contents of one will not affect the contents of the other) and both m and k will refer to the same instance (therefore any change on the instance using one of the two variables will be immediately visible when you refer to the vector using the other variable).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜