C ++ structs fully copied or just referenced when assigned with '='?

If the structures are completely copied, then the first cycle is more expensive than the second, because it performs an additional copy for each element v.

vector<MyStruct> v;

for (int i = 0; i < v.size(); ++i) {
    MyStruct s = v[i];
    doSomething(s);
}

for (int i = 0; i < v.size(); ++i) {
    doSomething(v[i]);
}

Suppose I want to write efficient code (as in loop 2), but at the same time I want to name the MyStruct elements that I draw from v (as in loop 1). Can I do it?

+3
source share
5 answers

( ) , =. = , , , . , :

for (int i = 0; i < v.size(); ++i) {
    MyStruct& s = v[i]; //& creates reference; no copying performed
    doSomething(s);
}

, , , . , . ,

void doSomething(structType x);

,

void doSomething(const structType& x);

sizeof structType , sizeof structType*. const , .

+6

, .

, , .

for (int i = 0; i < v.size(); ++i) {
    MyStruct& s = v[i];
    doSomething(s);
}
+3

*. . , ++ , , #.

++, , .

++ . , #, . , - ( ?).

* , , . , .

P.S: , # , .

+2

, .

vector<MyStruct> v;

for (int i = 0; i < v.size(); ++i) {
    MyStruct& s = v[i];
    doSomething(s);
}

, , . doSomething const ref, , .

vector<MyStruct> v;

for (vector<MyStruct>::iterator it = v.begin(); it != v.end(); ++it) {
    doSomething(*it);
}
+2

. '=' . ++ 11 " " " ", ; () . (, , , , , .)

:

  std::vector<int> foo(); // returns a long vector

  std::vector<int> myVector = std::move(foo());

MOVE, , , myVector, , .

However, do not forget about optimizing the return value. It was just a trivial example. RVO actually surpasses the semantics of movement when it can be used. RVO allows the compiler to simply avoid any copying or moving at all when returning the object, instead just using it directly on the stack where it was returned (see http://en.wikipedia.org/wiki/Return_value_optimization ). The constructor is not called at all.

+2
source

All Articles